我正在创建自己的评论系统,并决定是时候转向 MySQLi。
我想知道的是 - 我这样做正确吗?
我是否在必要时释放并关闭结果?我错过了什么吗?
(还有什么在这个网站上启用语法突出显示?代码示例按钮什么都不做)
$mysqli = new mysqli('localhost', 'username', 'password', 'comments');
if($stmt = $mysqli -> prepare("INSERT INTO comments (topid, body, user, active) VALUES (?, ?, ?, ?)"))
{
$stmt->bind_param('isii', $id, $comment, $userid, $mod);
$stmt->execute();
$stmt->close();
}
else
{
$mysqli->close();
echo '{"status":0,"error":'.json_encode('Database Error - Please try again.').'}';
return;
}
$mysqli->close();
这就是我为我的“while”循环所做的事情:
$comments = array();
$mysqli = new mysqli('localhost', 'username', 'password', 'comments');
$mysqli->set_charset('utf8');
if($stmt = $mysqli -> prepare("SELECT user.id as userid, user.name, comments.id, comments.body, comments.dt FROM comments JOIN user ON comments.user = user.id where comments.postid = ? and comments.topid=0 and comments.active=1 ORDER BY comments.id DESC Limit ?, ?"))
{
$stmt->bind_param('iii', $postid, $offset, $limit);
$stmt->execute();
$res = $stmt->get_result();
$stmt->close();
}
while($row = $res->fetch_assoc())
{
$comments[] = new Comment($row);
}
$res->free();
$mysqli->close();
return $comments;