我需要从URL获取变量code,所以我$codes = $_GET['code'];(URL示例website.com/update?code[]=7291&code[]=9274&code[]=8264&)然后我SELECT firstname FROM guests WHERE invitecode = $codes"然后输出数据并设置为$relatives = $row["firstname"],然后在文件中稍后回显/打印print $relative

为什么这对我不起作用?

... connection made ...
$codes = $_GET['code'];
$sql = "SELECT firstname FROM guests WHERE invitecode = $codes";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
    $relatives[] = $row["firstname"];
}
}

foreach ($relatives as $relative) {
print $relative;
}


更新:

所以现在使用:

<?php

$codes = $_GET['code'];
$thecodes = "";
foreach($codes as $vals)
    $thecodes .= (int)$vals . ",";
if($thecodes != "")
{
    $thecodes = trim($thecodes, ",");
    $sql = "SELECT firstname FROM guests WHERE invitecode IN ($thecodes)";
    $result = mysqli_query($conn, $sql);
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
    $relatives[] = $row["firstname"];
}
}
foreach ($relatives as $relative) {
print $relative;
}
}
else
{
}

?>


它可以工作,但是我想将foreach ($relatives as $relative) { echo $relative; };输入这样的值$message = $firstname . " " . $lastname . " will be coming to your event. " . ;

最后,结果是这样的:$message = $firstname . " " . $lastname . " will be coming to your event. " . foreach ($relatives as $relative) { echo $relative . " "; };

由于某些原因,当我将它们合并时,它将无法工作。

最佳答案

为此使用IN运算符。

<?php

$codes = $_GET['code'];
$thecodes = "";
foreach($codes as $vals)
    $thecodes .= (int)$vals . ","; //Loop through making sure each is an int for security reasons (No sqli)
if($thecodes != "") //There is at least one code
{
    $thecodes = trim($thecodes, ","); //Remove any additional commas
    $sql = "SELECT firstname, lastname FROM guests WHERE invitecode IN ($thecodes)"; //Use the IN operator
    $result = mysqli_query($conn, $sql);
    if (mysqli_num_rows($result) > 0) {
        while($row = mysqli_fetch_assoc($result)) {
            echo $row["firstname"] . " " . $row["lastname"] . "is coming to your event";
        }
    }

}
else //No codes to be queried
{

}

?>

10-06 00:26