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

2023-03-06php开发问题
2

本文介绍了如何使用 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 查询,该查询具有可变数量的用户提供的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

PHP实现DeepL翻译API调用
DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以...
2025-08-20 php开发问题
168

PHP通过phpspreadsheet导入Excel日期数据处理方法
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的...
2024-10-23 php开发问题
287

mediatemple - 无法使用 codeigniter 发送电子邮件
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)...
2024-08-23 php开发问题
11

Laravel Gmail 配置错误
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)...
2024-08-23 php开发问题
16

将 PHPMailer 用于 SMTP 的问题
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)...
2024-08-23 php开发问题
4

关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)...
2024-08-23 php开发问题
17