如何使用 mysqli 编写一个安全的 SELECT 查询,该查询具有可变数量的用户提供的值?

时间:2023-03-06
本文介绍了如何使用 mysqli 编写一个安全的 SELECT 查询,该查询具有可变数量的用户提供的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我需要一些帮助,以便在我的代码中执行 foreach.

I would like some help to execute a foreach into my code.

我将多个值发布到用户名中:作为 username[0] = user1 , user2

I post multiple value into username : as username[0] = user1 , user2

但是我的 foreach 给我的结果只是最后一个条目或什么都没有.

but my foreach gives me result like only the last entry or nothing.

$companyname = $_POST['companyname'];
$username_grab = $_POST['username'];
$username = implode(",", $username_grab);

foreach ($username_grab as $value){
    $value = $username_grab;

    $sql = "select * from linked_user where username = '$value' and company_name = '$companyname'";
    $res = mysqli_query($conn,$value);
    while($row = mysqli_fetch_array($res)){
        $returnValue['username'] = $row['username'];
        $returnValue['user_scid'] = $row['user_scid'];
    }
}
echo json_encode($returnValue);
?>

推荐答案

您要执行的任务是带有可变数量占位符的准备好的语句.这在 PDO 中更简单,但我将向您展示 mysqli 面向对象风格的方法.不管怎样,总是打印一个 json 编码的数组,这样你的接收脚本就知道需要什么样的数据类型.

The task you are to perform is a prepared statement with a variable number of placeholders. This is simpler in PDO, but I'll show you the mysqli object-oriented style approach. No matter what, always print a json encoded array so that your receiving script knows what kind of data type to expect.

我有一个片段,其中包括一整套诊断和错误检查.我没有测试过这个脚本,但它与我的这篇文章非常相似.

I had a snippet laying around that includes a full battery of diagnostics and error checking. I have not tested this script, but it has quite the resemblance to this post of mine.

if (empty($_POST['companyname']) || empty($_POST['username'])) {  // perform any validations here before doing any other processing
    exit(json_encode([]));
}

$config = ['localhost', 'root', '', 'dbname'];  // your connection credentials or use an include file
$values = array_merge([$_POST['companyname']], explode(',', $_POST['username']));  // create 1-dim array of dynamic length
$count = sizeof($values);
$placeholders = implode(',', array_fill(0, $count - 1, '?'));  // -1 because companyname placeholder is manually written into query
$param_types = str_repeat('s', $count);
if (!$conn = new mysqli(...$config)) {
    exit(json_encode("MySQL Connection Error: <b>Check config values</b>"));  // $conn->connect_error
}
if (!$stmt = $conn->prepare("SELECT user_scid, user_scid FROM linked_user WHERE company_name = ? AND username IN ({$placeholders})")) {
    exit(json_encode("MySQL Query Syntax Error: <b>Failed to prepare query</b>"));  // $conn->error
}
if (!$stmt->bind_param($param_types, ...$values)) {
    exit(json_encode("MySQL Query Syntax Error: <b>Failed to bind placeholders and data</b>"));  // $stmt->error;
}
if (!$stmt->execute()) {
    exit(json_encode("MySQL Query Syntax Error: <b>Execution of prepared statement failed.</b>"));  // $stmt->error;
}
if (!$result = $stmt->get_result()) {
    exit(json_encode("MySQL Query Syntax Error: <b>Get Result failed.</b>")); // $stmt->error;
}
exit(json_encode($result->fetch_all(MYSQLI_ASSOC)));

如果您不想要所有这些诊断条件和评论的膨胀,这里是应该执行相同的基本等效:

If you don't want the bloat of all of those diagnostic conditions and comments, here is the bare bones equivalent which should perform identically:

if (empty($_POST['companyname']) || empty($_POST['username'])) {
    exit(json_encode([]));
}

$values = explode(',', $_POST['username']);
$values[] = $_POST['companyname'];
$count = count($values);
$placeholders = implode(',', array_fill(0, $count - 1, '?'));
$param_types = str_repeat('s', $count);

$conn = new mysqli('localhost', 'root', '', 'dbname');
$stmt = $conn->prepare("SELECT user_scid, user_scid FROM linked_user WHERE username IN ({$placeholders}) AND company_name = ?");
$stmt->bind_param($param_types, ...$values);
$stmt->execute();
$result = $stmt->get_result();
exit(json_encode($result->fetch_all(MYSQLI_ASSOC)));

这篇关于如何使用 mysqli 编写一个安全的 SELECT 查询,该查询具有可变数量的用户提供的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:警告:mysqli_stmt::bind_result():绑定变量的数量与准备好的语句错误中的字段数量不匹配 下一篇:mysqli_prepare 与 PDO

相关文章