dongyishen5796 2013-07-10 14:19
浏览 241

在PHP中解析和回显SQL结果

I'm trying to write a simple PHP guestbook after following a few tutorials online. I am able to write to the database without any issues; however, when I try to parse through the existing comments and "echo" them back to the page, I am not seeing anything being displayed.

Is there an obvious reason for this?

(The code in question starts under "Existing Comments:")

<?php
require_once('includes/config.inc.php');
define('DB_GUEST','guestbook_db');

// Connect
$mysqli = @new mysqli(DB_HOSTNAME,DB_USERNAME,DB_PASSWORD,DB_GUEST);

// Check connection 
if (mysqli_connect_errno()) { 
printf("Unable to connect to database: %s", mysqli_connect_error()); 
exit(); 
} 

// POST
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $now = time();
    $name=($_POST['name']);
    $message =($_POST['message']);

$sql = "insert into comments (name,message,timestamp) values  ('$name','$message','$now')";

    $result = $mysqli->query($sql) or die($mysqli->error.__LINE__);
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Guest Book</title>
</head>
<body>

<h3>Post A Comment:</h3>
<form action="index.php" method="post">
   <strong>Name:</strong><br/> <input type="text" name="name" /><br/>
   <strong>Comment:</strong><br/> <textarea name="message" rows="5" cols="25">           
<textarea><br/>
<input type="submit" value="Go">
</form>

<h3>Exisiting Comments:</h3>

<?php
$sql1 = "select * from guestbook_db.comments";
$allPostsQuery = $mysqli->query($sql1) or die($mysqli->error.__LINE__);

if(!mysql_fetch_rows($allPostsQuery)) {
    echo "No comments were found!";
} else {
while($row = mysql_fetch_assoc($allPostsQuery)) {
echo "<b>Name:</b> {$comment[1]} <br/>";
echo "<b>Message:</b> {$comment[2]} <br/>";
echo "<b>Posted at:</b> " .date("Y-d-m H:i:s",$comment[3]). " <br/><hr/>";
    }
}
?>
</body>
</html>
  • 写回答

1条回答 默认 最新

  • dongqian5639 2013-07-10 14:30
    关注

    Well, first off I have to make an obligatory warning about using $_POST variables directly. Your user could have put anything there, SQL injection strings included. Sanitize your data by using a PDO or parameterizing with mysqli.

    With that out of the way, you are using the variable

    $comment
    

    when you should be using

    $row
    

    as that is what you named the record variable in your while loop. Further, you've called mysql_fetch_assoc (should be mysqli's fetch_assoc() as well, you are mixing up mysql with mysqli - use the mysqli ones) which returns an associative array, not a index numbered one as you are assuming when you call $comment[1] for example.

    In short, just some silly mistakes, but also go and read the docs on PHP's mysqli and about SQL injection.

    评论

报告相同问题?