在PDO和PHP中,我研究了一些我认为是查询语句函数的工作解决方案的研究。现在,它与语句
错误PHP警告:PDOStatement :: execute():SQLSTATE [HY093]:参数号无效:绑定变量的数量与/var/www/html/php/php_tools/private/functions.php中的令牌数量不匹配第39行
这是我的临时文件的第15行,以使这更容易阅读而不是通过多个文件,它仍然工作相同,我检查。
<?php
try {
$db = new PDO("mysql:host=$host;dbname=$base;", $user, $pass);
}catch(Exception $e){
echo $error = $e->getMessage();
}
function execute_query($con, $query, $statements) {
$query_string = $con->prepare($query);
foreach ($statements as $statement) {
$query_string->bindValue(1, $statement['string'], PDO::PARAM_STR);
$query_string->bindValue(2, $statement['value'], PDO::PARAM_STR);
$query_string->bindValue(3, $statement['type'], PDO::PARAM_STR);// I believe this is the culprit?
}
$query_string->execute();
return $query_string->fetchAll();
}
$multi_item_query = "SELECT t.t_id as id, t.item_code as code,
t.item_name as name,
t.retail_price as retail, t.sale_price as price,
t.item_pieces as pieces, t.qty as quantity,
t.sold as sold, t.description as description,
b.brand as brand, c.category as category,
tt.tool_type as sections, i.image as image
FROM Tools as t
INNER JOIN Brands as b on t.b_id = b.b_id
INNER JOIN Categories as c ON t.c_id = c.c_id
INNER JOIN Images AS i ON t.t_id = i.t_id
LEFT OUTER JOIN Types AS tt ON t.tt_id = tt.tt_id
WHERE tt.tool_type = :tool";
if ( isset($_GET['cat']) ) {
if ( $_GET['cat'] == 'wrenches') {
$page_name = 'Wrenches';
$section = 'wrenches';
$param = 'wrenches';
} elseif ( $_GET['cat'] == 'blades') {
$page_name = 'Blades';
$section = 'blades';
$param = 'blades';
} else {
$page_name = 'Full Catalog';
$section = null;
}
}
$con = $db;
$statement = array(); // Prepare a statement array.
$id = array(
'string' => ':tool',
'value' => $param,
'type' => PDO::PARAM_STR
);
$statement[] = $id;
?>
<?php $items = execute_query($con, $multi_item_query, $statement); ?>
正好在&#34; bindValue&#34;它是foreach循环中现在破坏的地方。 随着我的学习更多做更多的研究我相信我的底部&#34; bindValue&#34;是罪魁祸首?但我不确定我会用什么作为PDO ::?项目宣布为..?任何帮助或指导都是不完美的..因为我可能会离开..还是新的,还有任何反馈请吗?
答案 0 :(得分:4)
你使你的功能过于复杂,以至于你自己没有使用它。让它更简单,像这样:
function execute_query($con, $query, $variables) {
$stmt = $con->prepare($query);
$stmt->execute($variables)
return $stmt;
}
所以你能够以这种方式运行它
$con = $db;
$variables['tool'] = $param;
$items = execute_query($con, $multi_item_query, $variables)->fetchAll();
答案 1 :(得分:2)
foreach ($statements as $statement) {
$query_string->bindValue($statement['string'], $statement['value'],$statement['type'] );
}
循环中的execute方法
foreach ($statements as $statement) {
$query_string->bindValue($statement['string'], $statement['value'],$statement['type'] );
$query_string->execute();
}
答案 2 :(得分:2)
您尝试传递绑定的所有部分,但尝试单独绑定它们。您需要将语句的所有部分传递给一个绑定值:
foreach ($statements as $statement) {
$query_string->bindValue($statement['string'], $statement['value'], $statement['type']);
}