简体   繁体   中英

MySQL error at line 1 when I try to insert values

PHP Script:

<?php
include('connect.php');

if (isset($_POST['project_name'])){
    $name = $_POST['project_name'];
    $date = $_POST['date'];
    $amount = $_POST['amount'];
    $curr = $_POST['curr'];
    $spec = $_POST['spec'];
    $SQL = "INSERT INTO projects (name, date, currency, amount, specifications) VALUES '$name','$date','$amount','$curr','$spec'" or die(mysql_error()."update failed");
    $insert = mysql_query($SQL);    
    if($insert){
echo "Successful";
echo "<BR>";
echo "<a href='insert.php'>Back to main page</a>";
} else {
?>
A HTML FORM HERE
<?php
}
?>

NOTE: The connect.php file is working ok since I've used it before on other scripts but on the same server.

Every time I try to submit the form ( method = post ), I get this 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 ''sad','08/13/2013','244','dollars','sdasd'' at line 1 32767 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 ''sad','08/13/2013','244','dollars','sdasd'' at line 1 32767

What could be the problem?

INSERT INTO projects (name, date, currency, amount, specifications) VALUES( '$name','$date','$amount','$curr','$spec'")

(值后

While inserting, VALUES for a given row have to be enclosed in parenthesis.

INSERT INTO projects (name, date, currency, amount, specifications) VALUES  
    ('$name','$date','$amount','$curr','$spec')

In order to remember that, you simply have to remember that INSERT allow to add several rows, that's why each row has to be delimited by those parenthesis:

-- Just for the example, insert 3 time the same row
INSERT INTO projects (name, date, currency, amount, specifications) VALUES
    ('$name','$date','$amount','$curr','$spec'),
    ('$name','$date','$amount','$curr','$spec'),
    ('$name','$date','$amount','$curr','$spec');

BTW, please note that using string interpolation to build your query is a major risk of SQL injection. Please see How can I prevent SQL injection in PHP? for the details.

You are forgetting the ( & ) in your insert statement:

 $SQL = "INSERT INTO projects (name, date, currency, amount, specifications) 
         VALUES 
        ('$name','$date','$amount','$curr','$spec')" or die(mysql_error()."update failed");

You should pass the name value like 'sad' not ''sad'. Hope you can find the problem.

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