我正在尝试创建一个留言板,显示人们通过SQL查询发布的评论。我已成功连接到SQL数据库,但查询未显示任何内容。这有什么不对?
</form>
<h2>Current Posts</h2>
";
$sql = "SELECT * FROM 'guest_booklet' LIMIT 0, 30 ";
if ($numrows > 0) {
echo "$rows ['email']";
while ( $row = mysql_fetch_row($result) ){
$id = $row ['id'];
$name = $row['name'];
$email = $row['email'];
$message = $row['message'];
$message = n12br($message);
echo "<div>
$name - and email is $email <hr/>
$message
<div>";
}
}
mysql_close();
?>
</body>
</html>
答案 0 :(得分:1)
1)更改
$sql = "SELECT * FROM 'guest_booklet' LIMIT 0, 30 ";
要
$sql = "SELECT * FROM `guest_booklet` LIMIT 0, 30 ";
=&GT;使用Backtick
代替single quotes
来封闭表名。
2)您错过了$result = mysql_query($sql);
3)您错过了$numrows = mysql_num_rows($result);
。
4)删除echo "$rows ['email']";
行。它来自哪里的悬念。
Mysql (更新代码)
<?php
$sql = "SELECT * FROM `guest_booklet` LIMIT 0, 30 ";
$result = mysql_query($sql);
$numrows = mysql_num_rows($result);
if ($numrows > 0) {
while ( $row = mysql_fetch_row($result) ){
$id = $row ['id'];
$name = $row['name'];
$email = $row['email'];
$message = n12br($row['message']);
echo "<div>".$name." - and email is ".$email." <hr/>.".$message."<div>";
}
}
mysql_close();
?>
[注意:不推荐使用mysql_ *函数,它们已从PHP 7中删除,当您升级到该版本时,您的代码将停止工作。您不应该使用它们编写新代码,而是使用 mysqli _ * 或 PDO 。]
点击了解How can I prevent SQL-injection in PHP?
Mysqli (更新代码)
<?php
//Connection
$servername = "YOUR-VALUES";
$dbname = "YOUR-VALUES";
$user = "YOUR-VALUES";
$password = "YOUR-VALUES";
$connection = mysqli_connect($servername,$user,$password,$dbname);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `guest_booklet` LIMIT 0, 30 ";
$result = mysqli_query($connection,$sql);
$numrows = mysqli_num_rows($result);
if ($numrows > 0) {
while ( $row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$id = $row ['id'];
$name = $row['name'];
$email = $row['email'];
$message = n12br($row['message']);
echo "<div>".$name." - and email is ".$email." <hr/>.".$message."<div>";
}
}
mysqli_close($connection);
?>
答案 1 :(得分:0)
你在这里缺少很多东西。
<?php
$result = mysql_query($sql);
$numRows
但从未实际设置其值:`$ numRows = mysql_num_rows($ result); $row = mysql_fetch_row(...)
但后者您正在将结果行作为关联数组而不是数字索引读取。您必须使用mysql_fetch_assoc
代替。好像你从其他地方复制了这个,但没有做对。
答案 2 :(得分:0)
错误的事情
答案 3 :(得分:-5)
原始(不正确)回答
因为你有LIMIT 0,30。你告诉MySql从索引30开始给你0结果。
你也在查询字符串而不是结果集上使用mysql_fetch_row,你需要先实际运行查询。
- 我的假设确实是错的,这是你需要做的正确的事情:
"; //What is this?
$sql = "SELECT * FROM 'guest_booklet' LIMIT 0, 30 ";
$result = mysql_query($sql); //you need to add this