preserve MySQL comment in PHP script

2019-08-06 23:21发布

I have been working on a project where I've been developing the MySQL commands interactively. I now want to run the MySQL commands using a PHP script. I do this by simply pasting in the MySQL commands and making them into a PHP string. Like this...

$queryStg = "
    update table1 set col1 = 1;

    drop table table2; 
    ";

$sqlQuery = mysqli_multi_query($mysqliLink, $queryStg);

However I've always had to strip out the MySQL comments to get it to work. I'd prefer to retain these comments. Is there a way to do this?. I've tried adding '\n' at the end of each comment but I cant get this to work. E.g. if I run this it will come back with errors...

$queryStg = "
    -- a mySQL comment
    update table1 set col1 = 1;

    --another comment
    drop table table2; 
    ";

$sqlQuery = mysqli_multi_query($mysqliLink, $queryStg);

Full code incase its useful

$mysqliLink = new mysqli ($host, $username, $password, $dbName);

$queryStg = "
    -- a mySQL comment
    update table1 set col1 = 1;

    --another comment
    drop table table2; 
    ";

$sqlQuery = mysqli_multi_query($mysqliLink, $queryStg);

do {
        if ( mysqli_error($mysqliLink) ) {
        die("ERROR: " .
            htmlspecialchars(mysqli_error($mysqliLink), ENT_QUOTES) .
            "<br>\n");
    }

    echo mysqli_affected_rows($mysqliLink);
    mysqli_use_result($mysqliLink);
    $moreResults = mysqli_more_results($mysqliLink);
    @mysqli_next_result($mysqliLink);
} while($moreResults);

Thanks

2条回答
疯言疯语
2楼-- · 2019-08-07 00:00
"select * from
 -- comment
 atable"

Gets translated into "select * from -- comment atable" MySQL also allows this type of comments:

/*comment that ends*/

"select * from
 /*comment*/
 atable"

Gets translated into "select * from /*comment*/ atable"

And that does work :-).

See: http://dev.mysql.com/doc/refman/5.1/en/comments.html

查看更多
走好不送
3楼-- · 2019-08-07 00:08

Comments will be skipped EDIT if properly escaped ("-- " needs to be followed by space character, tab, newline etc.). Try this instead:

$queryStg = "
-- a mySQL comment
update table1 set col1 = 1;

-- another comment
drop table table2; 
";

$sqlQuery = $mysqliLink->multi_query($queryStg);
查看更多
登录 后发表回答