【问题标题】:PHP code to execute multiple queries with a single mysql_query() call使用单个 mysql_query() 调用执行多个查询的 PHP 代码
【发布时间】:2013-07-01 11:28:39
【问题描述】:

我正在尝试从我的 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 

【问题讨论】:

  • 据我所知,已弃用的旧版 mysql_... 扩展不支持多语句执行。您必须一个一个地运行它们。
  • 你为什么不用PDO
  • @ÁlvaroG.Vicario 我以这种方式尝试过的结果仍然相同......该怎么办......当它到达@columns 时,该语句正在中断......!!
  • @Bojangles 那是怎么回事..??请
  • 每当您说“它给我一个错误”时,您还应该提供您所看到的确切错误消息。如果可能的话,连同代码中抛出错误的点一起。

标签: php mysql


【解决方案1】:

来自the manual

mysql_query() 发送一个唯一查询(多个查询不 支持) 到服务器上当前活动的数据库 与指定的 link_identifier 关联。

移至mysqli,它支持multiple statements

【讨论】:

  • thanx man __ 你得到了一个更好的答案 __ 我发现使用 PDO 比迁移到 mysqli 更简单___你的意见是什么..??等待您的评论__!!
  • 要么比你现在拥有的要好。我会稍微偏爱 mysqli,因为它是 PHP 的一部分。
【解决方案2】:
/* 
Author: Jack Mason 
website:  volunteer @http://www.osipage.com , web access application and bookmarking tool. 
Language: PHP, Mysql 
This script is free and can  be used anywhere, no attribution required. 
*/ 

ini_set('display_errors', 0); 
error_reporting(0); 
// SET MYSQL CONFIGURATION 
$serverName = 'localhost'; 
$username   = 'root'; 
$password   = ''; 
$database   = 'test_delete'; 

// SET THE SQL FILE PATH OR DIRECTLY GIVE ALL SQL STATEMENTS INSIDE QUOTES 
$query = file_get_contents('file.sql'); 

//OR  to execute multiple SQL statements directly, set "$query" variable as follows: 

$query = 'CREATE TABLE IF NOT EXISTS `employee_attendances` ( 
  `id` int(11) NOT NULL AUTO_INCREMENT, 
  `attendance_date` date DEFAULT NULL, 
  `employee_id` int(11) DEFAULT NULL, 
  `employee_leave_type_id` int(11) DEFAULT NULL, 
  `reason` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, 
  `is_half_day` tinyint(1) DEFAULT NULL, 
  PRIMARY KEY (`id`) 
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; 
CREATE TABLE IF NOT EXISTS `items_product` ( 
  `id` int(11) NOT NULL AUTO_INCREMENT, 
  `product_name` TEXT DEFAULT NULL, 
  `price` DOUBLE DEFAULT NULL, 
  PRIMARY KEY (`id`) 
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; 
'; 


// Establishing connection with mysqli database 
$con = new mysqli($serverName, $username, $password, $database); 
/* check connection */ 
if(mysqli_connect_errno()) { 
    printf("Connect failed: %s\n", mysqli_connect_error()); 
    exit(); 
} 

/* execute multi query */ 
if($con->multi_query($query))  
{ 
    do { 
        /* store first result set */ 
        if($resultSet = $con->store_result())  
        { 
            while($row = $resultSet->fetch_row())  
            { 
                printf("%s\n", $row[0]); 
            } 
            $resultSet->free(); 
        } 

         //print divider 
        if($con->more_results())  
        { 
     $loadArray = array("Creating tables....", "please wait..", "stay tuned while all table definitions are dumped..."); 
     $upperLimit = count($loadArray) - 1; 
           $randNumb = rand(0, $upperLimit); 
           echo $loadArray[$randNumb]; echo '<br/>'; 
           $loadArray = array();  
        } 
    } while ($con->next_result()); 

    echo 'All tables have been successfully copied/created to given database!'; 
/* close connection */ 
} 
$con->close();

此代码适用于 .SQL 文件或直接执行多个 SQL 查询。通过一次成功执行多达 200 个表进行测试。取自this phpsnips page

【讨论】:

    【解决方案3】:

    只需对 MySQL 数据库运行查询“set names 'utf8'”,您的输出应该会显示正确。

    【讨论】:

      【解决方案4】:

      以下面的代码为例:

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

      已编辑:

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

      使用EOF 做出这样的声明。

      【讨论】:

      • @tradebel123 我知道了,我已经编辑了答案。现在也对已编辑的语句进行更改,然后检查。
      • 我得到的结果相同...声明在@colu 附近中断...??
      【解决方案5】:

      正如 Burhan 指出的那样,mysql+php 不再支持多个查询。原因可能是 SQL 注入

      【讨论】:

        猜你喜欢
        • 2021-10-30
        • 1970-01-01
        • 1970-01-01
        • 2010-09-25
        • 2016-03-11
        相关资源
        最近更新 更多