如果存在混合类型数组,如何为 IN 子句准备语句?

2024-02-25

我正在尝试为 IN 子句编写准备好的语句,其中数组是混合数组。我能够为“call_user_func_array()”构建数组,但我无法准备语句。没有显示输出。

这是我的 php 代码:

    $search1 = array('pune','india','2014','mumbai','2015'); 

    print_r($search1);

    echo $param = implode(",",$search1);

    $ids = array_flip(array_flip(explode(',', $param)));

    var_dump($ids);

    $type1 = array();

    foreach ($ids as $element) {

    if(is_string($element)) {
        $type1[] ='s';
    }elseif(is_int($element)) {
        $type1[] ='i';
        }
    }

    print_r($type1);

    echo $type=implode("",$type1);

    $inputArray[] = &$type;
    $j = count($ids);
    for($i=0;$i<$j;$i++){
    $inputArray[] = &$ids[$i];
    }

    print_r($inputArray);

    echo $clause = implode(',', array_fill(0, count($ids), '?'));

    $construct .="(city in ('.$clause.') or state in ('.$clause.')
          or country in ('.$clause.')) AND year in ('.$clause.') order by year desc";

    $constructs ="SELECT * FROM info WHERE $construct";

    if($stmt1 = mysqli_prepare($conn, $constructs)){

    call_user_func_array(array($stmt1,'bind_param'),$inputArray);

    if(mysqli_stmt_execute($stmt1)){    

            $result = mysqli_stmt_get_result($stmt1);
            if(mysqli_num_rows($result) > 0){
            echo $foundnum = mysqli_num_rows($result);
     while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){

                echo $id = $row['id'];
                echo $name = $row['name'];

                }
            }
        }
    }
    mysqli_stmt_close($stmt1);

请告诉我我在这里做错了什么。


100% 经过测试且成功的代码:

$search1 = ['2014','pune','india','2014','mumbai','2015','mumbai'];

// Separate logically and remove duplicates
foreach ($search1 as $value) {
    if (strlen($value)==4 && ctype_digit($value)) {  // qualifies for the year column
        $years[$value] = null;
    } else {
        $strings[$value] = null;
    }
}

$years = array_keys($years);  // move keys to values
$years_count = sizeof($years);

$strings = array_keys($strings);  // move keys to values
$strings_count = sizeof($strings);

if (!$years_count || !$strings_count) {  // this is a matter of program logic
    echo "A minimum of one year value and one non-year value is required for search functionality.";
}elseif (!$conn = new mysqli("host", "user","pass","db")) {
    echo "Database Connection Error: " , $conn->connect_error;  // don't show to the public
} else {
    $years_csph = implode(',', array_fill(0, $years_count, '?'));  // comma-separated placeholders
    $strings_csph = implode(',', array_fill(0, $strings_count, '?'));  // comma-separated placeholders

    $total_count = $strings_count * 3 + $years_count;
    $total_params = array_merge($strings, $strings, $strings, $years);
    $param_string = str_repeat('s', $strings_count * 3) . str_repeat('i', $years_count);  // write s chars before i chars

    if(!$stmt = $conn->prepare("SELECT id, name FROM info WHERE (city IN ($strings_csph) OR state IN ($strings_csph) OR country IN ($strings_csph)) AND year IN ($years_csph) ORDER BY year DESC")) {
        echo "Syntax Error @ prepare: " , $conn->error;  // don't show to public
    }else{
        array_unshift($total_params, $param_string);  // prepend the type values string
        $ref = [];  // add references
        foreach ($total_params as $i => $v) {
            $ref[$i] = &$total_params[$i];  // pass by reference as required/advised by the manual
        }
        call_user_func_array([$stmt, 'bind_param'], $ref);    

        if (!$stmt->execute()) {
            echo "Error @ bind_param/execute: " , $stmt->error;  // don't show to public
        } elseif (!$stmt->bind_result($id, $name)) {
            echo "Error @ bind_result: " , $stmt->error;  // don't show to public
        } else {
            while ($stmt->fetch()) {
                echo "<div>$id : $name</div>"; 
            }
            $stmt->close();
        }
    }
}

除其他潜在问题外,'.$clause.'看起来不太好,因为它在占位符周围写了单引号和点。占位符永远不需要单引号,即使这样做,语法也会不正确。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如果存在混合类型数组,如何为 IN 子句准备语句? 的相关文章

  • PHP 中 file、file_get_contents 和 fopen 之间的区别

    我是 PHP 新手 我不太确定 两者之间有什么区别file file get contents and fopen 函数 什么时候应该使用其中一个而不是另一个 前两个 file http www php net manual en func
  • 从数组中检索均匀分布的元素数

    我知道如何提取数组中的每个第 n 项 但我遇到的困难如下 如何从 1800 个元素的数组中提取第 n 个项目 始终包括第一个和最后一个元素 总共最多 256 个元素 Example array 1 2 3 4 5 6 7 8 9 10 提取
  • 从目录中读取所有文件内容 - php

    这实际上是一个简单的任务 我想显示指定文件夹中所有文件的内容 我正在传递目录名称 echo a href row qname a 在第二页上 我正在迭代目录内容 while entryname readdir myDirectory if
  • PHP 从日志事件中获取行号

    好的 我还有一个问题HERE https stackoverflow com questions 3213423 php how could i make this class better suggestions feedback wel
  • php exec 返回的结果比直接进入命令行要少

    我有一个 exec 命令 它的行为与通过 Penguinet 给 linux 的相同命令不同 res exec cd mnt mydirectory zcat log file gz echo res 当将命令直接放入命令行时 我在日志文件
  • 限制分页页数

    objConnect mysql connect localhost root or die mysql error objDB mysql select db Test strSQL SELECT FROM UserAddedRecord
  • 同一路由组的多个前缀

    我正在为一所学校编写一个相当简单的网站 该网站有新闻 文章 视频剪辑 等 它的工作方式是在主页中我们向访问者展示一些课程 例如 gt math gt geography gt chemistry 用户在其中选择 1 网站内容会根据用户的选择
  • 正确的标头 php mysql blob 显示图像

    我正在尝试在我的 PHP 页面中显示来自 mysql blob 的图像 我知道这不是最佳实践 然后我会将其引入我的 iOS 应用程序中 我在设置页面标题时遇到问题 我认为需要将其设置为图像 所以 这显示了图像 但我不相信页眉是正确的 hea
  • 使用 DateTime 类计算日期差异时出错

    我正在尝试使用 DateTime 类 php gt 5 3 来计算 2 个日期的差异 手册中的示例简单明了 我尝试了该示例并且效果很好 但如果改变开始和结束日期 就会出现问题 this gt start date 2011 03 01 th
  • 如何缓存 twitter api 结果?

    我想缓存 twitter api 结果的结果并将其显示给用户 缓存结果的最佳方法是什么 我正在考虑根据时间限制将结果写入文件 可以吗 还是应该使用任何其他方法 最重要的是 理想的缓存时间是多少 我想显示来自 twitter 的最新内容 但
  • 扫描 PHP 上传的病毒

    我目前正在使用以下代码来扫描作为申请表的一部分上传的文件 safe path escapeshellarg dir file command usr bin clamscan stdout safe path out int 1 exec
  • 使用 IntlDateFormatter 转换非公历日期

    我应该如何使用将非公历日期转换为其他日历类型IntlDateFormatter 我要转换 1392 01 02 from persian to islamic日历 我尝试了以下代码 但它没有转换日历 formatter IntlDateFo
  • 使用 python 中的公式函数使从 Excel 中提取的值的百分比相等

    import xlrd numpy excel Users Bob Desktop wb1 xlrd open workbook excel assignment3 xlsx sh1 wb1 sheet by index 0 colA co
  • PHP函数返回值到html标签

    我想获取函数的返回值并将其显示到特定的id 在我的 Class php 中 我有一个名为 login 的函数 用于验证密码是否正确 不正确
  • 将文本拆分为数组,同时保留 Swift 中的标点符号

    我想将文本拆分为一个数组 保持标点符号与其余单词分隔开 因此字符串如下 Hello I am Albert Einstein 应该变成这样的数组 Hello I am Albert Einstein 我尝试过sting components
  • 如何在 C# 中获取 Json 数组?

    我有一个像这样的 Json 字符串 我想将它加载到 C 数组中 当我尝试这样做时 我收到异常 我的字符串 customerInformation customerId 123 CustomerName Age 39 Gender Male
  • 通过复选框选择多行时出错错误未定义索引:复选框

    我想从中选择多行checkbox并想通过单击按钮立即更新它们 我尝试了多种方法 但不起作用 你能帮忙吗 它显示错误为Undefined index checkbox td td
  • PHP 中的坏词过滤器?

    我正在用 PHP 编写一个坏词过滤器 我在数组中有一个坏词列表 方法 clean text 的写法如下 public static function cleanse text originalstring if self is sorted
  • MySQL 正在将我的时间戳值转换为 0000-00-00

    我是 PHP 新手 目前仍在学习中 我认为我的注册表有问题 username password email全部成功插入MySQL registered and last seen不要 我以为我正在使用getTimestamp 错了 但它呼应
  • MYSQL 按喜欢/不喜欢和受欢迎程度排序

    我有评论表 其中包括喜欢和不喜欢的内容 现在我在正确的顺序上遇到了问题 实际上 我的系统在顶部显示了最多点赞的评论 我正在 youtube 上寻找类似系统的东西 这意味着 100like 100dislikes 的评论的顺序高于 1 1 我

随机推荐