Page 1 of 1

Help with SQL syntax error message

Posted: Mon Oct 05, 2009 12:06 pm
by phpBever
I can't figure out what the syntax error is in this code. This is the message I get:

Code: Select all

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 '['fac_id'])' at line 1
This is the code I'm using:

Code: Select all

$sqlDeleteAdvLink = "DELETE FROM tblStudFac WHERE stud_id = $stud_id";
        $resDeleteAdvLink = mysqli_query($mysqli, $sqlDeleteAdvLink) or die(mysqli_error($mysqli));
        $n = count($fac);
        for($i=0;$i < $n; $i++) {
            //echo $fac[$i]['fac_id'].$fac[$i]['fac_name'].$fac[$i]['advStatus']."<br />";
          if($fac[$i]['advStatus']=="True") {   
                $sqlInsertAdv = "INSERT INTO tblStudFac VALUES ($stud_id, $fac[$i]['fac_id'])";     
                echo $fac[$i]['fac_id'].$fac[$i]['fac_name'].$fac[$i]['advStatus']."<br />";
            $resInsertAdv = mysqli_query($mysqli, $sqlInsertAdv) or die(mysqli_error($mysqli));
            mysqli_free_result($resInsertAdv);
            }
      }
 
If I comment out line nine ( $resInsertAdv = mysqli_query($mysqli, $sqlInsertAdv) or die(mysqli_error($mysqli));), the code runs fine. In particular, line 8 correctly echos the relevant values. Also, the initial $sqlDeleteAdvLink seems to work fine.

As soon as I try to run it with line 9, however, I get the error message.
Can anyone see what's going wrong?

Thanks.

Re: Help with SQL syntax error message

Posted: Mon Oct 05, 2009 12:37 pm
by jackpf
Try putting curly brackets around your arrays in double quotes :)

Re: Help with SQL syntax error message

Posted: Mon Oct 05, 2009 8:47 pm
by phpBever
I'm not sure what you mean. Like this?

$sqlInsertAdv = "INSERT INTO tblStudFac VALUES ($stud_id, $fac{$i}{\"fac_id\"})";

Re: Help with SQL syntax error message

Posted: Mon Oct 05, 2009 8:52 pm
by phpBever
I figured out a work-around, but I still can't figure out why it's necessary or if it's necessary:

Code: Select all

$id = $fac[$i]['fac_id']; 
 $sqlInsertAdv = "INSERT INTO tblStudFac VALUES ($stud_id, $id)";   
Can anyone help on this?

Re: Help with SQL syntax error message

Posted: Tue Oct 06, 2009 5:33 am
by jackpf
Like this

Code: Select all

$sqlInsertAdv = "INSERT INTO tblStudFac VALUES ($stud_id, {$fac[$i]['fac_id']})";
PHP doesn't really like parsing arrays in double quotes...so you either need to concatenate them, or use curly brackets.

Re: Help with SQL syntax error message

Posted: Wed Oct 07, 2009 8:22 am
by phpBever
Thanks, jackpf. That works. By concatenate I take it you mean:

Code: Select all

$sqlInsertAdv = "INSERT INTO tblStudFac VALUES ($stud_id,". $fac[$i]['fac_id'].")";

Re: Help with SQL syntax error message

Posted: Wed Oct 07, 2009 10:16 am
by jackpf
Yeah, that also works. Just preference really :)