Randomly pairing users only in PHP - solution - php

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.

Related

Mysql update query for update all users data

I want a Mysql query to update all users 'status' filed in 'user' table. I can update one user by running following query.
Table
What I tried
update user set status = 1 where id = 1 and type = 'viber'
Do I need to run the above query inside a loop to update all users data?
I want a query like following
update user set status = 1 where id = 1 and type = 'viber' and id = 2 and type = 'twitter' ..
your help is much appreciated.
Just
update user set status=1;
Updates your whole table.
If you want to just update the status for all records then below query is useful for that.
update user set status=1;
The WHEREclause is used to extract only those records that fulfill a specified criterion. but here you don't want that .so just use this query to update all the records
update user set status=1;
just use:
$update = mysqli_query("UPDATE user SET status = 1")or die(mysqli_error());
if this not works, you can select all data and then update each row by setting user id like this :
$select = mysqli_query("SELECT * FROM user")or die(mysqli_error());
while($row = mysqli_fetch_array($select)){
$id = $row['id'];
mysqli_query("UPDATE user SET status=1 WHERE id='$id' ");
}

issue with SELECT COUNT(id)

I've been using this command to retrieve the number of the fields which have same email address:
$query = $db->query("SELECT COUNT(`user_id`) FROM `users` WHERE `email`='$email'") or die($db-error);
There are 3 records in users table with the same email address. The problem is when I put * instead of COUNT(user_id) it returns correctly: $query->num_rows gives 3 but when I use COUNT(user_id) then $query->num_rows returns 1 all the time. how can I correct this or where is my problem?
When you use $query->num_rows with that query it will return 1 row only, because there is only one count to return.
The actual number of rows will be contained in that query. If you want the result as an object, or associative array give the count a name:
$query = $db->query("SELECT COUNT(`user_id`) AS total FROM `users` WHERE `email`='$email'") or die($db-error);
And in the returned query total should be 3, while $query->num_rows will still be 1. If you just want the value a quick way would be using $total = $query->fetchColumn();.
As others have said though, be careful with NULL user ids, because COUNT() will ignore them.
Emails have to be uinque in users table. Thus, you need no count at all.
You ought to use prepared statements.
You shouldn't post a code that will never run.
Here goes the only correct way to run such a query:
$sql = "SELECT * FROM `users` WHERE `email`=?";
$stm = $db->prepare($sql);
$stm->execute([$email]);
$user = $stm-fetch();
(the code was written due to erroneous tagging. For mysqli you will need another code, but guidelines remains the same.)
Something like this
$sql = "SELECT * FROM `users` WHERE `email`=?";
$stm = $db->prepare($sql);
$stm->bind_param('s',$email);
$stm->execute();
$res = $stm->get_result()
$user = $res->fetch_assoc();
in $user variable you will have either userdata you will need in the following code or false which means no user found. Thus $user can be used in if() statement all right without the need of any counts.
In case when you really need to count the rows, then you use this count() approach you tried. You can use a function from this answer for this:
$count = getVar("SELECT COUNT(1) FROM users WHERE salary > ?", $salary);
That's the correct behaviour: If you use the COUNT function, the result of your select query will be just one row with one column containing the number of data sets.
So, you can retrieve the number of users with the given E-mail address like this:
$query = $db->query("SELECT COUNT(`user_id`) FROM `users` WHERE `email`='$email'") or die($db-error);
$row = $query->fetch_row();
$count = $row[0];
Note that this is faster than querying all data using SELECT * and checking $query->num_rows because it does not need to actually fetch the data.

Mysql update query, what if value didn't change? how do I check for that?

When executing UPDATE statement, if value is same as new value than rowCount doesn't change. But for purposes of my application this is also a success. So how do I check for successful update no matter if value changed or not?
$stmt = $conn->prepare('UPDATE users SET name = :name WHERE id = :id');
$result = $stmt->rowCount(); // 1
if ($result == 1) {echo "success!";}
You're not executing the query, merely preparing it. So rowCount() will report an invalid number of rows (the one referring to the last executed query), since no rows were affected yet, and the system doesn't know beforehand how many will be, once you execute the prepared statement with specific param values.
You should check for success upon executing the statement. The execute() method will return true if it succeeds and false otherwise. So if execution success is the only thing you need, then you should do it along the lines of:
$stmt = $conn->prepare('UPDATE users SET name = :name WHERE id = :id');
$result = $stmt->execute($params); // <-- execute first!
if ($result) {echo "success!";}
I agree with Legionar. But instead of count I used to add a column that contains the last update time. So that I can use that to get the entries that got updated after a specific time. In this way I able to reduce the number of entries send to client. The final decision is based on your requirement.
$stmt = $conn->prepare('UPDATE users SET name = :name, updateTime = currentTime WHERE id = :id');
$result = $stmt->rowCount(); // 1
if ($result == 1) {echo "success!";}
I think this cant be done normally, but you can use another column for help.
Add column counter to your users table. And then just increase this value on each update.
$stmt = $conn->prepare('UPDATE users SET name = :name, counter = counter + 1 WHERE id = :id');
$result = $stmt->rowCount(); // 1
if ($result == 1) {echo "success!";}
So now, doesnt matter, if value name will change or not, counter will change each time, so it will return each time 1 if successed.
Or also as Damodaran answered, instead of counter you can use current datetime when doing update.

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

how UPDATE mysql row plus one and get the value

I updated with success
$result = mysql_query("UPDATE $table SET `queue2` = `queue2` + 1 WHERE `id` = '$getid'");
but how can I get the "queue2" value without opening a new request to MySQL
I can simply get the new value with this command
$selresult = mysql_query("SELECT * FROM $table WHERE `id` = '$getid'") or die(mysql_error());
but I'm afraid that the database can get new update again and i will get higher number
Any idea how to do it ?
you can use query to update the value.
mysql_query("UPDATE user_profile SET userpoints = userpoints + 1 WHERE user_id = '".$user_id."'");
See URL:-
PHP + MySQL transactions examples
Try this:-
printf ("Updated records: %d\n", mysql_affected_rows());
mysql_query("COMMIT");
You will need to use a transaction between the queries to be certain.
The docs for transactions are here. A good SO question that covers it in detail: PHP + MySQL transactions examples
Edit:
Looking at it from a different angle, why don't you do it in reverse though? It might save the need for a transaction (thought it is possible that you get multiple reads before a write):
Get the value for your queue2 value to display in the page from this:
mysql_query("SELECT * FROM $table WHERE `id` = '$getid'");
You have the true value now, so you can run:
$result = mysql_query("UPDATE $table SET `queue2` = `queue2` + 1 WHERE `id` = '$getid'");
No transaction and you know the value of the data before the update.

Categories