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