I have a looping insert string, below. I keep getting an error message that I have 'unexpected T string". What am I doing wrong? I've tried all the combinations of punctuation I can think of. Thanks.


$sql = 'INSERT INTO cat_relations(relation_user_id,relation_cat) VALUES($ID,$_POST['categories'][$x])';

    Use the PHP bbcode tags properly and you'll see why:

    $sql = 'INSERT INTO cat_relations(relation_user_id,relation_cat) VALUES($ID,$_POST['categories'][$x])';

    (Then again, you should be using an editor with syntax highlighting anyway....?)

    Obviously, the array reference at the end is what breaks the string. Not only that, but since you're using single quotes as your string delimiter, the string isn't even being parsed for variables (so $ID is left as a literal dollar sign followed by ID).

    I would suggest you read up on how to form a [man]string[/man] properly. I would also suggest you use concatenation when referencing arrays:

    $string = 'This is my array: ' . $myArray['test'] . ' !';

    Also, do you mean that this query is in a loop, executed several times? If so, you could improve the efficiency and reduce overhead by running one single INSERT query that inserts multiple rows, ex.

    INSERT INTO myTable VALUES('row1', 'value1'), ('row2', 'value2'), ('row3', 'value3'), ...

      With so little information (no mention of what DBMS and API you are using, what is your relevant database schema, what exactly does $ID contain, what is $POST['categories'][$x] supposed to contain, etc), I would guess:

      $category = mysql_real_escape_string($_POST['categories'][$x]);
      $sql = "INSERT INTO cat_relations(relation_user_id,relation_cat) VALUES($ID, '$category')";

      Of course, you have to substitute the appropriate string escaping mechanism for your database API, and $ID may also need to be handled carefully.

        Thanks for the responses. Here is my looping I left out of my original message. Does this make what I'm asking any clearer? The 'categories' come from a SELECT field on a form where the viewer can pick multiple categories. Thanks again.

        for($x = 0;$x < count($POST['categories']);$x++){
        $sql = 'INSERT INTO cat_relations(relation_user_id,relation_cat) VALUES($ID,$
        POST['categories'][$x])';
        }

          So you could do something like this:

          $values = '';
          foreach($_POST['categories'] as $cat)
              $values .= '(' . $ID . ',' . mysql_real_escape_string($cat) . '), ';
          
          $sql = 'INSERT INTO cat_relations(relation_user_id,relation_cat) VALUES ' . rtrim($values, ', ');

          I added it into my code snippet here, but don't forget: never place user-supplied data directly into a SQL query; you must sanitize it first with a function such as [man]mysql_real_escape_string/man.

            Write a Reply...