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
Related
The problem is when i go to update a row from update.php page it is possible to update a row with same email and roll that has been inserted into the table before.
I want to add some conditions that will help me to prevent duplicating the same email and roll.
$exist_query = mysqli_query($link, "SELECT * FROM tbl_student WHERE st_email = '$_POST[email]'");
$row_cnt = mysqli_num_rows($exist_query);
if($row_cnt>=1){
throw new Exception('Email already exists');
}
else {
$query = "UPDATE tbl_student SET st_name = '$_POST[name]', st_roll = '$_POST[roll]', st_email = '$_POST[email]' WHERE id = $id";
$query_run = mysqli_query($link,$query);
$success_message = 'Data has been updaed successfully';
}
after using these codes
the table data is primarily looks like this.
when i tried to update Name from alexa to alex it tells that Email already exists
and i cannot update any of these fields.
I want to upadte data without duplicating the roll and email address.
How can i do that?
More to tell that when I changed the index of st_roll and st_email to UNIQUE it works without duplicating roll and email. After doing UNIQUE i tried this codes
$query = "UPDATE tbl_student SET st_name = '$_POST[name]', st_roll = '$_POST[roll]', st_email = '$_POST[email]' WHERE id = $id";
$query_run = mysqli_query($link,$query);
if($query_run){
$success_message = 'Data has been updaed successfully';
}
else {
throw new Exception('Data already exists');
}
i am only able to tell that data already exists.
But i want to be more specific that do the email is duplicating or the roll number is duplicating? What condition can i apply to be more specific?
N.B: Sorry for my bad English.
MAke Email UNIQUE
So no email adress can ever be double entered
With the following command you can make the column meail UNIQUE
ALTER TABLE student
ADD UNIQUE (email);
The portion that is trying to delete duplicate entries in the database seems incorrect. So I suppose I am asking what would be the correct way to do that in this example. I am not totally new to PHP , but this is beyond me. If you could please tell me what is wrong and how to fix that would be greatly appreciated.
Now on to what I am trying to accomplish. I have a multidimensional array filled with values that is generated by a function. What I am trying to do is if there is a value in the array that already exists in the database delete it. Code:
enter code here
if(is_array($items)){
$values = array();
foreach($items as $row => $value){
$rsn = mysqli_real_escape_string($connect, $value[0]);
$rank = mysqli_real_escape_string($connect, $value[1]);
$values[] = "('', '$rsn', '$rank', '')";
$sql = "SELECT id FROM users WHERE rsn = :rsn";
$query = $conn->prepare($sql);
$query->execute(array(":rsn" => $value[0]));
$results = $query->rowCount();
while($deleted = $query->fetch(PDO::FETCH_ASSOC)){
$sql = "DELETE FROM users WHERE id = :id";
$query = $conn->prepare($sql);
foreach($deleted as $delete){
$query->execute(array(':id' => $delete));
}
}
}
//user_exists_delete($conn, $rsn);
$sql = "INSERT INTO users(id, rsn, rank, points) VALUES ";
$sql .= implode(', ', $values);
if(!empty($rank)&& !empty($rsn)){
if(mysqli_query($connect, $sql)){
echo "success";
}else{
die(mysqli_error($connect));
}
}
}
EDIT: I have got it partially working now, just need it to delete all dupes instead of only one. I edited code to reflect changes.
There are a couple problems, if you didn't strip much of your original code and if you don't need to do more than just what you shown why not just send a delete instruction to your database instead of checking validity first?
You have
//Retrieve ID according to rsn.
$sql = "SELECT id FROM users WHERE rsn = :rsn ";
//Then retrieve rsn using rsn??? Useless
$sql = "SELECT rsn FROM users WHERE rsn = :rsn ";
//Then delete using ID, retrieved by rsn.
$sql = "DELETE FROM users WHERE id = :id";
All those could simply be done with a delete using rsn...
$sql = "DELETE FROM users WHERE rsn = :rsn";
The row won't be deleted if there are no rows to delete, you don't need to check in advance. If you need to do stuff after, then you might need to fetch information before, but if not, you can use that while still checking the affected rows to see if something got deleted.
Now, we could even simplify the script by using only one query instead of one per user... We could get all rsn in an array and then pass it to the DELETE.
$sql = "DELETE FROM users WHERE rsn in :rsn";
//Sorry not exactly sure how to do that in PDO, been a while.
I fixed it I just omitted the WHERE clause in the delete statement so all records are being deleted before that insert gets ran again.
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.
I have this DB table reset_attempts and inside it has an
id : int(10) auto_increment
reset_counter : int(10) default 1
reset_time : timestamp current_timestamp
ip : varchar(255)
and I have this simple php code
$sql = "SELECT * FROM reset_attempts WHERE ip = '$ip'";
$query = mysqli_query($db_conx, $sql);
$num_rows = mysqli_num_rows($query);
$row = mysqli_fetch_array($query);
$reset_counter = $row['reset_counter'];
$reset_time = $row['reset_time'];
if ($num_rows == 0) {
$sql = "INSERT INTO reset_attempts (reset_counter, reset_time, ip) VALUES ('1',now(),'$ip')";
$query = mysqli_query($db_conx, $sql);
} else if ($num_rows == 1) {
$reset_counter = $reset_counter + 1;
$sql = "UPDATE reset_attempts SET reset_counter = '$reset_counter', reset_time = now() WHERE ip = '$ip'";
$query = mysqli_query($db_conx, $sql);
}
This is just a piece of whole php file..this is only the problem code..of course it has the db connection and I take the ip correctly..The problem is when I hit submit it will execute the first if statement, it executes correctly except that the reset_counter value it passes it to DB always as zero and all the other fields are correctly.
When it executes the second if statement again it's not updating the reset_counter field and set it to zero. I don't know where is the problem. Maybe is so simple and I can't see it because I am searching it so much! Anyway thanks in advance!
As per discussion in comments (between the OP and I), the shown snippet of code works on its own and have determined that something else is causing this (in unshown full code).
Let's consider this question to be closed, until the rest of the (OP's) code can be investigated further.
Last two comments between OP and I:
Me: Ok, this is probably going to be my last suggestion, because I don't know what else could be causing this. Can you try and run that snippet on its own (your posted code), without the rest of your code, and see if it will work on its own? If it does work, then you'll know right away that something else in your full code is causing this.
OP: You are right..it was the last thought that did not came to my mid trying it pfff..the snippet works fine on it's own...so it's something else in my code as you said.. :/ I am sorry for that I didn't test it from start...at least now I know what to search..!
For the first time there is no record in the database for that ip so $row['reset_counter'] has value zero and you enter the value zero in the database. Then when you again submit then it fetches the same value from the database and as it enters 0 for reset_counter so when you do
$row = mysqli_fetch_array($query);
$reset_counter = $row['reset_counter'];
It fetches that row with 0 for reset_counter and update it to again zero
Update
Add these this inside else statement if you need it anywhere in your code otherwise remove this too
$reset_time = $row['reset_time'];
And remove
reset_counter = $row['reset_counter'];
Use this code
$sql = "SELECT * FROM reset_attempts WHERE ip = '$ip'";
$query = mysqli_query($db_conx, $sql);
$num_rows = mysqli_num_rows($query);
$row = mysqli_fetch_array($query);
if ($num_rows == 0) {
$sql = "INSERT INTO reset_attempts (reset_counter, reset_time, ip) VALUES ('1',now(),'$ip')";
$query = mysqli_query($db_conx, $sql);
} else if ($num_rows == 1) {
$reset_time = $row['reset_time'];
$sql = "UPDATE reset_attempts SET reset_counter = reset_counter+1, reset_time = now() WHERE ip = '$ip'";
$query = mysqli_query($db_conx, $sql);
}
I don't know exactly what goes wrong in your code but I think you are using too much PHP and too little MySQL. I have a couple of changes I would propose
First, most times you would do the update, right? Then I would just skip the SELECT, do the UPDATE and then ask the driver for number of rows updated. If it's 0 then do the INSERT.
Second. When you do the update just increment inside MySQL, no need to do that in PHP.
UPDATE reset_attempts SET reset_counter = reset_counter+1, reset_time = now() WHERE ip = '$ip';
Otherwise two parallel calls your page might just count as one in the database.
Third, if you reset_counter isn't already an integer change it. From your code it looks like it's a char or varchar and it just doesn't make any sense to store a counter as text.
Hello I’m working on a project (I’m a total newbie), here ‘s how the project goes…
I’ve created a Create User page, the user puts in the credentials and click on Create Account.
This redirects to another page (process.php) where all MySQL queries are executed-
Note: ID is set to Auto Increment, Not Null, Primary Key. All the data is inserted dynamically, so I don’t know which Username belongs to which ID and so on.
$query = “INSERT INTO users (Username, Something, Something Else) VALUES (‘John’, ‘Smith’, ‘Whatever’ )”
Everything gets stored into the “users” table.
Then it gets redirected to another page (content.php) where the User can review or see his/her credentials.
The problem is, I use SELECT * FROM users and mysql_fetch_array() but it always gives me the User with ID = 1 and not the current User (suppose user with ID = 11). I have no idea how to code this.
There are suppose 50 or more rows,
how can I retrieve a particular row if I don’t know its ID or any of its other field’s value?
You may use:
mysql_insert_id();
Get the ID generated in the last query. Reference: http://us1.php.net/mysql_insert_id
This function return the ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established.
Now you have the id, add that to your WHERE clause.
Note: It would be better if you use mysqli.
You are using mysql_fetch_array() just once, so it is getting you just one row.
what you are writing:
<?php
include('connection.php'); //establish connection in this file.
$sql = "select * from users";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo(row['id']);
?>
What should be there to fetch all the rows:
<?php
include('connection.php'); //establish connection in this file.
$sql = "select * from users";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo(row['id']);
}
?>
Now, what you need, is to get the user id of the registered user at that time.
For that, you need to create a session. Add session_start(); in your process.php and create a session there. Now to get the last id you have to make a query:
select *
from users
where id = (select max(id) from users);
Now this will give you the last id created. Store that in a session variable.
$_SESSION['id']=$id;
Now, on content.php add this:
session_start();
echo($_SESSION['id']);
You have to use WHERE:
SELECT * FROM users WHERE ID = 11
If you dont use WHERE, it will select all users, and your mysql_fetch_assoc will get you one row of all (ie. where ID = 1).
PS: mysql_* is deprecated, rather use mysqli_*.
Using mysql_ commands:
$query = "INSERT INTO users (`Username`, `Something`, `Something Else`) VALUES ('John', 'Smith', 'Whatever' )";
$result = mysql_query($query) or die( mysql_error() );
$user_id = mysql_insert_id();
header("Location: content.php?id=".$user_id);
Or another way to pass $user_id to your next page
$_SESSION['user_id'] = $user_id;
header("Location: content.php");
Using mysqli_ commands:
$query = "INSERT INTO users (`Username`, `Something`, `Something Else`) VALUES ('John', 'Smith', 'Whatever' )";
$result = mysqli_query($dbConn, $query) or die( printf("Error message: %s\n", mysqli_error($dbConn)) );
$user_id = mysqli_insert_id($dbConn);