简体   繁体   中英

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.

$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. 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. Its better to use MySQLi or PDO.

And DATA is a reserved keyword its possible that you get problems if you use it in your query. Rename your table in prefix_data for example.

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. Check your database connection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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