如何使用php在数据库中搜索记录“不知道表名”[重复]

nue99wik  于 2023-05-16  发布在  PHP
关注(0)|答案(2)|浏览(268)

此问题已在此处有答案

Search text in fields in every table of a MySQL database(27回答)
3天前关闭。
我正在尝试做一个PHP搜索表单,让你搜索的东西不知道没有表名,搜索后,它比较的记录与“搜索文本”在所有的数据库?

xtfmy6hx

xtfmy6hx1#

你想搜索每个表的每个字段吗?
您可以尝试获取所有表:

SHOW TABLES FROM your-database;

然后,对于每个表,您可以获得字段:

SHOW COLUMNS FROM your-table

示例:

$array = array();
$getTables = mysqli($link, "SHOW TABLES FROM your-database");

while ($t = mysqli_fetch_row($getTables))
    $array[$t[0]] = array();

foreach( $array as $tableName => $fields )
{
    $getColumns = mysqli($link, "SHOW COLUMNS FROM ".$tableName);

    while ($c = mysqli_fetch_assoc($getColumns))
        $array[$tableName][] = $c['Field'];
}

var_dump($array); // will output tables and each fields;

现在你有了表/字段,所以你可以构建你的查询来进行搜索。

lbsnaicq

lbsnaicq2#

创建所有表和所有列的搜索功能

function searchAll($searchText = "", $printLogs = false)
{
    //if you are executing this function in your terminal
    if($printLogs)
    {
        echo "\033[34m  \n \n process started ". date("Y-M-D h:s:i"). "\033[0m \n ";
    }

    // $this->db get you database instance
    $tables = $this->db->list_tables();

    // Loop through each table
    foreach ($tables as $table)
    {

        if($printLogs)
        {
             echo "\033[92m \n \n process table  ". $table . " \033[0m";
        }

        $fields = $this->db->list_fields($table);

        // $searchText this is your search text ;

        foreach ($fields as $field)
        {

            $this->db->select('*');
            $this->db->from($table);
            $this->db->like($table.'.'.$field,$searchText);
    
            $query = $this->db->get();
            // echo $this->db->last_query(); die;
            $tmpResult = $query->result_array();
        
            if(!empty($tmpResult)){
                foreach($tmpResult as $values){
                    print_r($values);
                }
            }
            
            
        }
        
    }

}

相关问题