php mysqli prepared statement

淺唱寂寞╮ 提交于 2019-11-30 09:55:52

问题


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);

Thanks!


回答1:


you want the following:

$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)
  );
}

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)




回答2:


  • Use question marks as placeholders in the SQL where you want the value of the variable to be.
  • Use mysqli_stmt::bind_param to bind values to the placeholders.



回答3:


If I'm not mistaken you have to use bindParam and replace the variables in your query with a question mark

$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);

you can find more examples at http://php.net/manual/en/pdo.prepared-statements.php



来源:https://stackoverflow.com/questions/5375182/php-mysqli-prepared-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!