Call a PHP function inside of a while loop - php

I have a function which gets a particular set of users from a table where a particular WHERE condition is meet.
I need to send each of them a message.
So, I used another function to send the message. And called that function inside he following while loop
while($user= mysqli_fetch_assoc($users_set)){
send_message($user['email']);
}
So, the problem is, the function is called only just one time. (Only with the last value of the loop)
How to fix this problem and make the function called with each value of the loop...
This is the full code...
$query = "SELECT * ";
$query .= "FROM user ";
$query .= "WHERE confirmed = 0";
$user_set = mysqli_query($db_conx, $query);
confirm_query($user_set);
while($user = mysqli_fetch_assoc($user_set)){
send_message($user['email']);
}
Here is the send message function....
function send_message($email){
global $db_conx;
$invitee_user = get_user_by_email($email);
$query5 = "INSERT INTO notification(";
$query5 .= "description, user_id";
$query5 .= ") VALUES(";
$query5 .= "'You have been confirmed'";
$query5 .= ", {$invitee_user['id']}";
$query5 .= ")";
$result5 = mysqli_query($db_conx, $query5);
if($result5){
//$_SESSION["message"] = "Notification sent". \mysqli_error($db_conx);
return "OK";
}else{
//$_SESSION["message"] = "Failed to send notification". mysqli_error($db_conx);
}
}
Here is the code for confirm_query()
function confirm_query($result_set){
if(!$result_set){
die("Fatal Error Occured : Database Query Failed Report this error");
}
}

I would just boil this down to one query and get rid of all the looping stuff
INSERT INTO notification (description, user_id)
SELECT 'You have been confirmed', user_id
FROM user
WHERE confirmed = 0
Your current logic is really convoluted.
You query the user table to get the user email field, then pass that email as parameter to your function only to then turn around and (I presume) look up the user ID based on email (when you already had this information from your initial query), then you make insert.
This means that for every record you return from first query, you need to do 2 queries to insert to the notification table. So if you had 100 results you would end up doing a total of at least 201 queries to complete the insertions.
Using my approach you make 1 query regardless of how many rows are affected.
One takeaway that you should get from this is that, anytime you see yourself trying to do some sort of nested querying, you should recognize this as an anti-pattern (a coding pattern that you do not want to typically use). There is usually a better approach that can be taken if you rethink how you are writing your queries.

Related

How can I get the data if I delete it and insert it to another table?

I have a little project which have item management and log history.
Item Management
Item Log
My problem is if I delete the data the last item name that I added is getting inserted in log history instead of the item name that I deleted.
How can I fetch the last item name that I deleted?
Here is my codes on delete button
if(isset($_GET['delete'])) {
$the_item_management_id = $_GET['delete'];
$query = "DELETE FROM item_management WHERE item_management_id = {$the_item_management_id}";
$delete_query = mysqli_query($connection, $query);
$query1 = "INSERT INTO item_management_log (item_code_id, item_name, deleted_stock) VALUES ('$item_code_id', '$item_name', 'deleted $item_name from the stock')";
mysqli_query($connection, $query1);
header("Location:inventory_management.php");
}
I believe you could do this:
if (isset($_GET["delete"])) {
mysqli_begin_transaction($connection); // Using transactions.
// Execute log insertion first.
$stm_log = mysqli_prepare($connection, "INSERT INTO item_management_log (item_code_id, item_name, deleted_stock) VALUES (?, ?, ?)");
$log_message = "deleted $item_name from the stock";
mysqli_stmt_bind_param($stm_log, "iss", $item_code_id, $item_name, $log_message);
mysqli_stmt_execute($stm_log);
// Remove the item later.
$stm_delete = mysqli_prepare($connection, "DELETE FROM item_management WHERE item_management_id = ?");
$the_item_management_id = $_GET["delete"];
mysqli_stmt_bind_param($stm_delete, "i", $the_item_management_id);
mysqli_stmt_execute($stm_delete);
if (mysqli_stmt_affected_rows($stm_delete) > 0) {
mysqli_commit($connection);
} else {
mysqli_rollback($connection); // Undo everything if nothing was deleted.
}
header("Location:inventory_management.php");
}
Why Transactions
You should use transactions because you probably want to log something that actually happened, and so you can abort (through rollback) recording the log if there is an error deleting the item. This way, you won't have an inaccurate log in the database.
Note
I also used mysqli_stmt_affected_rows which makes it possible to know the number of affected records and thus know if an item was really deleted or not.
Also, I believe you should use PDO instead of mysqli, which is a friendlier api. Or at least you should use the mysqli's object-oriented style, which will make your code cleaner and easier to understand.

