Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

php - SQL giving a syntax error, yet I don't see one

I wrote a PHP script to import topics and posts into a new forum from an old one, I am getting a syntax error on line 2 of my SQL statement, yet I don't see what the error could be.

INSERT INTO `uh46v_chronoengine_forums_topics` (`id`,`forum_id`,`title`,`alias`,`user_id`,`published`,`locked`,`created`,`modified`,`hits`,`params`,`post_count`,`last_post`,`reported`,`has_attachments`,`announce`,`sticky`) VALUES (`33`,`2`,`DS4Windows rebranding`,`DS4Windows-rebranding`,`2`,`1`,`0`,`2015-02-04 22:10:57`,``,`0`,`{"uid":"4ad6a17c-c7e0-4626-95ea-1a248caaf964"}`,`24`,`540`,`0`,`0`,`0`,`0`); 
INSERT INTO `uh46v_chronoengine_forums_posts` (`id`,`topic_id`,`forum_id`,`subject`,`text`,`user_id`,`created`,`modified`,`published`,`params`) VALUES (`172`,`33`,`2`,`DS4Windows rebranding`,`So it was suggested in out old forum that a rebranding was in order for us, mainly to differentiate ourselves from Jays distribution. With the building of forums and more traffic now coming to the site I believe splitting not only from the DS4Windows name, but also from the DSDCS brand would be a good idea sometime in the near future. Not being a very good "marketing guy" myself, im not quite sure what to rename the project. So I will open the floor on the subject and hope we have somebody in the community good with such things.

General guidelines:
Must not violate any copyrights or trademarks
Keep in mind this application may not alwayse be limited to DS4 -> X360 mapping
Prefer the .com of the name be available`,`2`,`2015-02-04 22:10:57`,``,`1`,`{"author_address":"96.58.100.87"}`); 

This yields the same error

INSERT INTO `uh46v_chronoengine_forums_topics` (`id`,`forum_id`,`title`,`alias`,`user_id`,`published`,`locked`,`created`,`modified`,`hits`,`params`,`post_count`,`last_post`,`reported`,`has_attachments`,`announce`,`sticky`) VALUES ('33','2','DS4Windows rebranding','DS4Windows-rebranding','2','1','0','2015-02-04 22:10:57','','0','{"uid":"0832fbee-506c-4fac-b2f6-eda324c54580"}','24','540','0','0','0','0'); 

