【发布时间】:2011-04-30 04:06:38
【问题描述】:
我在 PHP 中使用旧的 mysql api 已经很长时间了,并且想在我正在处理的一个新项目中开始使用 mysqli 来提高速度和安全性。我浏览了手册并阅读了几个教程,但是我发现了很多关于如何在 mysql 中执行准备好的语句的相互矛盾且有些混乱的信息。
这段代码中是否有不需要的内容,是否缺少任何内容?另外,这是做这样简单的事情的最简单方法吗(对于这样一个简单的任务似乎有点涉及)?
程序:
// build prepared statement
$query = mysqli_prepare($link, "SELECT email FROM users WHERE id = ?");
// bind parameters to statement
mysqli_stmt_bind_param($query, 's', $_GET['id']);
// execute statement
mysqli_stmt_execute($query);
// bind the variables to the result
mysqli_stmt_bind_result($query, $email);
// print the results
while (mysqli_stmt_fetch($query)) {
echo $email;
}
// close the statement
mysqli_stmt_close($query);
// close connection
mysqli_close($link);
面向对象:
// build prepared statement
$query = $link->prepare("SELECT email FROM users WHERE id = ?");
// bind parameters to statement
$query->bind_param('s', $_GET['id']);
// execute statement
$query->execute();
// bind the variables to the result
$query->bind_result($email);
// print the results
while ($query->fetch()) {
echo $email;
}
// close the statement
$query->close();
// close connection
$link->close();
【问题讨论】:
-
我的建议是跳过 MySQLi 直接进入 PDO。
PDOStatement类有一个非常清晰一致的界面 -
你应该跳过mysqli直接去PDO。你为什么坚持使用程序代码?!
-
@Phil,谢谢,我会看看 PDO。
-
@teresko,我一直在做程序,所以我不知道在这个项目上跳入 OO 是否是一个好主意(有点时间紧迫)。
-
哦,刚刚注意到 PDO 只是 OO,所以也许我应该继续尝试一下。不过,从学习的角度来看,我仍然对我原来的问题感兴趣。
标签: php mysql mysqli prepared-statement