使用单个 mysql_query() 调用执行多个查询的 PHP 代码

标签 php mysql

我试图从我的 PHP 类中执行下面的 SQL 代码,但是当我执行时出现错误。下面的代码在 PHPMyAdmin 的控制台中运行完美,但在 PHP 中运行不正常。

SET @columns := (
  SELECT
    GROUP_CONCAT(column_name)
    FROM information_schema.columns
    WHERE table_schema = 'test'
    AND table_name = 'mytable'
    AND column_key <> 'PRI'
);

SET @sql := (
  SELECT CONCAT(
    'INSERT INTO mytable (', @columns, ') ',
    'SELECT ', @columns, ' FROM mytable ',
    'WHERE id = 1;'
  )
);

PREPARE stmt FROM @sql;

EXECUTE stmt;

这就是我在 PHP 中的做法:

$sql='';
$sql.="SET @columns := (
  SELECT
    GROUP_CONCAT(column_name)
    FROM information_schema.columns
    WHERE table_schema = 'test'
    AND table_name = 'mytable'
    AND column_key <> 'PRI'
    );";

$sql.="SET @sql := (
  SELECT CONCAT(
    'INSERT INTO mytable (', @columns, ') ',
    'SELECT ', @columns, ' FROM mytable ',
    'WHERE id = 1;'
  )
);";


$sql.="PREPARE stmt FROM @sql;

        EXECUTE stmt;";

$result = mysql_query($sql, $this->connection);

我做错了什么?

查看正在获取的错误::

Database query failed: 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 'SET @sql := (
                              SELECT CONCAT(
                                'INSERT INTO mytable(', @colu' at line 9 

最佳答案

来自 the manual :

mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier.

移动到mysqli,它支持multiple statements .

关于使用单个 mysql_query() 调用执行多个查询的 PHP 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17403403/

相关文章:

php - 合并两个表,按日期排序,有限制

php - 结合 2 个 MySQL 查询

php - 从 mysql 中的 2 个表中获取数据(需要帮助)

Mysql 和 case 语句不起作用

mysql - MySQL 错误 #1064 中的语法错误

php mkdir 不遵守我正在使用的 chmod 规则

php - SQL表没有出现在页面上

javascript - 在 PHP 和 JavaScript 之间传递变量

php - 从带有空格和换行符的 MySQL 数据库回显?

mysql - Mysql information_schema可以不与show create table对齐吗?