簡體   English   中英

php / mysql從表1和表2中顯示列

[英]php/mysql SHOW COLUMNS from table1 and table2

有人可以建議我如何保存兩個數據庫表中的字段嗎?

一張桌子工作正常:

$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");

$result = mysql_query("SHOW COLUMNS FROM ".$table." WHERE Field NOT IN
('ID','Key','Text');");

$i = 0;
if (mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_assoc($result)) {
        $csv_output .= $row['Field']."; ";
        $i++;
    }
}
$csv_output .= "\n";`

我需要來自兩個不同表的字段。 我在同一台計算機上有兩個數據庫。 字段名稱是表上的differnet。

不是工作:

$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
mysql_select_db($db2) or die("Can not connect.");

$result = mysql_query("SHOW COLUMNS FROM ".$table." , ".$table2."  WHERE Field NOT IN 
('ID','Key','Text');");

$i = 0;
if (mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_assoc($result)) {
        $csv_output .= $row['Field']."; ";
        $i++;
    }
}
$csv_output .= "\n";

字段“ ID”,“鍵”和“文本”僅存在於DB1上。

您遇到的問題在於選擇數據庫。 選擇第一個數據庫后,立即選擇第二個數據庫,它將覆蓋前一個數據庫,因此所選數據庫最后是第二個數據庫。
一種解決方案是選擇第一個數據庫,獲取所需的列名,將其保存在$csv_output ,然后選擇第二個DB,獲取所需的列,並將其附加到$csv_output
烏斯曼提出的解決方案也不錯,解決方法如下

USE information_schema;  -- select the correct DB
SELECT column_name FROM columns WHERE table_name IN ('table1', 'table2');

希望有幫助!

更新資料

$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());

// get the column name from the first DB
mysql_select_db($db1, $link) or die("Can not connect to DB1.");
$result = mysql_query("SHOW COLUMNS FROM ".$table." WHERE Field NOT IN
('ID','Key','Text')");    
$i = 0;
if (mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_assoc($result)) {
        $csv_output .= $row['Field']."; ";
        $i++;
    }
}

// get the column names from the second DB
mysql_select_db($db2, $link) or die("Can not connect to DB2.");
$result = mysql_query("SHOW COLUMNS FROM ".$table." WHERE 1");
$i = 0;
if (mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_assoc($result)) {
        $csv_output .= $row['Field']."; ";
        $i++;
    }
}
$csv_output .= "\n";

將查詢更改為:

$result = mysql_query("SELECT column_name FROM information_schema WHERE table_name IN ('".$table."','".$table2."' WHERE column_name NOT IN ('ID','Key','Text');");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM