1

このクエリを PHP mysqli で実行しようとすると構文エラーが発生しますが、MySQL CLI で実行すると発生しません。ここで何が起こっているのか誰か教えてください。

クエリは次のとおりです。

DROP TABLE IF EXISTS `wp_commentmeta`;
    CREATE TABLE `wp_commentmeta` (
      `meta_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
      `comment_id` bigint(20) unsigned NOT NULL DEFAULT '0',
      `meta_key` varchar(255) DEFAULT NULL,
      `meta_value` longtext,
      PRIMARY KEY (`meta_id`),
      KEY `comment_id` (`comment_id`),
      KEY `meta_key` (`meta_key`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

テストコードは次のとおりです。

<?php

$sql="
    DROP TABLE IF EXISTS `wp_commentmeta`;
    CREATE TABLE `wp_commentmeta` (
      `meta_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
      `comment_id` bigint(20) unsigned NOT NULL DEFAULT '0',
      `meta_key` varchar(255) DEFAULT NULL,
      `meta_value` longtext,
      PRIMARY KEY (`meta_id`),
      KEY `comment_id` (`comment_id`),
      KEY `meta_key` (`meta_key`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
";

$conn=mysqli_connect('localhost','root','yesthereis','test');
if(mysqli_query($conn, $sql)){
    echo "Inserted\n";
}else{
    echo "Failed\n".mysqli_error($conn)."\n";
}
?>

...そしてそれは実行です:

jgalley@jgalley-debian:~/code/$ php test.php 
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 'CREATE TABLE `wp_commentmeta` (
      `meta_id` bigint(20) unsigned NOT NULL AUT' at line 2

ご覧のとおり、CLI で正常に動作します。

jgalley@jgalley-debian:~/code/mysqlsync2$ mysql -u root -p'yesthereis' test
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 213
Server version: 5.1.63-0+squeeze1 (Debian)

Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> DROP TABLE IF EXISTS `wp_commentmeta`;
Query OK, 0 rows affected, 1 warning (0.05 sec)

mysql>     CREATE TABLE `wp_commentmeta` (
    ->       `meta_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
    ->       `comment_id` bigint(20) unsigned NOT NULL DEFAULT '0',
    ->       `meta_key` varchar(255) DEFAULT NULL,
    ->       `meta_value` longtext,
    ->       PRIMARY KEY (`meta_id`),
    ->       KEY `comment_id` (`comment_id`),
    ->       KEY `meta_key` (`meta_key`)
    ->     ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Query OK, 0 rows affected (0.01 sec)

mysql> quit
Bye
4

1 に答える 1

7

mysqli_query1 回の呼び出しで 2 つのクエリを実行することはできません。クエリ文字列を 2 つに分割し、別々に実行します。(または、TheVedge がコメントで正しく指摘しているように、スクリプトmysqli_multi_query内の のドロップイン置換として使用mysqli_queryしてください。)

これは、SQL インジェクションを軽減するのに役立ちます。

于 2012-12-20T02:23:04.813 に答える