将普通 SELECT 查询转换为准备好的 SELECT 查询

Converting a normal SELECT query to a prepared SELECT query

如何将此 SELECT 查询转换为准备好的 SELECT 查询?我可以做 INSERT 准备好的语句或 UPDATE 的语句,但我对 SELECT 准备好的查询感到困惑,因为我永远不确定要为 bind_param 放置什么,我确实这样做了不知道如何用 JOIN

构建它
$stmt = mysqli_query($con,"SELECT up.ordering, u.username, up.playername 
FROM users AS u  
INNER JOIN playersByUser AS up ON u.id = up.userid 
WHERE u.id = $userid 
ORDER BY up.ordering"); 
if (!$stmt) {
    die('Invalid query: ' . mysqli_error($con));
}

我知道会是这样的...

$stmt = $con->prepare("SELECT up.ordering, u.username, up.playername 
FROM users AS u  
INNER JOIN playersByUser AS up ON u.id = up.userid 
WHERE u.id = $userid 
ORDER BY up.ordering");

if (!$stmt->bind_param("",)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}

if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

我只是不确定如何为它绑定参数或者是否需要它?

准备语句的全部意义在于,您可以分别发送查询和用户输入的值。这样,您就无法连接 恶意 数据和 build/run 恶意 SQL 查询。

在您的查询中,您需要使用 ?s 作为占位符。

$stmt = $con->prepare("SELECT up.ordering, u.username, up.playername 
FROM users AS u  
INNER JOIN playersByUser AS up ON u.id = up.userid 
WHERE u.id = ?
ORDER BY up.ordering");

然后您可以使用 bind_param 发送要放入占位符的值。

// The 'i' tells SQL what type to use in the query
// Here, it's an int
$stmt->bind_param('i', $userid);
$stmt->execute();

(查看 bind_param 的文档了解更多信息:http://php.net/manual/en/mysqli-stmt.bind-param.php

执行查询后,您需要使用 bind_resultfetch 来获取字段:

$stmt->bind_result($ordering, $username, $playername);
while ($stmt->fetch()) {
    // The variables $ordering, $username, and $playername
    // will be updated each loop iteration (every time `fetch()` is called)
    echo $playername;
}

bind_result 的文档解释了它是如何工作的:http://php.net/manual/en/mysqli-stmt.bind-result.php

当您使用准备好的查询时,您不会在查询字符串中放置变量,而是放置占位符 ?。然后使用 bind_param 将占位符连接到变量。

$stmt = $con->prepare("SELECT up.ordering, u.username, up.playername 
FROM users AS u  
INNER JOIN playersByUser AS up ON u.id = up.userid 
WHERE u.id = ?
ORDER BY up.ordering");
$stmt->bind_param("i", $userid);
$stmt->execute();