MySQL/PHP连接正常,sql语句不正常;不起作用


MySQL/PHP connection ok, sql statement doesn't work

如何通过php使其回显或打印select语句的结果?

<?php
$username = "root";
$password = "root";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
?>
<?php
$query="SELECT * FROM mydb.product";
$result=mysql_query($query);
echo "$result";
echo $result;
?>

我已经走了这么远,但仍然一无所获。问题出在我的mysql表中吗?或者它落在别的地方了

    <?php
$username = "root";
$password = "root";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$sth = $db->prepare("SELECT * FROM mydb.test;");
$sth->execute();
$result = $sth->fetchAll();
?>
<h1> Im here</h1>
<?php
foreach ($result as $row) {
    echo "<tr>";
    echo "<td>{$row['name']}</td>";
    echo "<td>" . $row['email'] . "</td>";
    echo "</tr>";
}
?>
<h1> Im still here</h1>

感谢所有的帮助

您需要查看结果。比如说,如果每行有3列,那么你的代码看起来像这样:

for($i=0;$i<mysql_num_rows($result);$i++) {
    $row_array=mysql_fetch_row($result);
    echo($row_array[0]." ".$row_array[1]." ".$row_array[2]."<br />");
}

正如注释中所建议的那样,您必须循环获取的结果:

$query="SELECT * FROM mydb.product";
$result=mysql_query($query);
// Add these lines:
while ($row = mysql_fetch_assoc($result)) {
  var_dump($row);
  // each item from the row could be used like this:
  // echo $row['field'];
}

更多信息可在此处找到:http://php.net/manual/en/function.mysql-query.php

请注意,mysql_query是不复杂的,您应该考虑切换到mysqli(http://php.net/manual/en/book.mysqli.php)或PDO(http://php.net/manual/en/ref.pdo-mysql.php)