即使没有找到结果,也从 mySql 查询中获取列名

问题描述

我正在使用 laravel 执行前端发送的动态查询字符串。

这是一个用于加速开发过程的开发环境。

由于我不知道查询会是什么样子,所以我无法真正使用 Laravel 查询构建器。

所以这个

$users = DB::table('look_up_lists')
    ->leftJoin('look_up_list_values','look_up_lists.id','=','look_up_list_values.look_up_list_id')
    ->where('look_up_list_values.id',99)
    ->get();

实际上看起来像这样

select * from `look_up_lists` left join `look_up_list_values` on `look_up_lists`.`id` = `look_up_list_values`.`look_up_list_id` where `look_up_list_values`.`id` = 99

PHPmyAdmin 中,即使没有抛出任何结果,您也可以看到所涉及的列。

PHP my admin query result example

这正是我需要的,我想不出办法做到这一点。 只要有结果,我就设法让这些列参与进来,但当我没有结果时就不行。

我试过了:

 $sth =  DB::getPdo()->prepare($query);
    $sth->execute();
    return  $sth->fetchALl(\PDO::FETCH_OBJ);

同样,只要有结果就可以工作。

我被这个问题困扰了好几天,有人可以帮忙吗?

解决方法

如果结果集为空,我添加了一个 count(*) as ignore 这将强制只输出一行并为您提供列名, 或者您将空结果转储到临时表中,然后您可以在 tmep 表上使用简单的选择。 祝你好运。

      <?php
            include_once "../include/connect.pdo.php";
            
            $q = "select * from ttt";
            $xx = $connect_pdo->prepare($q);
            $xx->execute([]);
            $rows = $xx->fetchAll(PDO::FETCH_OBJ);
            $n = count($rows);
            
            echo var_dump($rows);
            
           $q = "select *,count(*) as ingnor from ttt";
           $xx = $connect_pdo->prepare($q);
           $xx->execute([]);
           $rows = $xx->fetchAll(PDO::FETCH_OBJ);
           $n = count($rows);
           echo "<p>". var_dump($rows);


// dump unknown query in temp-table then use the simple select with count

        $q = "CREATE TEMPORARY TABLE IF NOT EXISTS t1temp as (select * from ttt)";
        $xx = $connect_pdo->prepare($q);
        $xx->execute([]);
        $q = "select *,count(*) from t1temp";
        $xx = $connect_pdo->prepare($q);
        $xx->execute([]);
        $rows = $xx->fetchAll(PDO::FETCH_OBJ);
        $n = count($rows);
        $q = "drop temporary table t1temp";
        $xx = $connect_pdo->prepare($q);
        $xx->execute([]);
        echo "<p>" . var_dump($rows);
   

// The output
 
        F:\xampp-htdocs\project_template\user\test.php:11:
array (size=0)
  empty
F:\xampp-htdocs\project_template\user\test.php:24:
array (size=1)
  0 => 
    object(stdClass)[3]
      public 'id' => null
      public 'i0' => null
      public 'i1' => null
      public 't1' => null
      public 'c1' => null
      public 'e1' => null
      public 'u1' => null
      public 's1' => null
      public 'x1' => null
      public 'rt' => null
      public 'i2' => null
  public 'count(*)' => string '0' (length=1)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...