PHP-遍历多个表并填充多维数组 [英] PHP - Loop through multiple tables and populate a multidimensional array

查看:87
本文介绍了PHP-遍历多个表并填充多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要遍历数据库中的多个表,然后使用其内容填充多维数组.我目前拥有的代码返回一个MySQL错误.我已经尝试过搜索,但是发现的所有内容都不符合我的需求.

I need to loop through multiple tables in my database and then populate multidimensional arrays with their contents. The code I have at the moment is returning a MySQL error. I've tried searching around but everything I find does not match my needs.

代码

// The arrays that will hold the data we wish to collect
$ids = array();
$data = array();

// The database tables we want to search through
$databaseTables = array("table1", "table2", "table3", "table4");

for ($x = 0; $x < 4; $x++) {
    // Create a new array for this table's data
    $ids[] = array();
    $data[] = array();

    // Query the database
    $query = "SELECT * FROM '$databaseTables[$x]'";
    $result = @mysql_query($query) or die(mysql_error());

    // Collect the data
    while ($row = mysql_fetch_array($result)) {
        $ids[$x][] = $row['id'];
        $data[$x][] = $row['data'];
    }
}

谢谢您的帮助.

修改

MySQL错误:

您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册以获取正确的语法,以在第1行的"table1"附近使用

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''table1'' at line 1

推荐答案

不要引用表名,而应使用反引号:

Dont quote table names, use the backtick instead:

$query = "SELECT * FROM `$databaseTables[$x]`";

如果打开了模式ANSI_QUOTES,则可以双引号表格名称,因为这会使引号成为标识符引号字符(与字符串引号字符相比),但默认情况下未设置.

If you have the mode ANSI_QUOTES turned on you can double quote table names as that causes quotes to be identifier quote characters (vs a string quote character), but by default this is not set.

来源:

  1. http://dev.mysql.com/doc/refman/5.0/en/identifiers.html
  2. http://dev.mysql.com/doc/refman/5.0/en/sql-mode.html
  3. http://dev.mysql.com/doc/refman/5.0/zh-CN/sql-mode.html#sqlmode_ansi_quotes
  1. http://dev.mysql.com/doc/refman/5.0/en/identifiers.html
  2. http://dev.mysql.com/doc/refman/5.0/en/sql-mode.html
  3. http://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_ansi_quotes

顺便说一句,我建议您不要再使用mysql_*函数.在以后的PHP版本中,不推荐使用它们,并且将删除.请参见 MySQL简介页面.

As an aside, I would advise you to not use the mysql_* functions any longer. They are deprecated and will be removed in future versions of PHP. See the introduction page to mysql.

相反,我会使用 PDO 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