PHP MySQL delete where values are equal to - php

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());
}

Related

Delete the row with the highest id in mysql, using 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.

PHP compare value from database

I have a form with more then 4 fields and all data inserted into those fields are related, so i want to achieve something different.
For example - I have 4 fields with names class class_time class_teacher & batch_name and each time i fill and submit the form the data will be submitted into database, basically it's a time-table script.
So if first time i added maths 12-01 ashok IAS these values and submitted the form and it got saved, now if second time i add same time and teacher name with different batch then it should show an error and form should not submit, because same teacher can not appear at two different classes at the same time. How could i achieve this with PHP.
Here are some code which i tried.
$sql2 = "SELECT * FROM `s_timetable`";
$res = mysql_query($sql2) or die(mysql_error());
$fetch_data = mysql_fetch_array($res);
if ($fetch_data['class_info'] && $fetch_data['teacher_info']) == $_POST['class'] && $_POST['teacher']
{
}
before inserting new data you can check the things by below given query and if that query return more than 0 rows you can show an error message
select * from `tablename` where `class_time` = '".$class_time."' and `class_teacher`='".$class_teacher."'
You shouldn't use any mysql_*-functions. They have been deprecated since php 5.5 and completely removed in latest php versions
Instead of doing this in PHP you could just add a composite unique key that would not allow having the same teacher at the same time in the database.
ALTER TABLE s_timetable ADD CONSTRAINT myUniqueConstraint UNIQUE(class_time, class_teacher);
Now everytime you would try to insert new data it would return an SQL error if the same teacher is there at the same time.
Multiple column index documentation
You need to check first that user is already in the table or not.
$sql = mysql_query("select * from table_name where class_time ='" . $_REQUEST['class_time'] . "' AND class_teacher ='" . $_REQUEST['class_teacher'] . "'");
$record = mysql_num_row($sql);
if ($record) {
echo "Record already exits";
exit();
} else {
//insert query
}
Note : Stop using mysql it is deprecated.
Simply add a query that will select class_time and class_teacher so that if it already exist you can produce an error msg.
$checksched = mysqli_query($con,"SELECT * FROM s_timetable WHERE class_time = '".$inputted_time."' and class_teacher = 'inputted_teacher' ")
$match = mysqli_num_rows($checksched);
if ($match > 0){
echo "<script>
alert('Teacher already exist!');
</script>";
}

$_SESSION storing wrong value

I made a portal where i have to fetch result with primary key as id i am using it everywhere storing it in a variable however there is a certain problem that i am facing
$sql="SELECT users from hostelusers WHERE users Like'%$roll%'";
$result = mysql_query($sql) or die(mysql_error());
$rows=mysql_fetch_row($result);
$uid=$rows[0];
$_SESSION['uid']=$uid;
In my code the variable $uid is echoing out values of column 1 ie users however I have selected column 0 which is id(in the table in mysql)
can't think of any mistake there
your mysql query string is wrong . You are using :
$sql="SELECT users from hostelusers WHERE users Like'%$roll%'";
And how do you expect to get id field in the result ??
Moreover you will be having only a single column [field] in your rows[] and that is rows[0]
if you want to use rows[0] to get your id field
Change your query to this
$sql="SELECT id from hostelusers WHERE users Like'%$roll%'";
or this:
$sql="SELECT * from hostelusers WHERE users Like'%$roll%'";
and it will work for sure

Randomly pairing users only in PHP - solution

So i wanna pairing users only in PHP:
First, get one avaliable user id //right now not random
mysql_query('SELECT id FROM users WHERE state="0" LIMIT 1'); //state 0 = user avaliable, 1 = talking/playing with someone
$available_id = stuffs to get id from query
And then update:
$result = mysql_query('UPDATE INTO users SET state="1" WHERE (id=$available_id OR id=$my_id) AND state="0"');
if $result == false then it mean that no one row has updated. So back to First step,
if $result == true then what? it can mean that my row has updated or available user, or both. I am confused how to done with it.
mysql_query returns false for error. You can check the count of updated rows using mysql_affected_rows
you can use mysql_num_rows();
http://php.net/manual/en/function.mysql-num-rows.php and mysql_affected_rows(); http://php.net/manual/en/function.mysql-affected-rows.php
your query seems wrong $result = mysql_query('UPDATE INTO users SET state="1" WHERE (id=$available_id OR id=$my_id) AND state="0"'); remove into
Try this code
$first=mysql_query('select id from users where state =0 limit 1');
$available=mysql_fetch_row($first);
$available_id=$available['id'];
$result = mysql_query('UPDATE INTO users SET state="1" WHERE
(id=$available_id OR id=$my_id) AND state="0"');
No,
It is like this
INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on
success or FALSE on error.
if the mysql_query return FALSE means you query get failed and have syntactical error, if TRUE, that means the query ran successfully but that does not mean that the row is updated.
You can really check a row is updated or not with mysql_affected_rows after the successfully execution of UPDATE query
$id = mysql_query('SELECT id FROM users WHERE state="0" LIMIT 1');
$uid = mysql_fetch_array($id);
$id2 = mysql_query('SELECT id FROM users WHERE status="0" AND `id`!='".$uid."' ORDER BY rand LIMIT 1');
$uid2 = mysql_fetch_array($id2);
mysql_query("UPDATE user SET `user`='1' WHERE `id` IN($uid,$uid2)");
and pair it in your pair table.

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;

Categories