2011-03-21 118 views
0

嘿,我有一个快速的。有没有办法将变量包含到准备好的查询中?例如:php mysqli准备好声明

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

谢谢!

+0

你的问题是不完整的,我想你想问的是:我如何检索准备好的查询结果。你的结果变量将是空的,直到你调用'$ result-> fetch()' – knittl 2011-03-21 08:29:50

回答

1

找到更多的例子如下替换查询中的变量:

$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)值。直接做准备语句中使用变量,因为那样会(从消除解析时间间隔)

+0

呵呵,看看这正是我写的,相同的顺序和一切。变量在所有这一切之前得到声明,所以我不知道为什么它不显示。 – tim 2011-03-21 08:23:26

+0

@tim:不,它是不一样的。你直接在你的sql字符串中插入你的变量(没有转义发生!)。你的问题可能是误导性的,我猜你错过了'$ result-> fetch()'之后 – knittl 2011-03-21 08:25:06

+0

我想我很困惑。我应该在什么时候为这些绑定变量赋值? – tim 2011-03-21 08:30:52

-1

如果我没有记错,你必须使用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

0
  • 使用问号在SQL您想要的变量值的占位符击败预处理语句的全部目的成为。使用mysqli_stmt::bind_param将值绑定到占位符。