如何从数据库中取出与用户选择的值相关的值?

时间:2015-11-13 15:40:15

标签: php mysql database find

我知道很多HTML和CSS,但仍在学习PHP。这就是我提出的。我需要用户提交code#,它会在数据库中找到一个值。这是我的代码:

$invitecode = $_GET['invitecode'];
$isattend = $_GET['attend'];
$isphone = $_GET['phone'];
$isemail = $_GET['email'];

$sql = "SELECT firstname, lastname FROM guests WHERE code = $code";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        $firstname = $row["firstname"];
        $lastname = $row["lastname"];
}}

现在我可以echo $firstname;

我需要它来查找具有相同"relate"字段的其他值,就像我刚刚提取的那样。因此,如果我添加与我得到的信息有关。

$sql = "SELECT firstname, lastname, relate FROM guests WHERE code = $code";
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
    $firstname = $row["firstname"];
    $lastname = $row["lastname"];
    $relate = $row["relate"];
}}

然后我启动另一个数据库搜索:

$sql = "SELECT firstname, lastname, code FROM guests WHERE relate = $relate";
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
    $first = $row["firstname"];
    $last = $row["lastname"];
    $code = $row["code"];
    echo " ?><input type="checkbox" name="add" value="<?php echo $code; ?>"><?php You are " . $first . " " . $last . "<br>";
}
}

我需要用户能够选择值。这就是为什么我也试图通过新值添加复选标记的原因。我怎么能让这项工作正确?

1 个答案:

答案 0 :(得分:2)

您有语法错误。最后一个块应该是:

# This is a great way to get hacked.
# http://php.net/manual/en/security.database.sql-injection.php
$sql = "SELECT firstname, lastname, code FROM guests WHERE relate = $relate";
$result = mysqli_query($conn, $sql);
if ( mysqli_num_rows($result) > 0 ) {
    // output data of each row
    while ( $row = mysqli_fetch_assoc($result) ) {
        $first = $row["firstname"];
        $last = $row["lastname"];
        $code = $row["code"];
        ?>
        <input type="checkbox" name="add" value="<?php echo $code ?>"> You are "<?php echo $first ?>" "<?php echo $last ?><br>
        <?php
    }
}

另外,我怀疑你真的希望它是一个收音机,而不是一个复选框。复选框允许多个选择。