简体   繁体   中英

SQL syntax error in PHP Mysql

I have been getting a sql syntax error with the below line in my php script

mysqli_query($con, "INSERT INTO 'rates_{$tablename}' (Weight, CBMMin, CBMMax) VALUES (".$row['weight'].",".$row['cbm_min'].",".$row['cbm_max'].");");

The error:

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 ''rates_woop' (Weight, CBMMin, CBMMax) VALUES (1000,0.1,2.3)' at line 1

the variable $con is my connection which works fine

$tablename is just a string

$row[''] is a row from an array structured like below

$rows = array(
array('weight' = > 1000, 'cbm_min' = > 0.1, 'cbm_max' = > 2.3),
array('weight' = > 1500, 'cbm_min' = > 2.31, 'cbm_max' = > 3.5),
array('weight' = > 2000, 'cbm_min' = > 3.51, 'cbm_max' = > 4.6),
array('weight' = > 2500, 'cbm_min' = > 4.61, 'cbm_max' = > 5.75),
array('weight' = > 3000, 'cbm_min' = > 5.75, 'cbm_max' = > 6.9),
array('weight' = > 3500, 'cbm_min' = > 6.91, 'cbm_max' = > 8));

So the query is within a foreach loop

Don't quote the table name:

mysqli_query($con, "INSERT INTO rates_{$tablename} (Weight, CBMMin, CBMMax) VALUES (".$row['weight'].",".$row['cbm_min'].",".$row['cbm_max'].")");

If you want, use the ` :

mysqli_query($con, "INSERT INTO `rates_{$tablename}` (Weight, CBMMin, CBMMax) VALUES (".$row['weight'].",".$row['cbm_min'].",".$row['cbm_max'].")");
<?php

$rows = array(
                array('weight' => 1000, 'cbm_min' => 0.1, 'cbm_max' => 2.3 ),
                array('weight' => 1500, 'cbm_min' => 2.31, 'cbm_max' => 3.5 ),
                array('weight' => 2000, 'cbm_min' => 3.51, 'cbm_max' => 4.6 ),
                array('weight' => 2500, 'cbm_min' => 4.61, 'cbm_max' => 5.75 ),
                array('weight' => 3000, 'cbm_min' => 5.75, 'cbm_max' => 6.9 ),
                array('weight' => 3500, 'cbm_min' => 6.91, 'cbm_max' => 8 )
            );

// Create connection
$con=mysqli_connect("localhost","root","","test");//place your host name username and password

// Check connection
if (mysqli_connect_errno($con))
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
//$result = mysqli_query($con,"SELECT * FROM mytb "); 

foreach ($rows as $row)
{
$weight=$row['weight'];
$cbm_min=$row['cbm_min'];
$cbm_max=$row['cbm_max'];
$query="insert into mytb values ('$weight','$cbm_min','$cbm_max')";//place your table name over there
mysqli_query($con,$query);
}

?>

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