gpt4 book ai didi

php - 在 MySQL 的 IN 子句中传递字符串变量

转载 作者:行者123 更新时间:2023-11-29 10:43:21 25 4
gpt4 key购买 nike

我有这段代码,我需要在 IN 子句中传递一个变量,以便从数据库中捕获所有相应的记录。问题是它只返回第一条记录,而有多个记录。问题出在第二个查询中:

// FIRST QUERY
$query0 = "SELECT articoli.id
FROM articoli
WHERE articoli.visibile = ?
AND articoli.genere2 = ?
ORDER BY articoli.id ASC";

$stmt0 = mysqli_stmt_init($con);
mysqli_stmt_prepare($stmt0,$query0);
mysqli_stmt_bind_param($stmt0,'ii',$visibile,$id);
mysqli_stmt_bind_result($stmt0,$rows0['id']);
mysqli_stmt_execute($stmt0);

while (mysqli_stmt_fetch($stmt0)){
$array_id[] = $rows0['id'];
}

$array_id = implode(',', $array_id);

print_r($array_id);

echo gettype($array_id)."<br />";

$immagini = array();

// SECOND QUERY:
$query1 = "SELECT articoli.id AS id_articoli,
articoli.titolo,
articoli.descrizione,
galleria.id AS id_galleria,
group_concat(galleria.foto) as immagini
FROM articoli
LEFT JOIN galleria
ON articoli.id = galleria.rif_id
WHERE FIND_IN_SET(articoli.id,?) // => Initially it was 'WHERE articoli.id IN ?'
AND articoli.visibile = ?
GROUP BY articoli.id
ORDER BY articoli.id";

$stmt1 = mysqli_stmt_init($con);
mysqli_stmt_prepare($stmt1,$query1);
mysqli_stmt_bind_param($stmt1,'ii',$array_id,$visibile);
// INIZIALIZZO LA CONNESSION
$stmt1 = mysqli_stmt_init($con);

// PREPARARE QUERY
mysqli_stmt_prepare($stmt1,$query1);

// LEGO I PARAMETRI
mysqli_stmt_bind_param($stmt1,'ii',$array_id,$visibile);

mysqli_stmt_bind_result($stmt1,$rows1['id_articoli'],
$rows1['titolo'],
$rows1['descrizione'],
$rows1['id_galleria'],
$rows1['immagini']);
// ESEGUO LA QUERY
mysqli_stmt_execute($stmt1);

while (mysqli_stmt_fetch($stmt1)){
$html .= "<p>$rows1[id_articoli]</p>";
$html .= "<p>$rows1[titolo]</p>";
$html .= "<p>$rows1[descrizione]</p>";
$html .= "<p>$rows1[id_galleria]</p>";
$html .= "<p>$rows1[immagini]</p>";
//$immagini = explode(',', $rows1['immagini']);
//$html .= "<p>$immagini[0]</p>";
}

return $html;

mysqli_stmt_close($stmt1);

在上面的代码中,在第一个查询中,我有一个 id 列表,我将其放入一个数组中,然后将数组内爆为一个字符串。然后,使用 print_r() 我可以看到所有记录。使用 echo gettype() 它告诉我该变量是一个字符串。然后我在 IN 子句中使用变量,但它总是只返回第一条记录。然后谷歌搜索我发现了 FIND_IN_SET 命令,我更改了代码并尝试了它,但它没有改变。它总是只返回第一条记录。我该如何解决这个问题?我必须使用字符串,或者我可以将数组传递给查询,并且使用 IN 子句或 FIND_IN_SET 子句更好?

最佳答案

摆脱第一个查询,只需在第二个查询中使用这些参数,而不需要 FIND_IN_SET 来匹配 ID。

$query1 = "SELECT articoli.id AS id_articoli,
articoli.titolo,
articoli.descrizione,
galleria.id AS id_galleria,
group_concat(galleria.foto) as immagini
FROM articoli
LEFT JOIN galleria
ON articoli.id = galleria.rif_id
WHERE articoli.visibile = ?
AND articoli.genere2 = ?
GROUP BY articoli.id
ORDER BY articoli.id";
$stmt1 = mysqli_stmt_init($con);
mysqli_stmt_prepare($stmt1,$query1);
mysqli_stmt_bind_param($stmt1,'ii',$visibile, $id);

关于php - 在 MySQL 的 IN 子句中传递字符串变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45067339/

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