Calling a function for each MySQL row - php

I have a standard MySQL database, with around 60 rows (as in user accounts). When I first made it I made the mistake of making session IDs the same as the simple account ID, now I want to fix my mistake and I am obviously not going to go through 60 rows to reset them different secure session IDs, so I am writing this function:
function generate_sessionid(){
return bin2hex(openssl_random_pseudo_bytes(32));
}
function assign_all_sessionids(){
$sessionid = generate_sessionid();
$conn = sql_connect();
$result = mysqli_query($conn, "UPDATE accounts SET sessionid='$sessionid' WHERE 1");
sql_disconnect($conn);
}
assign_all_sessionids();
Problem: Every account in the database gets the same random session ID as the rest. How do I make it recall the function for each row in order to allow it to be random for each row?

Try get user's count from DB and simply execute it N times
function assign_all_sessionids(){
$conn = sql_connect();
// getting users count
// here just change 'id' to your id parameter
$result = mysqli_query($conn, "SELECT id FROM accounts");
$arr = $result->fetch_array(MYSQLI_NUM);
// executing N times
for($i = 0; $i < $result->num_rows; $i++){
$sessionid = generate_sessionid();
// here just change 'id' to your id parameter again
mysqli_query($conn, "UPDATE accounts SET sessionid='$sessionid' WHERE `id`=".$arr[$i]);
}
sql_disconnect($conn);
}

You can do what you want by first setting all the session ids to NULL:
UPDATE accounts
SET sessionid = NULL;
Then, inside the loop:
UPDATE accounts
SET sessionid = '$sessionid'
WHERE sessionid IS NOT NULL
LIMIT 1;

Normally you don't want to execute queries in a loop, however in this case you need to get all of the current unique identifiers, loop and generate a new identifier and then update one:
function assign_all_sessionids(){
$conn = mysqli_connect('whatever...');
$select = mysqli_query($conn, "SELECT sessionid FROM accounts");
while(list($id) = mysqli_fetch_assoc($select)) {
$sessionid = generate_sessionid();
$update = mysqli_query($conn, "UPDATE accounts SET sessionid='$sessionid' WHERE sessionid='$id'");
}
}

Related

Problem with creating a function that checks for two variables and updates another variable

My variables in the mysql table are "usersEmail" "usersRefer and "usersPoint". I want to check the whole table if usersEmail = usersRefer on different rows then UPDATE the integer usersPoint on the row of both usersEmail and usersRefer. I want to check for one specific user, that is the value of the usersRefer checks the entire column of usersEmail to check if it matches.
Here's something that I tried out:
$sql = "SELECT * FROM walitlist";
if($result = $conn->query($sql)){
while ($row = $result->fetch_assoc()){
$pointSys = $row ["usersPoint"];
if ($row ["usersEmail"] = $row ["usersRefer"]){
$pointSys = "UPDATE waitlist SET usersPoint = usersPoint+100";
}
}
}
How can I make this work?

Trying to insert a random six digit code/number in mysql table but it is giving same for every new registered users

I am trying to insert 6 digits number in mysql table through php but every time I tried to register a new user, it is giving the same sequence of code.
I have done something like this
<?php
if(isset($_POST['generate']))
{
$num = (rand(111111, 999999));
file_get_contents("mylink");
$query = mysqli_query($con, "UPDATE users SET otp='".$num."'");
$qry_run = mysqli_query($con, $query);
header("location: otp.php");
}
?>
Because You Are not Put Any Condition in Your Query.
So now it will update all users and set same random number to all fields.
Build Query Like this
$query = mysqli_query($con, "UPDATE users SET otp='".$num."' WHERE USERID = 1 ");

Add value to a user not logged in using php

I have a table (users) with various users. if you refer someone to register it creates a referal id in a field (refcode) similar to your (id) in his/her profile. now when he/she is logged in, i want to add value to the referal's profile.
So basically i need to add value to a user not logged in.
here is my code.
$sql="SELECT * FROM users";
$val=(2);
$result=mysql_query($sql,$bd);
$data=mysql_fetch_assoc($result);
while ($array = mysql_fetch_array($result)) {
// equate the value to a variable to use outside
// this while loop
$acc_balance = $array['com_balance'];
$comm = $array {$_SESSION['refcode']};
$commision = $array['id'];
}
$remainder = $acc_balance + $val;
$update_query = mysql_query("UPDATE users SET com_balance = '". mysql_real_escape_string($remainder) ."'
WHERE id=refcode");
if ($update_query) {
print ""
A bunch of changes, marked by numbers:
$sql="SELECT * FROM users where userID='$_SESSION['refcode']'"; //#1
$val = 2; //#2 : Why do u need the ()?
$result = mysql_query($sql,$bd);
$data=mysql_fetch_assoc($result);
while ($array = mysql_fetch_array($result)) {
// equate the value to a variable to use outside
// this while loop
$acc_balance = $array['com_balance'];
$comm = $array{$_SESSION['refcode']}; //#3: I am not sure what you're doing here?
$commision = $array['id'];
}
$remainder = $acc_balance + $val;
$update_query = mysql_query("UPDATE users SET com_balance = '". mysql_real_escape_string($remainder) ."'
WHERE id=refcode"); // #4: where are you defining refcode? if variable, the query needs to be WHERE id='$refcode'");
if ($update_query) {
print "Update successful";
Firstly, change:
$sql="SELECT * FROM users";
as you do not need to loop through an entire table just to get the details of the user logged in. Something like this should do the trick:
$yourID=3;// Assume this is sanitized data from a cookie or a login script.
$sql="SELECT * FROM users where userID=$yourID";
Secondly, when you verify the login of the user who referred the next user, just add in a query like this:
$update_query = mysql_query("
UPDATE users SET
com_balance = (select * from (
select com_balance from users where id=$yourID))");
This will update the new user with the balance from the referring user (which seems to be what you want). You will need to use the double subquery to get past the annoying mysql bug/feature where it cannot update a table from a subquery on the same table unless you encapsulate it in a second subquery.

Updating records If ipAddress and playerName match

At the moment im sending scores and data to my database from my flash game, though every level completed is a new record.
feilds are set out like l1Score,l2Score,l3Score
im trying to figure out how to update records if the field ipAddress and playerName match the current $varibles.
UPDATE highscores SET l2Score = '$l2Score' WHERE ipAddress = "$ipAddress" && playerName = '$playerName'
I was thinking somthing along these lines, but could someone point me in the right direction please!
First you want to perform a query to check if there is already a score in place for that user & IP.
$sql = "SELECT * FROM highscores WHERE ipAdress = '$ipAdress' AND playerName = '$playerName'";
$result = mysql_query($sql, $con);
$row = mysql_fetch_assoc($result);
Now, if $row is empty then you want to insert a new record, else you want to update a previous record.
if($row == "")
{
$query = "INSERT INTO highscores (l2score, ipAdress, playerName) VALUES ('$l2score', '$ipAdress', '$playerName'";
} else {
$query = "UPDATE highscores SET l2Score = '$l2Score' WHERE ipAdress = '$ipAdress' AND playerName = '$playerName'";
You may need to edit this to fit with the specific query that you need.

How can I query the mysql database for a variable, if exists create another variable, if not insert?

say I have a variable
$id = mt_rand();
how can I query the mysql database to see if the variable exists in the row id, if it does exist then change the variable $id, once the variable is unique to all other stored ids, then insert it into the database?
Thanks you guys.
$con = mysql_connect("<host>","<login>","<pass>");
if ($con) {
mysql_select_db('<schemata>', $con);
$found = false;
while (!$found) {
$idIamSearching = mt_rand();
$query = mysql_query("SELECT count(*) FROM <table> WHERE <idColumnName>='".$idIamSearching."'");
$result = mysql_fetch_row($query);
if ($result[0] > 0) {
mysql_query("INSERT INTO <table> (<column>) VALUES ('".$idIamSearching."')");
$found = true;
}
}
mysql_close($con);
}
Your description is hard to understand, so, this is something that could give you pointers...
'SELECT COUNT(*) as count from table where row_id="'.$variable.'" LIMIT 1'
make sure to escape the variable if it's user input or if it's going to have more than alphanumeric characters
then fetch the row and check if count is 1 or greater than 0
if one, then it exists and try again (in a loop)
although, auto increment on the id field would allow you to avoid this step
$bExists = 0;
while(!$bExists){
// Randomly generate id variable
$result = mysql_query("SELECT * FROM table WHERE id=$id");
if($result){
if(mysql_num_rows($result) > 0){
$bExists = 1;
} else {
// Insert into database
$bExists = 1;
}
}
1 Randomly generate id variable
2 Query database for it
2.1 Result? exit
2.2 No result? Insert

Categories