PHP MySQLi Prepared Statements Tutorial to Prevent SQL Injection

https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection#introduction

One Row
$result->fetch_assoc() - Fetch an associative array
$result->fetch_row() - Fetch a numeric array
$result->fetch_object() - Fetch an object array
All

$result->fetch_all(MYSQLI_ASSOC) - Fetch an associative array
$result->fetch_all(MYSQLI_NUM) - Fetch a numeric array

Side note: The following two examples use the splat operator for argument unpacking, which requires PHP 5.6+. If you are using a version lower than that, then you can substitute it with call_user_func_array().

$inArr = [12, 23, 44];
$clause = implode(',', array_fill(0, count($inArr), '?')); //create 3 question marks
$types = str_repeat('i', count($inArr)); //create 3 ints for bind_param
$stmt = $mysqli->prepare("SELECT id, name FROM myTable WHERE id IN ($clause)");
$stmt->bind_param($types, ...$inArr);
$stmt->execute();
$resArr = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
if(!$resArr) exit('No rows');
var_export($resArr);
$stmt->close();
posted @ 2020-02-01 15:48  Coding_Changes_LIfe  阅读(115)  评论(0编辑  收藏  举报