Click here to Skip to main content
15,882,209 members
Please Sign up or sign in to vote.
1.44/5 (2 votes)
See more:
I am trying to update table in database using php but it gives mysql error mentioned above.

What I have tried:

$conn = new mysqli(Host,Username,Password,Database);
    $que="UPDATE `spare_parts` SET 
 `item_name`='$item_name', `brand`='$brand',
 WHERE `id`='$id' LIMIT 1";
        $msg = 'alert("Record updated successfully");';
             $msg= $conn->error;
Updated 4-Feb-23 18:11pm
Richard MacCutchan 2-Oct-17 8:07am    
I suspect the use of back quotes is not correct. Check the documentation to be sure.
Member 13435586 2-Oct-17 8:33am    
This is not issue, because it works for others records but not working for some records it is one of them

1 solution

Probably, it's the data. If any of the data contains a quote character - "Mary's Beets" perhaps - it will terminate the input and the remained of the data will be used as SQL instructions. Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
A perfectly valid "delete the table" command
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?

See here: PHP: Prepared statements and stored procedures - Manual[^]
Share this answer
Member 13435586 2-Oct-17 8:48am    
How can i use "PHP: prepared statements" for update query? please give a code example
OriginalGriff 2-Oct-17 8:51am    
Follow the link, read and learn.
Member 13435586 2-Oct-17 9:02am    
Sir i used it as but it's not working when i press update button the screen clears
$stmt = $conn->prepare ("UPDATE spare_parts SET qty = ? WHERE id = ? ");
$stmt -> bindParam('ss', $qty,$id);
$stmt -> execute();
$result = $stmt->get_result();

$msg = 'alert("Record updated successfully");';

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900