我为sql创建了准备好的语句,在mysqlWorkbench中为我提供了正确的结果,但当我尝试对php pdo使用相同的查询时,它会返回一个空数组。
那么,如何将我准备好的语句与php-pdo一起使用呢?
这是我的代码:
<?php
$dbh = new PDO('mysql:host=localhost;dbname=db', 'user', 'pass');
$pstmt = "set @sql = null;
select
group_concat(distinct
concat(
'MAX(IF(ch.ch_name = ''', replace(ch.ch_name, '''', ''''''), ''', v.v_value, NULL)) AS ''', replace(ch.ch_name, '''', ' ') , ''''
)
) into @sql
FROM e_champ ch
join e_champ_value v on v.v_fk_champ_id = ch.ch_id
join e_collecte c on c.c_id = v.v_fk_collecte_id
AND c.c_id = 2;
set @sql = concat('select oi.oi_id, ', @sql, ' from e_order_item oi
left join e_champ_value v on v.v_fk_order_item_id = oi.oi_id
join e_champ ch on ch.ch_id = v.v_fk_champ_id
join e_collecte c on c.c_id = v.v_fk_collecte_id
AND c.c_id = 2 GROUP BY oi_id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;";
$sth = $dbh->prepare($pstmt);
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:'n");
$result = $sth->fetchAll();
print_r($result);
?>
您的"prepared"语句易于SQL注入。
因为您不是在为真实的查询做准备,而是在模仿一个准备好的语句,而实际上使用的是相同的旧的脏连接和手动转义。
因此,在您的案例中,并没有任何理由使用SQL准备语句。
无论如何,要回答标题中的问题,要运行任何sql查询,无论是否使用sql准备的语句,都必须使用query()
方法,在单独的query()
调用中运行单独的sql查询
我找到了一个能给我正确结果的解决方案。
我在数据库中创建了一个存储过程,然后在php-pdo中调用它。
DELIMITER $$
CREATE PROCEDURE GetResult()
BEGIN
set @sql = null;
select
group_concat(distinct
concat(
'MAX(IF(ch.ch_name = ''', replace(ch.ch_name, '''', ''''''), ''', v.v_value, NULL)) AS ''', replace(ch.ch_name, '''', ' ') , ''''
)
) into @sql
FROM e_champ ch
join e_champ_value v on v.v_fk_champ_id = ch.ch_id
join e_collecte c on c.c_id = v.v_fk_collecte_id
AND c.c_id = 2;
set @sql = concat('select oi.oi_id, ', @sql, ' from e_order_item oi
left join e_champ_value v on v.v_fk_order_item_id = oi.oi_id
join e_champ ch on ch.ch_id = v.v_fk_champ_id
join e_collecte c on c.c_id = v.v_fk_collecte_id
AND c.c_id = 2 GROUP BY oi_id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$
//PHP代码
<?php
$dbh = new PDO('mysql:host=localhost;dbname=db', 'user', 'pass');
$pstmt = "call GetResult()";
$sth = $dbh->prepare($pstmt);
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:'n");
$result = $sth->fetchAll();
print_r($result);
?>
这是一个关于php预准备语句和存储过程的链接https://www.php.net/manual/en/pdo.prepared-statements.php
看看这是否有帮助:
$conn = new PDO('mysql:host=localhost;dbname=tabela_nome','user','pass');
try{
$select= "SELECT * from user_ WHERE email=:'email@email.com'";
$result = $conn->prepare($select);
$result->execute();
} catch(PDOException $e){
echo $e->getMessage();
}