gpt4 book ai didi

PHP:无法多次运行相同的 MySQL 查询

转载 作者:行者123 更新时间:2023-11-29 12:26:02 28 4
gpt4 key购买 nike

HTML 文件:

<form method="post" action="generate.php">
Product Reference(s): (if multiple, separate by ",")<br />
<input type="text" name="project_ref" value="REF123, REF124" />
<input type="submit" value="Generate" />
</form>

PHP 文件:

<?php

$ref_array = explode(',', $_POST['project_ref']);

foreach ($ref_array as &$ref) {

// Create connection
$conn = mysqli_connect($host, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT * FROM `inventory` WHERE reference = '$ref' LIMIT 1";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Brand: " . $row["brand"]. "<br>";
}
} else {
echo "0 results";
}

mysqli_close($conn);

}

?>

结果:
品牌:Bose
0 个结果

但我实际上想要:
品牌:Bose
品牌:Beats

所以问题在于 MySQL 查询并未针对每个数组项运行。它只执行数组的第一项。

最佳答案

您的输入值在不同的引用之间有空格:REF123、REF124

您可以在逗号和空格上进行爆炸:

$ref_array = explode(', ', $_POST['project_ref']);

或修剪值:

 $sql = "SELECT * FROM `inventory` WHERE reference = '" . trim($ref) . "' LIMIT 1";

还强烈建议您传入 $ref 作为参数,而不是字符串文字:

http://php.net/manual/en/mysqli-stmt.bind-param.php

关于PHP:无法多次运行相同的 MySQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28307426/

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