繁体   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