嘿,我有一个很快的。有没有办法将变量包含在准备好的查询中?示例:
$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);
谢谢!
发布于 2011-03-21 08:20:22
您需要以下内容:
$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
)值。不要在预准备语句中直接使用变量,因为这将违背预准备语句的全部目的(除了消除解析时间之外)
发布于 2011-03-21 08:23:59
发布于 2011-03-21 08:20:15
如果我没记错的话,您必须使用bindParam并将查询中的变量替换为问号
$sql = "SELECT id, title, author, LEFT(description, 40) AS excerpt,
image_small, image_med, date
FROM posts
ORDER BY id DESC
LIMIT ?, ?";
$result = $connect->prepare($sql) or die ('error');
$result->bindParam(1, $start);
$result->bindParam(2, $postsPerPage);
你可以在http://php.net/manual/en/pdo.prepared-statements.php找到更多的例子
https://stackoverflow.com/questions/5375182
复制