准备好的声明中的数组无效

时间:2014-04-08 16:25:38

标签: php

我想创建一个名为$params的数组的预准备语句。当我运行我的脚本时,我收到以下错误:

  

致命错误:在非对象中调用成员函数bind_param()   第110行/home/morea/directory-new.php

第110行是$stmt->bind_param('i', $place_holders);

$params = array(5, 6, 7, 9, 10, 11, 12, 3, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 4, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42);
/* Create a string for the parameter placeholders filled to the number of params */
$mysqli = new MySQLi("localhost", "erpa", "48p", "le3");
$mysqli->set_charset('utf8');
$place_holders = implode(',', array_fill(0, count($params), '?'));
$sth = ("SELECT u.url, COUNT(u.url) AS total, u.SiteTypeID, p.SiteType FROM sites AS u LEFT JOIN sitetypes AS p USING (SiteTypeID) WHERE SiteTypeID=($place_holders)");
$stmt = $mysqli->prepare($sth);
$stmt->bind_param('i', $place_holders);
$stmt->execute($params);
$query5 = mysqli_query($dbc, $sth);

while($row2 = mysqli_fetch_array($sql3, MYSQLI_ASSOC) && $row4 = mysqli_fetch_array($query5, MYSQLI_ASSOC)){
if ($row4['SiteType'] == 'selected'){
    $list .= $row4['total'];
    $list .= '<option value="'.$row4['SiteTypeID'].'"';
     $list .= "selected='selected'>";
    $list .= $row4['SiteType'];
    $list .= "</option>";
}
}

2 个答案:

答案 0 :(得分:1)

调用prepare()后应检查$ stmt。这可能是错误的,因为您的查询应使用WHERE SiteTypeID IN ($place_holders)而不是WHERE SiteTypeID=($place_holders);

编辑:(现在应该涵盖所有问题,并且是可接受的答案) 另外(感谢Rocket!)bind_params()需要一个参数列表,而不是数组,而execute()根本不需要参数。在http://us.php.net/manual/en/mysqli-stmt.bind-param.php仔细检查php文档中的这些功能。如果你想绑定到一个数组,考虑使用PDO,我觉得它比mysqli更好。

答案 1 :(得分:0)

您需要为查询中的每个 bind_param发送?个值。它还需要值作为参考。此外,->execute()不接受任何参数。最后,此处mysqli_query()不正确。

$stmt = $mysqli->prepare($sth);

$boundParams = array(str_repeat('i', count($params)));
foreach($params as &$val){
    $boundParams[] =& $val;
}
call_user_func_array(array($stmt, 'bind_param'), $boundParams);

$stmt->execute();    
$query5 = $stmt->get_result();

// then you can run mysqli_fetch_array on $query5

注意:get_result()要求您安装了mysqlnd驱动程序。

P.S。 WHERE SiteTypeID=($place_holders)应为WHERE SiteTypeID IN ($place_holders)