在我的PHP文档中,我得到了如下的SQL查询:
if(isset($_GET['id']))
{
$id = $_GET['id'];
$q = "SELECT * FROM `objekt_t` WHERE `id`='" . $id . "'";
$row = mysqli_query($con, $q) or die(mysqli_error($con));
while($r = mysqli_fetch_assoc($row))
{
$objekt = $r;
}
}
我意识到这是关于SQL注入等非常不安全的做法,所以我一直在研究准备好的SQL查询,使用绑定参数。查看bobby-tables.com,我看到这个示例查询:
$stmt = $db->prepare('update people set name = ? where id = ?');
$stmt->bind_param('si',$name,$id);
$stmt->execute();
我不明白我应该如何修改我当前的查询,以匹配使用绑定参数的更安全的查询。
同理
$mysqli = new mysqli("localhost", "my_user", "my_password", "db");
if(isset($_GET['id']))
{
$id = $_GET['id'];
$q = "SELECT some_field FROM `objekt_t` WHERE `id`= ?";
if ($stmt = $mysqli->prepare($q)) {
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
}
}
现在$result变量包含了您的查询结果
预处理语句将原始数据传输到查询,因此SQL注入是不可能的。对于real_escape_String
或任何其他格式化函数,不需要转义,因为这已经为您完成了。
的例子:
$db = new mysqli ("host","user","password","database");
$statement = $db->prepare("SELECT test FROM test WHERE Username=?");
$statement->bind_param('s',$_POST['Username']);
$statement->execute();
$statement->bind_result($resultCol);
$statement->fetch();
$statement->close();
我基本上是将$_POST数据直接绑定到查询,因为数据是作为原始数据发送的,所以即使查询包含注入形式,如$_POST['username'];查询将正常运行。
在过程和OOP风格方面,这取决于个人偏好,我个人更喜欢OOP风格,因为它更具可读性。
处理数字:
$ID= 5;
$db = new mysqli ("host","user","password","database");
$statement = $db->prepare("SELECT test FROM test WHERE ID=?");
$statement->bind_param('i',$ID);
$statement->execute();
$statement->bind_result($resultCol);
$statement->fetch();
$statement->close();
或者您可以直接在语句中使用精确值:
$db = new mysqli ("host","user","password","database");
$statement = $db->prepare("SELECT test FROM test WHERE ID='5'");
$statement->execute();
$statement->bind_result($resultCol);
$statement->fetch();
$statement->close();
你可以这样做:
$stmt = $mysqli->prepare('SELECT * FROM objekt_t WHERE id = ?');
$stmt->bind_param('i', $id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// $row is an associative array
}