2013-07-01 14 views
6

Sto provando ad eseguire il codice SQL sotto dalla mia classe PHP, ma quando lo faccio dà un errore. Il codice seguente funziona perfettamente nella console di PHPMyAdmin, ma non in PHP.Codice PHP per eseguire più query con una sola chiamata mysql_query()

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; 

Questo è come io sto facendo in 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); 

Che cosa sto facendo di sbagliato?

vedere l'errore sto ottenendo ::

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 
+2

Per quanto ne so, l'estensione deprecata di mysql _... non supporta l'esecuzione di più istruzioni. Dovrai eseguirli uno per uno. –

+0

Perché non stai usando [PDO] (http://php.net/manual/en/book.pdo.php)? – Bojangles

+0

@ ÁlvaroG.Vicario ho provato in questo modo anche lo stesso risultato .... cosa fare..la frase si rompe quando raggiunge @columns ... !! – tradebel123

risposta

6

Da the manual:

mysql_query() invia una query unico (più query non sono supportati) al database attualmente attivo sul server che è associato alla identificativo_connessione specificato.

Passare a mysqli, che supporta multiple statements.

+0

thanx man __ sei venuto con una risposta migliore __ usare fù PDO è più semplice della migrazione a mysqli___what è la tua opinione .. ?? aspettando il tuo commento__ !! – tradebel123

+0

O sarà meglio di quello che hai ora. Darei una leggera preferenza a mysqli poiché la sua parte di PHP è corretta. –

0

Utilizzare il codice qui sotto come esempio:

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

CURA:

$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; 

Utilizzare il EOF a fare tale dichiarazione .

+0

ancora che ottiene lo stesso errore mate___ – tradebel123

+0

@ tradebel123 ho ottenuto ho modificato la risposta. ora fai anche il cambiamento nell'istruzione modificata e poi controlla. –

+0

lo stesso risultato che sto ottenendo ... la dichiarazione si sta spezzando vicino a @colu ... ?? – tradebel123

0

Come Burhan ha sottolineato il fatto che più query non sono supportate più con mysql + php .Il motivo potrebbe essere SQL Injection

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(); 

Questo codice funziona sia con file SQL o direttamente esecuzione di più query SQL. Testato eseguendo fino a 200 tabelle in una sola volta. Tratto da this phpsnips page.

0

Basta eseguire la query "imposta nomi 'utf8'" contro il DB MySQL e l'output dovrebbe apparire corretto.

Problemi correlati