如何将易受攻击的 sql 查询转换为参数化查询 PHP

How to turn vulnerable sql queries into parameterized queries PHP

我有这段代码,我知道它很容易受到攻击,但我无法从中生成安全的准备好的语句。任何知道如何到达获取存储在变量 $userrecord 中的成员记录数组和存储在 $rowsnumber 中的行数的人都可以帮助我。我之前没有使用过 MySQLi 准备好的语句

/*This query returns member records in an array format*/
$querymember = "SELECT * FROM members WHERE phone='$providedphone' "; 
$member = mysqli_query($conn,$querymember);

// Number of rows
$rowsnumber = $member->num_rows;

// User record (Entity)
$userrecords = $member->fetch_array(MYSQLI_NUM);

我试过的

$stmt = $mysqli->prepare("SELECT * FROM members WHERE phone = ?");
$stmt->bind_param("s", $providedphone);
$stmt->execute();

// To get number of rows
$rowsnumber = $stmt->num_rows;

// To get user records
$userrecords = $stmt->get_result();

$userrecords = $stmt->get_result();mysqli::statement 对象转换为 mysqli::result 对象,所以现在您所要做的就是像

之前那样处理结果集
$stmt = $mysqli->prepare("SELECT * FROM members WHERE phone = ?");
$stmt->bind_param("s", $providedphone);
$stmt->execute();
//To get number of rows
$rowsnumber = $stmt->num_rows;
//To get user records
$result = $stmt->get_result();
$userrecords = $result->fetch_array(MYSQLI_NUM);

或者您可以使用 mysqli::statement 对象,就像这样通过将 PHP 变量绑定到列名然后执行 mysqli::statement->fetch()

$stmt = $mysqli->prepare("SELECT * FROM members WHERE phone = ?");
$stmt->bind_param("s", $providedphone);
$stmt->execute();

// bind returned columns to PHP variables
// as I dont know what your column names are this is just an example
$stmt->bind_result($name, $code);

// this will fetch the columns into the PHP varibles
$stmt->fetch();