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.
Related
I have a table with a user id and a date, several users connect at the same time and only one user a day can do insert in the database.
I have a slow connection to the server and what it takes to do the select of the last entry, whether it has been today or not, since it can not be a primary key because the date can vary, sometimes it makes double registrations for the same day.
How can I do this so that this does not happen and I only insure an insert a day?
Thank you
Code:
<?php
$sql = "SELECT MAX(timestamp_pole) as last_pole FROM pole WHERE id_group = ". $id_grup;
$resultado = $mysqli->query($sql);
$resultado = $resultado->fetch_assoc();
$las_00 = date('Y-m-d');
$las_00 = strtotime($las_00);
if ($resultado['last_pole'] >= $las_00){
} else {
$sql = "INSERT INTO pole (timestamp_pole, id_user, id_group) VALUES (". $timestamp .",". $user['id'] .",". $id_group .")";
$mysqli->query($sql);
//return addslashes($sql);
if (isset($user['username']))
return "#". $user['username'] ." pole!";
else
return $user['name'] ." pole!";
}
?>
you can create unique index using (date, id_group) as key, by that way you can make sure that there isn't any duplicated date in same group. Also remember to implement try/ catch as running insert query.
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
I have to generate a random number which will be unique from the numbers stored in the mysql database. I have written the following function to generate. But it is not working.
function random(){
$invoice = rand(0,9999);
$check = mysql_query("SELECT order_ID FROM premises WHERE order_ID='$invoice'");
$match = mysql_num_rows($check);
echo $invoice;
echo "sdhfji";
if($match == 0){
mysql_query("INSERT INTO orders values('$invoice','$id','$name','$key_num')");
mysql_query("INSERT INTO persons values('$invoice','$fname','$lname','$address','$phone','$email'.'$business')") or die(mysql_error());
}else{
random();
}
echo $invoice;
}
It is not entering into the function. Please help me if there is any alternative way.
dFirst of, use mysqli since mysql is deprecated as of php 5.5 (to future proof your work).
I dont get what the purpose of this "random function" is, but I guess you simply want to insert a post into the database and insert "link" that post into another table?
/* cant figure out what the diffrenece in invoice and id is. Pls provice database-structure to improve this answer */
$query = "INSERT id (id, name, key_num )INTO orders values('$id','$name','$key_num')";
$mysqli->query($query);
//Get id from latest query
$latest_insert = $mysqli->insert_id;
$query = "INSERT INTO persons values('$last_id','$fname','$lname','$address','$phone','$email'.'$business')";
$mysqli->query($query);
I’ve created a little weekly trivia game for my website. Basically its five questions, then at the end the user can add their score to a scoreboard.
The problem is that I want the scores to carry from week to week and cumulate. So let’s say you got 4 points one week, then 5 points the next. I want the scoreboard to reflect you have 9 points.
So I created a small form with an i
nvisible field that has the users score, a field for the username, and a field for the e-mail address. Next week, when the user takes the quiz again, I want their score to be updated if the username and e-mail match a record in the database. If no record does match, I want an entry to be created.
Here’s the script I came up with, however, it doesn’t work (which doesn’t surprise me, I’m pretty new to PHP/MySQL)
$name = $_POST['name']; //The Username
$score = $_POST['submitscore']; //The users score (0-5)
$email = $_POST['email'];//Users email address
$date = date("F j, Y, g:i a");//The date and time
if($name != '') {
$qry = "SELECT * FROM scoreboard WHERE name='$name'";
$result = mysql_query($qry);
if($result) {
if(mysql_num_rows($result) > 0) {
$sum = ($row['SUM(score)']+$score);
"UPDATE scoreboard SET score = '$sum' WHERE name = '$name'";
}
else
$q = mysql_query("INSERT INTO scoreboard (`name`, `email`, `date`, `score`) VALUES ('$name', '$email', '$date', '$score');");
#mysql_free_result($result);
}
else {
die("Query failed");
}
}
My table scoreboard looks like this
id........name........email...........date...........score
1........J.Doe.....j.doe#xyz.com.....7/27/11.........4
You're looking for INSERT... ON DUPLICATE KEY syntax
"INSERT INTO scoreboard (`name`, `email`, `date`, `score`) ".
" VALUES ('$name', '$email', '$date', '$score') ".
"ON DUPLICATE KEY UPDATE `score` = $sum";
Aside:
Use mysql_real_escape_string!
$name = mysql_real_escape_string( $_POST['name'] );
$score = mysql_real_escape_string( $_POST['submitscore'] );
$email = mysql_real_escape_string( $_POST['email'] );
$date = date("F j, Y, g:i a");//The date and time
EDIT
First, this doesn't really work unless you have a column SUM(SCORE):
$sum = ($row['SUM(score)']+$score);
If you want the sum of a column, you need to put that in the MySQL query directly. If you just want the score for that row, however, you can use $row['score']. If you need to add to an existing score you don't need to select for the value (thanks to a1ex07 for pointing this out)
ON DUPLICATE KEY UPDATE `score` = $score + score
This line is incorrect:
$sum = ($row['SUM(score)']+$score);
You probably want to replace it by:
$sum = ($row['score']+$score);
As you are new to PHP/MySQL I recommend you to read about MySQL Injections as your queries contain potential risks.
I'd have a database table to hold quizzes; a database table for members; and a database table that contains foreign keys to both tables along with a score so only one record can be created for each member and each quiz.
I'd also save the score in a session when the user finishes the quiz so the user can't then just submit any old score to your database; the score entered is the score your application generated.
This way, you can then just query SUM(score) of a member based on that member's ID.
The 'id' field of my table auto increases when I insert a row. I want to insert a row and then get that ID.
I would do it just as I said it, but is there a way I can do it without worrying about the time between inserting the row and getting the id?
I know I can query the database for the row that matches the information that was entered, but there is a high change there will be duplicates, with the only difference being the id.
$link = mysqli_connect('127.0.0.1', 'my_user', 'my_pass', 'my_db');
mysqli_query($link, "INSERT INTO mytable (1, 2, 3, 'blah')");
$id = mysqli_insert_id($link);
See mysqli_insert_id().
Whatever you do, don't insert and then do a "SELECT MAX(id) FROM mytable". Like you say, it's a race condition and there's no need. mysqli_insert_id() already has this functionality.
Another way would be to run both queries in one go, and using MySQL's LAST_INSERT_ID() method, where both tables get modified at once (and PHP does not need any ID), like:
mysqli_query($link, "INSERT INTO my_user_table ...;
INSERT INTO my_other_table (`user_id`) VALUES (LAST_INSERT_ID())");
Note that Each connection keeps track of ID separately (so, conflicts are prevented already).
The MySQL function LAST_INSERT_ID() does just what you need: it retrieves the id that was inserted during this session. So it is safe to use, even if there are other processes (other people calling the exact same script, for example) inserting values into the same table.
The PHP function mysql_insert_id() does the same as calling SELECT LAST_INSERT_ID() with mysql_query().
As to PHP's website, mysql_insert_id is now deprecated and we must use either PDO or MySQLi (See #Luke's answer for MySQLi). To do this with PDO, proceed as following:
$db = new PDO('mysql:dbname=database;host=localhost', 'user', 'pass');
$statement = $db->prepare('INSERT INTO people(name, city) VALUES(:name, :city)');
$statement->execute([':name' => 'Bob', ':city' => 'Montreal']);
echo $db->lastInsertId();
As #NaturalBornCamper said, mysql_insert_id is now deprecated and should not be used. The options are now to use either PDO or mysqli. NaturalBornCamper explained PDO in his answer, so I'll show how to do it with MySQLi (MySQL Improved) using mysqli_insert_id.
// First, connect to your database with the usual info...
$db = new mysqli($hostname, $username, $password, $databaseName);
// Let's assume we have a table called 'people' which has a column
// called 'people_id' which is the PK and is auto-incremented...
$db->query("INSERT INTO people (people_name) VALUES ('Mr. X')");
// We've now entered in a new row, which has automatically been
// given a new people_id. We can get it simply with:
$lastInsertedPeopleId = $db->insert_id;
// OR
$lastInsertedPeopleId = mysqli_insert_id($db);
Check out the PHP documentation for more examples: http://php.net/manual/en/mysqli.insert-id.php
I just want to add a small detail concerning lastInsertId();
When entering more than one row at the time, it does not return the last Id, but the first Id of the collection of last inserts.
Consider the following example
$sql = 'INSERT INTO my_table (varNumb,userid) VALUES
(1, :userid),
(2, :userid)';
$sql->addNewNames = $db->prepare($sql);
addNewNames->execute(array(':userid' => $userid));
echo $db->lastInsertId();
What happens here is that I push in my_table two new rows. The id of the table is auto-increment. Here, for the same user, I add two rows with a different varNumb.
The echoed value at the end will be equal to the id of the row where varNumb=1, which means not the id of the last row, but the id of the first row that was added in the last request.
An example.
$query_new = "INSERT INTO students(courseid, coursename) VALUES ('', ?)";
$query_new = $databaseConnection->prepare($query_new);
$query_new->bind_param('s', $_POST['coursename']);
$query_new->execute();
$course_id = $query_new->insert_id;
$query_new->close();
The code line $course_id = $query_new->insert_id; will display the ID of the last inserted row.
Hope this helps.
Try like this you can get the answer:
<?php
$con=mysqli_connect("localhost","root","","new");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO new values('nameuser','2015-09-12')");
// Print auto-generated id
echo "New record has id: " . mysqli_insert_id($con);
mysqli_close($con);
?>
Have a look at following links:
http://www.w3schools.com/php/func_mysqli_insert_id.asp
http://php.net/manual/en/function.mysql-insert-id.php
Also please have a note that this extension was deprecated in PHP 5.5 and removed in PHP 7.0
I found an answer in the above link http://php.net/manual/en/function.mysql-insert-id.php
The answer is:
mysql_query("INSERT INTO tablename (columnname) values ('$value')");
echo $Id=mysql_insert_id();
Try this... it worked for me!
$sql = "INSERT INTO tablename (row_name) VALUES('$row_value')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
$msg1 = "New record created successfully. Last inserted ID is: " . $last_id;
} else {
$msg_error = "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Another possible answer will be:
When you define the table, with the columns and data it'll have. The column id can have the property AUTO_INCREMENT.
By this method, you don't have to worry about the id, it'll be made automatically.
For example (taken from w3schools )
CREATE TABLE Persons
(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (ID)
)
Hope this will be helpful for someone.
Edit: This is only the part where you define how to generate an automatic ID, to obtain it after created, the previous answers before are right.