在后续查询中使用 mysqli 查询对象作为集合

Using mysqli query object as a set in subsequent query

我正在为当地度假村开发一个预订系统,该系统只能通过相当安全的 LAN 访问,因此我不会立即关注 SQL 注入。我主要关心的是基于 PK(s) return 通过对单个客人的查询查找预订的功能。为此,我一直在使用 mysqli 查询对象 return 通过 table 的查询包含来宾信息:

$get_guest_id = "SELECT id FROM guests WHERE fname = '$fname' OR lname = '$lname' OR phone = '$phone' OR email = '$email'";
$guest_id_result = mysqli_query($con, $get_guest_id);

我试过使用这个查询对象,就像我在 mySQL:

中的一个集合一样
$search_by_id = "SELECT * FROM reservation WHERE guest_id IN '$guest_id_result'";

但这并不像预期的那样return:

Returns false on failure. For successful queries which produce a result set, such as SELECT, SHOW, DESCRIBE or EXPLAIN, mysqli_query() will return a mysqli_result object. For other successful queries, mysqli_query() will return true.

return 为 true、false 或结果集,PHP 脚本在此语句处停止执行。

是否有不同的方式将 mysqli 查询对象中包含的数据以类似于集合的方式传递给另一个查询?

问题是您正试图将对象转换为查询字符串...

最好的解决方案可能是将两个查询变成一个查询,另外更新代码以使用准备好的语句。

查询

SELECT * FROM reservations
WHERE guest_id IN (SELECT id
    FROM guests
    WHERE fname  = ?
        OR lname = ?
        OR phone = ?
        OR email = ?
);

代码

$sql = "
    SELECT * FROM reservations
    WHERE guest_id IN (SELECT id
        FROM guests
        WHERE fname  = ?
            OR lname = ?
            OR phone = ?
            OR email = ?
    );
";

$query  = $con->prepare($sql);
$query->bind_param("ssss", $fname, $lname, $phone, $email);
$query->execute();
$result = $query->get_result();

while ($row = $result->fetch_assoc()) {
    echo $row["guest_id"], PHP_EOL; // Example output printing the guest_id of guests with reservations (followed by a newline)
}