0

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 !

Chathurika
  • 419
  • 2
  • 6
  • 18

4 Answers4

2

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

Community
  • 1
  • 1
Murad Hasan
  • 9,565
  • 2
  • 21
  • 42
1

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.

1

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());
}
Webeng
  • 7,050
  • 4
  • 31
  • 59
  • Definitely, now I have fixed my problem by this way, thank u – Chathurika May 26 '16 at 09:37
  • @Chathurika awesome no problem! Oh and if this answer is the one that worked for you, please accept it (with a green checkmark) so that users know it worked for you :) – Webeng May 26 '16 at 18:04
1

You Should Use 'UPDATE' instead of 'INSERT'

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

Hope It will Work.

Sunil Rajput
  • 960
  • 9
  • 19