简体   繁体   中英

Insert query with WHERE condition in mysql

I tried to insert data into mysql table with some where condition. But it makes some error which is

error on queryYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE 

I have tried following query,

if(isset($_POST['submit'])){
    $type=$_POST['leave_type'];
    $division=$_POST['division'];
    $number_of_date=$_POST['number_of_date'];

    $resul=mysql_query("SELECT * from employee where (division='$division' || division='all_dpt')") or die("query error".mysql_error());
    $result3 = mysql_fetch_array($resul);
    $emp_division=$result3['division'];
    $id=$result3['emp_id'];
    $annual_additional=$result3['annual_additional'];

    $value=$annual_additional+$number_of_date;

    if(($division==$emp_division || $division='all_dpt') && $type='Annual'){
        $result1=mysql_query("INSERT INTO employee (annual_additional) VALUES ('$value') WHERE emp_id='$id'")or die("error on query".mysql_error());
    }}

How can I fix it, please help !

You can't use INSERT.....WHERE , For Updating a row you need UPDATE....WHERE .

If you have the condition that you need to insert and if the key isn't exist then use the given example.

Demo for example:

INSERT INTO Users (id, weight, desiredWeight) VALUES(1, 160, 145) ON DUPLICATE KEY UPDATE weight=160, desiredWeight=145

Collected from: MySQL Insert Where query

with witch query you get the error?Insert? Futhermore, use mysql_real_escape_string or this: http://pear.php.net/package/DB for your querys.

IMPORTANT WARNING: mysql_query was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include mysqli_query() and PDO::query()

FOR EDUCATIONAL PURPOSES : this is how your code should look if you are using mysql_query:

//you should definitely create a function that sanitizes the users input
//so that you don't get hacked via sql injection:
$value = sanitize($value);
$id= sanitize($id);

$sql = "UPDATE employee SET annual_additional = '$value' 
WHERE emp_id='$id'";
if (!result = mysql_query($sql))
{
    die("query error".mysql_error());
}

You Should Use 'UPDATE' instead of 'INSERT'

UPDATE employee SET `annual_additional`='$value' WHERE `emp_id`='$id' 

Hope It will Work.

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