Delete the row with the highest id in mysql, using php - php

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.

Related

how to get the NEXT AVAILABLE row / ID in a database as opposed to the LAST? [duplicate]

This question already has answers here:
Make auto increment fill previously deleted number [duplicate]
(3 answers)
Closed 2 years ago.
I am using the following code to know where to put my next post:
// Create connection
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM `wp_posts` WHERE ID = (SELECT max(ID) FROM `wp_posts`)";
$res = $link->query($sql);
while( $rs = $res->fetch_object() ) {
echo 'Last ID is: '. $rs->ID .' <br />';
$lastID = $rs->ID;
}
// Close connection
mysqli_close($link);
$ID_of_Next_Post = $lastID + 1;
echo 'Next post will go to ID: '. $ID_of_Next_Post .' <br />';
The issue I'm facing is that if I make a post that goes into, say, ID = 100 and then I delete that post, the next time this code is called $lastID will still equal 100 but the next post will go into 102 (because 101 was taken, even though it has been deleted and is not there anymore).
So how can I change my SQL query to find the NEXT AVAILABLE id so I know where the next post will go?
The ID row is set to auto-increment so it's tempting to not set the ID of the post but I need to know what the ID is so I can set interdependencies in other tables of the database.
First of all it should be stated, that it's better to just let the auto increment do its job, and leave the gaps there. But, if you insist on filling up every possible gap in the id-s, then this is how you could approach it:
SELECT (CASE WHEN `wpm`.`min_id` = 1 THEN MIN(`u`.`id` + 1) ELSE 1 END) as next_id
FROM `wp_posts` wp
LEFT JOIN `wp_posts` wp2 ON `wp2`.`id` = `wp`.`id`+1
LEFT JOIN (SELECT MIN(id) as `min_id` FROM `wp_posts`) as wpm ON 1
WHERE `wp2`.`id` IS NULL
This will pair up id-s with their subsequent id-s, and return the minimum of those that do not have a subsequent id on the table. Because of the nature of this, 1 being a missing id is a special case, so we have to account for that as well.
Maybe you can use this
select auto_increment from information_schema.TABLES
where TABLE_NAME ='tablename' and TABLE_SCHEMA='database_name';
and if you don't want to use information_schema then you can use
SHOW TABLE STATUS LIKE 'table_name'

PHP MySQL delete where values are equal to

I have a PHP chat script that calls a MySQL database when a user signs out to delete them from the database.
My script is:
if(isset($_GET['logout'])){
mysql_query("DELETE FROM users WHERE username='" .$user['username']. "' AND rank='0'");
header("Location: login_mini.php?logout=1");
}
What I want to do is delete the user if they have a rank of 0 when they leave. Why isn't this script working?
DELETE doesn't take column arguments
Remove the *
The syntax for MYSQL Delete example:
DELETE FROM somelog WHERE user = 'jcole'
ORDER BY timestamp_column LIMIT 1;
So you're query is wrong that's the reason why it is not running:
It should be
//without * and add quotes in your $user['username']
mysql_query("DELETE FROM users WHERE username=" .$user['username']. " AND rank='0'");
mysql_query("DELETE FROM users WHERE username='$user[username]' AND rank=0");
There is no * or any columns in DELETE operation because you are deleting the whole row(s).
Are you sure that users table have a record that have rank == 0 ?
Check it by
SELECT COUNT(*)
FROM users
WHERE rank='0'
then if there is check your variable $user['username'] if it has value.
var_dump($user);
then if both has value then try to execute this manually on your mysql
SELECT *
FROM users
WHERE username = #the value of the username
AND rank = '0'
If there is a result then maybe your PHP is throwing an error while executing the mysql_query. try to insert this code after the mysql_query
if (mysql_error()) {
die(mysql_error());
}

Copy added info from one mysql table to another in PHP

