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

时间:2015-02-03 19:45:36

标签: php mysql

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查询没有针对每个数组项运行。它只执行数组的第一项。

2 个答案:

答案 0 :(得分:1)

您的输入值在不同引用之间有空格: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

答案 1 :(得分:0)

看起来您的问题在爆炸中。爆炸的第一个值是正确的,第二个(第三个,第四个等)将具有前导空格。在使用之前爆炸','代替','或修剪结果。

但是这段代码还有其他一些东西。不要为每个查询创建新连接,单个连接只能重用它。其次,在sql中使用它之前使用参数或清理值,这有助于防止sql注入攻击,更好的方法是使用PDO并使用参数。最后,更改查询,以便单个查询使用IN子句返回所需的所有结果。

<?php

$ref_array = explode(', ', $_POST['project_ref']);
$ref_IN = "";
foreach ($ref_array as $ref_val)
    $ref_IN .= "'{$ref_val}', ";
$ref_IN = rtrim($ref_IN , ",");

// 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 IN ({$ref_IN}) GROUP BY reference";
$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);

?>