2014-04-08 37 views
1

我想用一个名为$params的数组创建一个准备语句。当我运行我的脚本,我得到以下错误:准备好的语句中的数组不工作

Fatal error: Call to a member function bind_param() on a non-object in /home/morea/directory-new.php on line 110

线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>"; 
} 
} 
+0

为什么你有'mysqli_query($ dbc,$ sth);'在那里? –

+0

使用fetch_array与我的sql语句 – user3286022

+0

这不正确的使用'mysqli_query'。 –

回答

1

你应该准备调用后检查$语句()。这可能是假的,因为你的查询应该使用WHERE SiteTypeID IN ($place_holders)WHERE SiteTypeID=($place_holders);

编辑:(现在应该涵盖所有问题,是一个可以接受的答案) 另外(!感谢火箭)bind_params()预计参数列表,而不是一个数组, execute()完全不需要参数。请在http://us.php.net/manual/en/mysqli-stmt.bind-param.php仔细检查这些功能的php文档。如果你想绑定到一个数组,可以考虑使用PDO,我发现代码比mysqli好得多。

+0

嗨,罗布,只是想你说什么,它似乎有帮助,但现在我得到的错误变量数量不匹配准备语句中的参数数量 – user3286022

+0

@ user3286022:'$ stmt-> bind_param('我', $ STI);'。你绑定多个'''s,但只为它们之一发送一个值。 –

+0

嗨Rocket,好的,我用$ stmt-> bind_param('i',$ place_holders)试了一下。相反,它告诉我变量的数量与预准备语句中的参数数量不匹配。我计算了数组中的项目数量,它们与我表格中的项目数量相匹配。 – user3286022

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)