简体   繁体   English

使用 php*fixed* 查询数据库时遇到问题

[英]Trouble querying database with php*fixed*

I am having trouble selecting my data from a database and displaying it.我无法从数据库中选择我的数据并显示它。 I have looked at tutorials and i still get the same error.我看过教程,但仍然遇到相同的错误。 Some help would be appreciated.一些帮助将不胜感激。 The error i am getting is couldnt fetch result.我得到的错误是无法获取结果。

$sql = "SELECT * FROM data";
$result = mysql_query($sql) or die("couldnt fetch result");
if($result > 0){
while ($rows = mysql_fetch_array($result)){
$username = $rows['username'];
echo $username;
    }
}

Just do that (assuming got it right connecting to DB, first thing to check !)就这样做(假设它正确连接到数据库,首先要检查!)

$sql = "SELECT * FROM `data`"; // data is a reserved keyword, protect it !!!
$result = mysql_query($sql) or die("couldnt fetch result"); // potentially diying here
if($result){
     while ($row = mysql_fetch_assoc($result)){
          $username = $row['username'];
          echo $username;
    }
}

I think the very simple problem is that you check if the $result is greater then 0. But you get an resource.我认为非常简单的问题是你检查$result是否大于 0。但是你得到了一个资源。

$conn = mysql_connect.......

$sql = "SELECT * FROM data";
$result = mysql_query($sql) or die("couldnt fetch result");
if($result){
    while ($rows = mysql_fetch_array($result)){
        $username = $rows['username'];
        echo $username;
    }
}

And if you see your die statement you have an error in your SQL Syntax.如果您看到 die 语句,那么您的 SQL 语法就会出错。 Its very short but its possible that your table doesn't exist in that database you're trying to connect.它很短,但您尝试连接的数据库中可能不存在您的表。 I hope you have a connect before and its not your complete code.我希望你之前有一个连接,它不是你的完整代码。

You use the old mysql functions.您使用旧的 mysql 函数。 Its better to use MySQLi or PDO.最好使用 MySQLi 或 PDO。

And DATA is a reserved keyword its possible that you get problems if you use it in your query.并且DATA是一个保留关键字,如果您在查询中使用它,您可能会遇到问题。 Rename your table in prefix_data for example.例如,在prefix_data重命名您的表。

https://dev.mysql.com/doc/refman/5.7/en/keywords.html https://dev.mysql.com/doc/refman/5.7/en/keywords.html

If what you're getting is literally 'couldnt fetch result' it means your mysql_query() fails, and die statement takes over.如果您得到的是字面上的“无法获取结果”,则意味着您的mysql_query()失败,并且die语句接管了。 Check your database connection.检查您的数据库连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM