2014-09-26 121 views
-3

嗨我有问题访问我的服务器我在我的笔记本电脑上使用mysql apache2和php。我的问题是我可以似乎连接到数据库,但无法从数据库中的注册表中获取任何数据。在此先感谢我一直在运行window7。连接php到mysql

<?php 
    $username = "root"; 
    $password = "deslap"; 
    $hostname = "localhost"; 
#connection to the database seems to work and prints connected to MySQL 
    $dbhandle = mysql_connect($hostname, $username, $password)or die("Unable to connect to MySQL"); 
    echo "<br />Connected to MySQL<br>"; 
#select a database to work with 
    $selected = mysql_select_db('registered',$dbhandle)or die("Could not select database"); 

#execute the SQL query and return records. 
    $result = mysql_query("SELECT id, Name FROM registered"); 
    while($row = mysql_fetch_array($result)) 
    { 
     echo "ID:".$row{'id'}." Name:".$row{'name'}."Email: ".$row{'Email'}; 
    } 
?> 
</body> 
</html> 
+7

请不要在新代码中使用'mysql_ *'函数](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php)。 *他们不再维护,并[已正式弃用](https://wiki.php.net/rfc/mysql_deprecation)*。看到[红色框](http://uk.php.net/manual/en/function.mysql-connect.php)?学习[准备的语句](http://en.wikipedia.org/wiki/Prepared_statement),并使用[PDO](http://us1.php.net/pdo)或[MySQLi](http:// us1.php.net/mysqli)。 [这篇文章](http://php.net/manual/en/mysqlinfo.api.choosing.php)将帮助你决定哪些。 – 2014-09-26 14:10:22

+0

在打开'<?php'标签后立即向文件顶部添加错误报告 'error_reporting(E_ALL); ini_set('display_errors',1);'看看它是否产生任何东西。如果数据库连接失败,也将'或者死亡(mysql_error())'变为'mysql_query()'和'死亡'('Could not connect:'。mysql_error())'并且得到真正的错误。 – 2014-09-26 14:12:22

+0

寻找更近一点我不知道是否数据库被命名为注册或表是....还是两者?看起来DB是因为你的选择不会失败。表名是否相同? – 2014-09-26 14:20:47

回答

3

更改大括号框支架(您可以使用{}[],但方括号是传统与数组元素工作) -

echo "ID:".$row['id']." Name:".$row['Name']."Email: ".$row['Email']; 

你也只能选择'id'和Name(将'name'更改为'Name'),所以Email不会被退回。

+1

*方括号和花括号可以互换用于访问数组元素* - http://uk1.php.net/manual/en/language.types.array.php#99015 – George 2014-09-26 14:13:18

+0

True @George,但我喜欢人了解他们正在处理数组元素并使用约定。 – 2014-09-26 14:15:53

+1

错误检查的*破折号将是一个很好的补充这样一个伟大的食谱。你钉了它;) – 2014-09-26 14:17:02