PHP and MySQL not allowing Queries

I'm working on some code for a friend but my PHP code refuses to query the database even when I simplify it down to running without variables.
$sql = "SELECT message1, message2 FROM cards WHERE number = 5150671";
if ($conn->query($sql) === TRUE) {
Echo "Connection to the Database Success, Card Information Recieved.";
$Message1 = $_row["message1"];
$Message2 = $_row["message2"];
...etc
Full Code:
https://pastebin.com/jGs2xBFD
It returns a Query Failed error every time, the database, table, and rows are all named correctly and the values are in there.
cards #door_sign (localhost_3306) - Table
number message1 message2
5150671 1 2
any input would be greatly appreciated.
Missing something?
$result= $conn->query($sql);
while($row = $result->fetch_assoc()) {
//stuff for the thing
}

MYSQL: Saving various instances of players

I host multiple servers for multiplayer games and I am requiring some help with creating a PHP MySQL script.
I have made scripts for the game servers that output a few variables to a php script. These variables include the player name, a GUID number (Game User ID) and a couple other unimportant things. These are sent to the php script every time a player joins the server.
Anyway what I basically need it to do is every time a player joins the server it saves the player name, guid and join date/timestamp to a row in a MySQL table. The player will always have only one GUID code, which is sort of like their cd-key. What I have at this current time:
if ( $action == "save")
{
$name = mysql_real_escape_string($_GET['name']);
$guid = mysql_real_escape_string($_GET['guid']);
}
mysql_query("INSERT INTO `players` (`name`, `guid`) VALUES ('$name', '$guid') ON DUPLICATE KEY UPDATE `last_joined`=CURRENT_TIMESTAMP")or die(mysql_error());
echo "-10";
die();
Now, this works great as it is. But what I need it to do is; if the player comes on the server with a different name, it will log that instance into a new row and if they come on again with the same name it will update the same row with the current time stamp. And for instance, if they change their name back to the first name they use it will update the row that has that name recorded with the current time stamp.
The only thing I have tried is making the 'name' column, a primary key and on a duplicate entry it would update it. However if I did that and another player came on the server with the same name it would just update the last player's data.
So it needs to record every username a player uses.
There's probably quite a simple solution but I've never had the time to learn to MySQL and I need this done soon.
Thanks for any help.
Make the GUID the primary unique key.
Then instead of just inserting the row, check if that guid exists in the database first and then if it does, update the row. If it doesn't then you can insert it.
You can take a shot for this:
$guid = mysqli_real_escape_string($conn, $_GET["guid"]);
$name = mysqli_real_escape_string($conn, $_GET["name"]);
if (!empty($guid) && !empty($name)) {
//Check if the user exists
$sql = "SELECT COUNT(*) AS cnt FROM players WHERE guid = " . $guid;
$res = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($res);
if ($row['cnt']) {
//If yes, update
$sql = "UPDATE players SET `last_joined` = NOW()
WHERE `guid` = " . $guid;
} else {
//If no, insert
$sql = "INSERT INTO players (`guid`, `name`, `last_joined`)
VALUES (" . $guid . ", '" . $name . "', NOW())";
}
mysqli_query($conn, $sql);
echo "-10";
die();
} else {
echo 'Missing parameter';
die();
}
NOTE:
I am using mysqli fucntions, because mysql functions are deprecated. You can use PDO also.

Check if an user is in a database

I have developed a game with Javascript and when the user finishes it, I must save his record in a database. Here you see the code:
$temp = $_POST['playername']; //username
$text = file_get_contents('names.txt'); //list with all usernames
//this text file contains the names of the players that sent a record.
$con=mysqli_connect("localhost","username","pass","my_mk7vrlist");
if (stripos(strtolower($text), strtolower($temp)) !== false) {
//if the username is in the list, don't create a new record but edit the correct one
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game` SET `record` = '".$_POST['dadate']."' WHERE `mk7game`.`playername` = ".$temp." LIMIT 1 ");
} else {
//The username is not in the list, so this is a new user --> add him in the database
mysqli_query($con, "INSERT INTO `mk7game` (`playername`,`record`,`country`,`timen`) VALUES ('".$_POST['playername']."', '".$_POST['dadate']."', '".$_POST['country']."', '".$_POST['time_e']."')");
file_put_contents("names.txt",$text."\n".$temp);
//update the list with this new name
}
//Close connection
mysqli_close($con);
When I have a new user (the part inside my "else") the code works correctly because I have a new row in my database.
When the username already exists in the list, it means that this player has already sent his record and so I must update the table. By the way I cannot edit the record on the player that has alredy sent the record.
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game` SET `record` = '".$_POST['dadate']."' WHERE `mk7game`.`playername` = ".$temp." LIMIT 1 ");
It looks like this is wrong, and I can't get why. I am pretty new with PHP and MySQL.
Do you have any suggestion?
You're missing quotes around $temp in the UPDATE statement:
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game`
SET `record` = '".$_POST['dadate']."'
WHERE `mk7game`.`playername` = '".$temp."'
^ ^
LIMIT 1 ") or die(mysqli_error($con));
However, it would be better to make use of prepared statements with parameters, rather than inserting strings into the query.
Escape your user input!
$temp = mysqli_real_escape_string($con, $_POST['playername']);
Make sure to stick your mysqli_connect() above that
$select = mysqli_query($con, "SELECT `id` FROM `mk7game` WHERE `playername` = '".$temp."'");
if(mysqli_num_rows($select))
exit("A player with that name already exists");
Whack that in before the UPDATE query, and you should be good to go - obviously, you'll need to edit it to match your table setup

Get subject from Table in PHP

OK So I'm trying to access a table called emg_quote I have the Quote ID so Im trying to get the Column Subject from the same row as this ID but for some reason All I'm getting is the first row in the entire table? Can any one figure out what I'm doing wrong? Here is my coding:
$row['quote_id'] = quoteTitle($row['quote_id']);
function quoteTitle($quoteid){
global $db;
$sql = "SELECT subject FROM emg_quote WHERE ".$quoteid."";
$res = $db->query($sql);
$row = $db->fetch_row();
$output = $row['subject'];
return $output;
}
Are you using a custom object to wrap the native API's?
Either way it doesn't look right to me. You don't seem to be using the result of the query.
i.e.
$result = $mysqli->query($query);
$row = $result->fetch_row();
You have few bad practices in your code.
A. You lie on $quoteid to give you the correct where syntax. ie: ID=123
This is an highly unsafe method, because the user can change the it to Some-Important-Details='bla'
To extract more details from this table or others.
B. You should ALWAYS escape characters when receiving data from user, otherwise you easily subjected to SQL-Injections. And believe me you don't want it.
you have to use the checking after where.
use you column name before your $quoteid variable
$row['quote_id'] = quoteTitle($row['quote_id']);
function quoteTitle($quoteid){
global $db;
$sql = "SELECT subject FROM emg_quote WHERE quoteid=".$quoteid." LIMIT 1 ";
$res = $db->query($sql);
$row = $db->fetch_row();
$output = $row['subject'];
return $output;
}
Remember : USE limit 1 when you search with primary key and you know that only 1 record will be searched. it reduce your processing time.
You might be missing the where column.
$sql = "SELECT subject FROM emg_quote WHERE quote_id=".$quoteid."";
^^^^^^^^
We also do not see weather something with your Db class is wrong.
You should in any case not directly put request variables into a database query.
$sql = "SELECT subject FROM emg_quote WHERE ID='".$quoteid."'";
You had not wrote your db fieldname in where condition

Categories