I'm working on a really simple minichat program ( php/mysql
) which displays the last 10 messages.
I wanted to add a button to delete the last message (using a form, leading to a php
file like the one under).
I'm really a beginner with php
and mysql
so, I don't understand why it doesn't work.
Follows my code:
<?php
// Create connection
$cn = new mysqli("localhost","root","","test");
// Check connection
if($cn->connect_error)
{
echo "Connection failed : " . $cn->connect_error;
}
$sql = "DELETE FROM `minichat` WHERE `minichat`.`id` = ('SELECT MAX(`id`) FROM `minichat`')";
if($cn->query($sql) === TRUE){
echo "Deleted succesfully";
}
else
{
echo "Error deleting record: " . $cn->error;
}
//header('Location: connexion.php');
?>
According to the manual on DELETE Syntax :
Subqueries
You cannot delete from a table and select from the same table in a subquery.
So instead you should do something like:
DELETE FROM minichat ORDER BY id DESC LIMIT 1
And you probably want a condition to make sure a user can only delete his / her own comment..
You should remove the single quote around the subselect
"DELETE FROM `minichat` WHERE `minichat`.`id` = (SELECT MAX(`id`) FROM `minichat`)"
Otherwise you have WHERE minichat
. id
= 'mi string text'
and for fact that you can delete from a sub query you can try
DELETE
FROM `minichat`
WHERE `minichat`.`id` = (select t.id from (SELECT MAX(`id`) FROM `minichat`) t)
This is expected to exceed the limit for delete with subquery
You could try and set up a variable which collected the ID you want. Then you can refer to that variable as the ID you want to delete.
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.