I have two tables in different mysql databases.
I would like to copy from table A to table B. Only one way.
I need to read last datetime from table B and then check if there any data added to table A after this readed datetime. If there is some data added, then copy it.
I tried this:
It writes one row if I refresh page, but I need it to write everything in one load!
do
{
#TABLE A
$querylastA = "SELECT * FROM `stock` ORDER BY `jrk` DESC LIMIT 1";
$resultlastA = mysql_query($querylastA) or die(mysql_error());
while($rows=mysql_fetch_array($resultlastA)){
$lastcodeA = $rows['datetime'];
}
#TABLE B
$querylastB = "SELECT * FROM `stockcopy` ORDER BY `jrk` DESC LIMIT 1";
$resultlastB = mysql_query($querylastB) or die(mysql_error());
while($rows=mysql_fetch_array($resultlastB)){
$lastcodeB = $rows['datetime'];
}
#TABLE A - NEXT DATE AFTER LAST DATE IN TABLE B
$querynextA = "SELECT datetime FROM stock WHERE datetime > '$lastcodeB' ORDER BY datetime ASC LIMIT 1";
$resultnextA = mysql_query($querynextA) or die(mysql_error());
while($rows=mysql_fetch_array($resultnextA)){
$nextcodeA = $rows['datetime'];
}
mysql_query("INSERT INTO stockcopy(datetime, data1, data2) SELECT datetime, data1, data2 FROM stock WHERE datetime = '$nextcodeA'");
echo "Date from table A " . $lastcodeA . "<br>";
echo "Date from table B " . $lastcodeB . "<br>";
}
while ('$lastcodeA' == '$lastcodeB');
You can insert data on a table using a SELECT statement, so all you need to do is put the condition in the SELECT.
For instance:
INSERT INTO table_example(foo, bar)
SELECT foo, bar FROM table_example2
WHERE time_condition > {SOME DATE}
This will insert into table_example the rows that the SELECT statement returns, which are the ones that satisfy the time condition. You will need to replace {SOME DATE} with an actual date (without brackets).
Also, please see: INSERT with SELECT
And also: Select columns across different databases
You can do this with little to no knowledge of SQL, but with a bit of creativity :)
Create a temporary table (table_c), and copy the contents of table_a there.
Then manually (this means by running delete queries in phpmyadmim) delete the information that doesn't matter anymore ( DELETE FROM table_c WHERE id < 1000 for example ).
Then, export the info from table_c and import it into table_b (and delete table_c
Problem was in: while ('$lastcodeA' == '$lastcodeB');
Changed it to: while ($lastcodeA != $lastcodeB); now it works! Thank you all :)

PHP/MySQL - Ordering rows

