2

我正在通过 PHP 脚本运行以下查询

DROP TABLE IF EXISTS `address`;CREATE TABLE `address` (  `Id`
int(11) NOT NULL auto_increment,   `EntityId` int(11) NOT NULL,  
`sStreet1` varchar(50),   `sStreet2` varchar(50),   `sCity`
varchar(50),   `sLoc` varchar(50),   `sPv` char(2),   `sState`
varchar(50),   `sZip` varchar(10),   `sType` varchar(50),  
`FiscalAddress` tinyint(1) NOT NULL,   PRIMARY KEY  (`Id`) );

我可以通过不同的客户端(例如 Navicat)毫无问题地运行此查询,但通过 PHP 运行此查询将输出以下内容

$result = mysql_query($query);
if (!$result) {
    $message  = 'Invalid import content: ' . mysql_error() . "\n\n";
    $message .= 'Whole query: ' . $query;
    die($message);
}

这将输出以下内容:

您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 2 行的“CREATE TABLE address (Id int(11) NOT NULL AUTO_INCREMENT, EntityId int(11)”附近使用正确的语法整个查询:DROP TABLE IF EXISTS address; CREATE表地址 ( Id int(11) NOT NULL AUTO_INCREMENT, EntityId int(11) NOT NULL, sStreet1 varchar(50), sStreet2 varchar(50), sCity varchar(50), sLoc varchar(50), sPv char(2), sState varchar(50), sZip varchar(10), sType varchar(50), FiscalAddress tinyint(1) NOT NULL, PRIMARY KEY (Id) );

我究竟做错了什么???

4

2 回答 2

2

问题不在于CREATE TABLE语句,而是mysql_query()不支持在一次调用中执行多个语句。DROP TABLE首先在单独的调用中执行语句mysql_query(),然后执行CREATE TABLE.

$dt = mysql_query("DROP TABLE IF EXISTS `address`");
if ($dt) {
  // Execute CREATE TABLE separately...
  $ct = mysql_query("CREATE TABLE...........");
  if (!$ct) {
     // Proceed with the rest of your code.
    $message  = 'Invalid import content: ' . mysql_error() . "\n\n";
    $message .= 'Whole query: ' . $query;
    die($message);
  }
}
else {} // DROP TABLE call failed. Handle appropriately.
于 2012-10-01T10:57:19.457 回答
0

感谢 Mihai,您为我指明了正确的方向……在这种情况下,正确的方法是 msqli

这是完整的工作代码:

function runImportQuery($query = '') {

    $mysqli = new mysqli($this->DATABASE_HOST,$this->DATABASE_USER,$this->DATABASE_PASS,$this->DATABASE_DB );

    if ($mysqli->connect_errno) {
            $message = "Connect failed: ". $mysqli->connect_error;
    }else{

        $result = $mysqli->multi_query($query);
            // Check result
            // This shows the actual query sent to MySQL, and the error. Useful for debugging.
            if (!$result) {
                $message  = "Failed to run query: (" . $mysqli->errno . ") " . $mysqli->error ."\n\n\r";
                $message .= 'Whole query: ' . $query."\n\n\r";
                return $message;
            }else{
                $message  = "Import successfully completed!";

            }

    }
    mysqli_close($link);
    return $message;

}
于 2012-10-01T13:44:15.647 回答