INSERT INTO `uh46v_chronoengine_forums_posts` (`id`,`topic_id`,`forum_id`,`subject`,`text`,`user_id`,`created`,`modified`,`published`,`params`) VALUES ('172','33','2','DS4Windows rebranding','So it was suggested in out old forum that a rebranding was in order for us, mainly to differentiate ourselves from Jays distribution. With the building of forums and more traffic now coming to the site I believe splitting not only from the DS4Windows name, but also from the DSDCS brand would be a good idea sometime in the near future. Not being a very good "marketing guy" myself, im not quite sure what to rename the project. So I will open the floor on the subject and hope we have somebody in the community good with such things.

General guidelines:
Must not violate any copyrights or trademarks
Keep in mind this application may not alwayse be limited to DS4 -> X360 mapping
Prefer the .com of the name be available','2','2015-02-04 22:10:57','','1','{"author_address":"96.58.100.87"}'); 

Error:

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 'INSERT INTO uh46v_chronoengine_forums_posts (id,topic_id,forum_id,`subje' at line 2

For reference but not likely related since the error is a MySQL one, here is the PHP script I am using to accomplish this.

<?PHP
function GUID()
{
    if (function_exists('com_create_guid') === true)
    {
        return trim(com_create_guid(), '{}');
    }

    return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
}

include_once('configuration.php');
$config = new JConfig;

$servername = $config->host;
$username = $config->host;
$password = $config->host;

$sourceForumID = 7;
$destinationForumID = 2;

// Create connection
$db = new mysqli($config->host, $config->user, $config->password, $config->db);


// Check connection
if ($db->connect_error) {
    die("Connection failed: " . $db->connect_error);
} 
$topicsTableA = "phpbb_topics";
$topicsTableB = $config->dbprefix."chronoengine_forums_topics";
$postsTableA = "phpbb_posts";
$postsTableB = $config->dbprefix."chronoengine_forums_posts";

$topicsSQLA = <<<SQL
    SELECT *
    FROM `$topicsTableA`
    WHERE forum_id = $sourceForumID
SQL;


if(!$topicsResultA = $db->query($topicsSQLA)){
    die('There was an error running the query [' . $db->error . ']');
}

$topicsSQLB = "";
while($topicsRowA = $topicsResultA->fetch_assoc()){
    $id = $topicsRowA["topic_id"];
$postsSQLA = <<<SQL
    SELECT *
    FROM `$postsTableA`
    WHERE topic_id = $id
SQL;
    if(!$postsResultA = $db->query($postsSQLA)){
        die('There was an error running the query [' . $db->error . ']');
    }


    $id = $topicsRowA["topic_id"];
    $forum_id = $destinationForumID;
    $title = mysqli_real_escape_string($db,$topicsRowA["topic_title"]);
    $alias = preg_replace("/[^A-Za-z0-9]/", '-', $topicsRowA["topic_title"]);
    $user_id = $topicsRowA["topic_poster"];
    $published = 1;
    $locked = 0;
    $created = (new DateTime("@".$topicsRowA["topic_time"]))->format('Y-m-d H:i:s');
    $modified = null;
    $hits = 0;
    $params = mysqli_real_escape_string($db,'{"uid":"'.strtolower(GUID()).'"}');
    $post_count = $postsResultA->num_rows;
    $last_post = $topicsRowA["topic_last_post_id"];
    $reported = 0;
    $has_attachments = 0;
    $announce = 0;
    $sticky = 0;

    $topicsSQLB .= "INSERT INTO `$topicsTableB` (`id`,`forum_id`,`title`,`alias`,`user_id`,`published`,`locked`,`created`,`modified`,`hits`,`params`,`post_count`,`last_post`,`reported`,`has_attachments`,`announce`,`sticky`) VALUES ('$id','$forum_id','$title','$alias','$user_id','$published','$locked','$created',NULL,'$hits','$params','$post_count','$last_post','$reported','$has_attachments','$announce','$sticky'); 

";
    while($postsRowA = $postsResultA->fetch_assoc()){
        $Tid = $postsRowA["post_id"];
        $topic_id = $id;
        $subject = mysqli_real_escape_string($db,$postsRowA["post_subject"]);
        $text = mysqli_real_escape_string($db,$postsRowA["post_text"]);
        $user_id = $postsRowA["poster_id"];
        $created = (new DateTime("@".$postsRowA["post_time"]))->format('Y-m-d H:i:s');
        $modified = null;
        $published = 1;
        $params = mysqli_real_escape_string($db,'{"author_address":"'.$postsRowA["poster_ip"].'"}');

        $topicsSQLB .= "INSERT INTO `$postsTableB` (`id`,`topic_id`,`forum_id`,`subject`,`text`,`user_id`,`created`,`modified`,`published`,`params`) VALUES ('$Tid','$topic_id','$forum_id','$subject','$text','$user_id','$created',NULL,'$published','$params'); 

";

    }

}
//if ($db->query($topicsSQLB) === true) {
//    echo "New record created successfully";
//} else {
//    echo "Error: " . $sql . "<br>" . $db->error . "<br>";
//}
echo $topicsSQLB;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

PHP Mysqli permits multiple queries with the multi_query() function.

The following is to add on to the conversation in general terms, and avoid grief from endless Out of Sync errors when blocks of multi queries are run on top of one another. Or a non-multi after a multi.

The trouble begins after the execution of multi_query() if one then proceeds to the next query without clearing the result set. The error would be the one denoted as Note1 at the bottom. But it is avoided in this Answer.

Your particular problem had nothing to do with or . They were tested as part of this effort, but left out not to confuse the next person coming in with their problem, different.

<?php
    //mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    mysqli_report(MYSQLI_REPORT_ALL);
    error_reporting(E_ALL); // report all PHP errors
    ini_set("display_errors", 1); 
    echo "start<br/>";

    try {
        $mysqli= new mysqli('hostname', 'dbuser', 'pwd', 'dbname');
        if ($mysqli->connect_error) {
            die('Connect Error (' . $mysqli->connect_errno . ') '
                . $mysqli->connect_error);
        }
        echo "I am connected and feel happy.<br/>";
        $query = "INSERT INTO `table1`(`thing`) values ('aaa')";
        $mysqli->query($query);
        // works fine

        // Note the concat below
        $query = "INSERT INTO `table1`(`thing`) values ('bbb1'); ";
        $query .=$query; // double it up with concat (in other words two insert)
        // we have a multi query so call it the right way:
        $mysqli->multi_query($query);
        // we need to clear the protocol to avoid Out of Sync errors
        // http://stackoverflow.com/a/21754463
        do { 
            $mysqli->use_result(); 
        }while( $mysqli->more_results() && $mysqli->next_result() );        
        // if you remark out the above 3 lines, 
        // expect error message depicted in **** Note1 ****

        // purpose of this next block is to show result sets are cleared
        // from prior multi, and we can do another insert
        // thus avoiding error 500 out of sync errors
        $query = "INSERT INTO `table1`(`thing`) values ('ccc')";
        $mysqli->query($query);   // a single insert statement

        // Finally, this shows that running a multi without a multi_query fcn call will bomb
        $query = "INSERT INTO `table1`(`thing`) values ('explosion'); 
";
        $query .=$query; // double it up with concat
        $mysqli->query($query);   // make a multi query explode by not calling multi_query (but rather query)
        //  The above line generated an error, error message below (**** Note2 ****)
        $mysqli->close();
    } catch (mysqli_sql_exception $e) { 
        throw $e; 
    }
?>

Database results:

select * from table1;
+----+-------+
| id | thing |
+----+-------+
|  1 | aaa   |
|  2 | bbb1  |
|  3 | bbb1  |
|  4 | ccc   |
+----+-------+

The following error messages are mentioned in the source code shown. The first one is completely avoided. The second one is not, and there to show that the function multi_query(), as opposed to query(), is required.

****** Note1 ******

Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Commands out of sync; you can't run this command now' in C:Apache24htdocsmi_insert_multi_query_test.php:36 Stack trace: #0 C:Apache24htdocsmi_insert_multi_query_test.php(36): mysqli->query('INSERT INTO `ta...') #1 {main} thrown in C:Apache24htdocsmi_insert_multi_query_test.php on line 36

****** Note2 ******

Fatal error: Uncaught exception 'mysqli_sql_exception' with message '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 'INSERT INTO table1(thing) values ('explosion')' at line 2' in C:Apache24htdocsmi_insert_multi_query_test.php:41 Stack trace: #0 C:Apache24htdocsmi_insert_multi_query_test.php(41): mysqli->query('INSERT INTO `ta...') #1 {main} thrown in C:Apache24htdocsmi_insert_multi_query_test.php on line 41 select * from table1;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...