I'm using a row to return all of the users for a particular project, which isn't a problem. However, how would I order it so that the first result is always the logged in user.
I see two solutions, both of which I've tried with no success:
Printing the user's name then using an if statement to only print the rest of the row if they are different from the user's name.
print user's name;
if (username !== user's name) {
print this name;
}
Printing them all in a row but ordering it somehow so that the current user is at the top.
Any ideas?
EDIT
I'm trying it now with the following code:
$query7 = mysql_query("SELECT users_ID FROM projects_users WHERE projects_id = '$id' AND WHERE users_id <>'$q6[0]'") or die(mysql_error());
But I get the 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 'WHERE users_id <>'1'' at line 1
I've tried != and NOT instead of <> but I can't see what's going wrong!
Never mind, fixed it. For future reference, don't sure WHERE twice ;)
Thanks for your help everyone.
You first solution is perfect.
If you want to use your second solution you should build your SQL query like this:
(SELECT * FROM user WHERE id = :currentUserID) UNION (SELECT * FROM user)
And you are good
I think you could do this with a simple mysql query:
SELECT * FROM table_name ORDER BY FIELD(username, 'username');
To learn more:
http://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html
SELECT *
FROM USERS
ORDER BY (CASE user_id WHEN :currentUserID THEN 1 ELSE 2 END);
if you want to use php than, You can try something like this
$currentuser = "";
$otherusers = "";
if(username == user's name)
{
$currentuser = username;
}
else
{
$otherusers .= username;
}
echo $currentuser;
echo $otherusers;

How do I fetch the last record in a MySQL database table using PHP?

I want to fetch the last result in MySQL database table using PHP. How would I go about doing this?
I have 2 Columns in the Table, MessageID(auto) & Message.
I already know how to connect to the database.
Use mysql_query:
<?php
$result = mysql_query('SELECT t.messageid, t.message
FROM TABLE t
ORDER BY t.messageid DESC
LIMIT 1') or die('Invalid query: ' . mysql_error());
//print values to screen
while ($row = mysql_fetch_assoc($result)) {
echo $row['messageid'];
echo $row['message'];
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>
The SQL query:
SELECT t.messageid, t.message
FROM TABLE t
ORDER BY t.messageid DESC
LIMIT 1
...uses the ORDER BY to set the values so the highest value is the first row in the resultset. The LIMIT says that of all those rows, only the first is actually returned in the resultset. Because messageid is auto-increment, the highest value is the most recent one...
Records in a relational database do not have an intrinsic "order" so you cannot fetch the "last" record without some kind of ORDER BY clause.
Therefore, in order to fetch the "last" record, simply reverse the ORDER BY clause (change ASC to DESC or vice versa) then select the first result.
If you have an auto-increment field and you just want to find the last value that was inserted, you can use the fact that the auto-increment fields are ever-increasing (therefore the "last" one will be the one with the highest value) and do something like this:
SELECT *
FROM my_table
ORDER BY id_field DESC
LIMIT 1
Of course you can select the last row by sorting DESC in your query. But what if you want to select the first row and then the last. You can run a new query, but you can also use the function mysql_data_seek. check code below:
$result = mysql_query('YOUR QUERY') or die('Invalid query: ' . mysql_error());
$row_first = mysql_fetch_array($result);
mysql_data_seek($result , (mysql_num_rows($result)-1));
$row_last = mysql_fetch_array($result);
Hope this helps
The MySql query would look like this:
select MessageID, Message
from Table
order by MessageID desc
limit 1;
I am too rusty with PHP to give you the right syntax for executing this.
This query works because you have an auto-incrementing identifying field (MessageID). By ordering the results by that field in descending (largest to smallest) order we are effectively returning the records in the table in reverse order. The limit 1 clause simply limits the result set to one record - the last one in the table.
What do you mean by "the last result"? You need to precise a bit more.
Do you mean "the last entry I registered"?
In this case you should use the appropriate method (depending on the extension you are using) mysqli->insert_id OR mysql_insert_id.
If you mean "the latest entry in the table", an SQL query such as Andrew Hare's is just what you need.
Do you mean the last record or do you need the id of the most recently inserted record? For that you would use the PHP mysql_insert_id() function. Or if you are using the myusqli extension use $mysqli->insert_id.
for some reason (which I don't know why), my boss force me to get the data in this way:
$message_arr = array();
while ($row = mysql_fetch_assoc($result)) {
$message_arr['messageid']= $row['messageid'];
$message_arr['message']= $row['message'];
}
return $message_arr;
Of course, you need everything from OMG Ponies's answer I'm just telling you another way to do it =)
I hope this help.
You should use SELECT query. How SELECT works.
SELECT * FROM table - selects everything in a table (id, row 1, row 2,...)
SELECT id FROM table - selects only particular row from table.
If you now know, how to select, you can use additional logic.
SELECT * FROM table ORDER by id DESC LIMIT 1;
selects everything from table table, orders it by id - orders it DESCENDING and limits the query to only one result.
If you would do it like this:
SELECT * FROM table ORDER by id ASC limit 1; - you would get 1 entry into database.
You can order it by any row you want.
Hope it helps.
One thing to remember is that data does not get saved in the insertion order in any MYSQL database. So in order to get the last entered record u will have to have an auto increment field. Since there is an auto increment field in this table we are good to go.
The below script will help to get the last entered record
<?php
$sql = "SELECT * FROM table_name ORDER BY MessageID DESC LIMIT 2";
$result_set = mysql_query($sql);
if($result_set){
while($row = mysql_fetch_array($result_set)) {
echo "Message Id: ".$row['MessageID']."<br>";
echo "Message: ".$row['Message']."<br>";
}
//creating alert
echo "<script type=\"text/javascript\">alert('Data was Retrieved
successfully');</script>";
}
else{
//creating alert
echo "<script type=\"text/javascript\">alert('ERROR! Could Not Retrieve
Data');</script>";
}
?>
The query selects all the records in the table and orders them according to the descending order of the MessageID (as it is the auto increment field) and limits the returned result to only one record. So since the table is ordered according to the descending order of the MessageID only the last entered record will be returned.
NOTE: if you are using a newer version you will have to use mysqli_query($connection_variable,$sql); instead of mysql_query($sql); and mysqli_fetch_array($result_set) instead of mysql_fetch_array($result_set)
$result = mysql_query('select max(id) from your_table ') or die('Invalid query: ' . mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo $row['id'];
echo $row['message'];
}
//
//
mysql_free_result($result);
simple like that
this code of php works fine
SELECT t.messageid, t.message
FROM TABLE t
ORDER BY t.messageid DESC
LIMIT 1
if you don't have concurrent entries going into some table.b'cause concurrent entries may not go in accordance of their insertion order.
$statement = $PDO->prepare("
SELECT MessageID,
Message
FROM myTable
ORDER BY MessageID DESC
LIMIT 1;
");
$statement->execute();
$result = $statement->fetch(\PDO::FETCH_ASSOC);
echo $result['MessageID']." and ".$result['Message'];

Categories