简体   繁体   中英

Array values in SQL query?

$sql = mysql_query("INSERT INTO `users` VALUES(
        '',
        '$form['name']',
        '$form['saddress']',
        '$form['apt']',
        '$form['zip']',
        '$form['homephone']',
        '$form['cellphone']',
        '$form['email']',
        '$form['    ']',
        '$form['city']',
        '$form['state']',
        '$form['country']',
        '$salt','$hash',
        '$form['username']'
    )");

How would I make that work? It's giving me Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING

Try using curly brackets around the variables, like this:

..
'{$form['name']}',
'{$form['saddress']}',
..

Either by removing the single quotes from the $form['x'] or by doing something like:

mysql_query("INSERT INTO x VALUES(
  '" . mysql_real_escape_string($form['x']) . "',
  '" . mysql_real_escape_string($form['x']) . "'
");

Notice that there are double quotes inside the single quotes.

This is a classic problem that stems from PHP's ability to parse strings for variables, which can get confusing. I prefer to keep my variables outside of the strings, and concatenate when needed.

Here's what I would do:

$sql = mysql_query("INSERT INTO `users` VALUES('" .
    implode("','", array(
        "",
        $form['name'],
        $form['saddress'],
        $form['apt'],
        $form['zip'],
        $form['homephone'],
        $form['cellphone'],
        $form['email'],
        $form['    '],
        $form['city'],
        $form['state'],
        $form['country'],
        $salt,
        $hash,
        $form['username']
    )) . "')";
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM