我试图从我的 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/