gpt4 book ai didi

php - 使用插入值数组执行准备好的语句不起作用

转载 作者:行者123 更新时间:2023-11-29 01:25:56 26 4
gpt4 key购买 nike

我正在尝试使用插入值数组,使用准备好的语句在我的数据库上的 php 中定义 SELECT 。目前我使用存储过程,我的代码如下所示:

$user_id = $user["id_user_key"];
$is_active = 1;

$stmt = $db->prepare("CALL spGetUserProducts(?, ?)");
$stmt->bind_param("ii", $user_id, $is_active);
$stmt->execute();
$result = $stmt->get_result();

这工作正常,但目前我想摆脱我的存储过程并在 php 中执行所有 SQL

我将上面的代码更改为:

$user_id = $user["id_user_key"];
$is_active = 1;

$stmt = $db->prepare(
"SELECT
tp.id_product AS id,
tp.product_name AS pname,
tp.product_code AS pcode,
tp.product_icon AS picon
FROM
tbl_user_products tup
INNER JOIN
tbl_products tp
ON tp.id_product = tup.id_product_fk
WHERE
tup.active = :isActive
AND tup.id_user_fk = :getUser"
);
$stmt->execute(array(
":getUser" => $user_id,
":isActive" => $is_active)
);
$result = $stmt->get_result();

当我运行此脚本时,出现以下错误:

Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':isActive AND tup.id_user_fk = :getUser' at line 12

可以肯定的是,我也确实在没有绑定(bind)参数的情况下运行了 SQL 脚本,如下所示:

$user_id = $user["id_user_key"];
$is_active = 1;

$stmt = $db->prepare(
"SELECT
tp.id_product AS id,
tp.product_name AS pname,
tp.product_code AS pcode,
tp.product_icon AS picon
FROM
tbl_user_products tup
INNER JOIN
tbl_products tp
ON tp.id_product = tup.id_product_fk
WHERE
tup.active = 1
AND tup.id_user_fk = 1"
);
$stmt->execute();
$result = $stmt->get_result();

这也有效。尽管我遵循了 php.net 中的示例,但 :getUser:isActive 的绑定(bind)似乎不起作用:

/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->execute(array(':calories' => $calories, ':colour' => $colour));

我在 XAMPP 3.2.2 上运行。

对此有什么想法吗?

最佳答案

您似乎正在使用 mysqli_ PHP 代码库连接到您的数据库。 MySQLi 不支持命名参数。您没有确切地说您的示例是从哪里获得的,但我猜它是来自与 PDO 库相关的页面。它们是不同的库,具有不同的函数名称和功能(尽管看起来相似,如果您没有仔细检查的话)。

但是,没有什么可以阻止您继续使用支持的语法。您只需切换提供参数的顺序,以匹配它们在 SQL 中出现的顺序。 (或者当然你可以切换 SQL 中 WHERE 子句的顺序,但这里我切换了参数值的顺序。)

$stmt = $db->prepare(
"SELECT
tp.id_product AS id,
tp.product_name AS pname,
tp.product_code AS pcode,
tp.product_icon AS picon
FROM
tbl_user_products tup
INNER JOIN
tbl_products tp
ON tp.id_product = tup.id_product_fk
WHERE
tup.active = ?
AND tup.id_user_fk = ?"
);

$stmt->bind_param("ii", $is_active, $user_id);
$stmt->execute();

关于php - 使用插入值数组执行准备好的语句不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55142152/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com