附加查询字符串 - PHP

I have a php variable

$query="insert into msnowplaying values";

Then, I want to append a query string

$q1="('1', '$selMovieTitle1', 'ST001', '1', '' )";
$query.=$q1;
echo "<script type='text/javascript'>alert('$query');</script>";

However, the alert shows nothing. Somehow, there's an error on the console:

[10:12:06.851] SyntaxError: missing ) after argument list @ http://localhost:1234/2013_12_2/controller/doaddNowPlaying.php:1

What am I missing? I've changed $q1 to " a" and the alert shows insert into msnowplaying values a

I don't know what happened, I really need some help. Thanks.

Remember, PHP is parsed on the server, before the HTML hits the viewer, and javascript is parsed in the browser, after the HTML has been received by the user.

What you are sending to the user is written by php into the data as if you wrote it by hand, including anything that may later be interpreted as javascript code.

When you are echoing $query to the browser, you are most likely ending up with something that looks like this:

<script type='text/javascript'>alert('('1', '$selMovieTitle1', 'ST001', '1', '' )');</script>

Do you see how this is invalid javascript? You are using unescaped single quotes inside the alert('..'). First, if you want to see the correct string in javascript, try this:

echo '<script type="text/javascript">alert("'.addslashes($query).'");</script>';

Here we are using the function addslashes() ( http://php.net/addslashes ) to escape the quotes appropriately.

$query = "insert into msnowplaying values";
$query .= "('1', '$selMovieTitle1', 'ST001', '1', '' )";
$query = addslashes($query);
echo "<script type='text/javascript'>alert('$query');</script>";

Try that