php mysqli准备的语句 [英] php mysqli prepared statement
本文介绍了php mysqli准备的语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嘿,我来个快.有什么办法可以将变量包含在准备好的查询中?例如:
Hey, I have a quick one. Is there any way to include a variable into a prepared query? example:
$sql = "SELECT id, title, author, LEFT(description, 40) AS excerpt,
image_small, image_med, date
FROM posts
ORDER BY id DESC
LIMIT $start, $postsPerPage";
$result = $connect->prepare($sql) or die ('error');
$result->execute();
$result->bind_result($id, $title, $author, $excerpt, $image_small, $image_med, $date);
谢谢!
推荐答案
您需要以下内容:
$start = 1; $postsPerPage = 1;
$sql = "SELECT id, title, author, LEFT(description, 40) AS excerpt,
image_small, image_med, date
FROM posts
ORDER BY id DESC
LIMIT ?, ?";
$stmt = $connect->prepare($sql) or die ('error');
$stmt->bind_param('ii', $start, $postsPerPage);
$stmt->execute();
$stmt->bind_result($id, $title, $author, $excerpt, $image_small, $image_med, $date);
while($stmt->fetch()) {
printf('<h1>%s</h1><p>%s <small> by %s on %s</small></p>',
htmlspecialchars($title),
htmlspecialchars($excerpt),
htmlspecialchars($author),
htmlspecialchars($date)
);
}
这会将两个问号都绑定到$start
和$postsPerPage
的整数(i
)值.不要不要直接在准备好的语句中使用变量,因为这会破坏准备好的语句的整个目的(除了消除解析时间)
this binds both question marks to integer (i
) values of $start
and $postsPerPage
. do NOT use variables directly in prepared statements, because that would defeat the whole purpose of prepared statements (apart from eliminating parsing time)
这篇关于php mysqli准备的语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文