How to give the users the ability to update their information - php

Hey guys I am new to programming and I have a quick question and hopefully it isnt too much. I am trying to give users of my test website to have the ability to update their information. I use the following code:
$mysqli = mysqli_connect('localhost', 'root', 'testpass', 'testdatabase')
or die(mysqli_error());
echo "<h2>How would you like to update your account $_SESSION[username]?</h2>";
$display = <<<END
<h4> Update your username here: <br/></h4>
<form method="POST" action="$_SERVER[PHP_SELF]">
<input type="text" name="update_username"/>
<input type="submit" name="submit" value="Update"/>
</form>
END;
echo $display;
$update_username = $_POST['update_username'];
$current_username = $_SESSION['username'];
$sql_update = "UPDATE users SET username = '$update_username' WHERE username = '$current_username'";
$result_update = mysqli_query($mysqli, $sql_update) or die (mysqli_error($mysqli));
The code above updates their information, but it only updates once. When I check the database after updating it, it changed to whatever I changed it too. Then I try and changed it again but it doesnt change, so I log out and log back in. When I log back in I change it, but this time, when I look at the database, there is no username. I log back out and log back in again. I change it again and it actually changes. I have to go through this same process everytime I try and change the username(or any other sort of information) and it gets very annoying. Do you guys have any ideas on why it is doing this?Thanks!

For database stuff, you want to track everything by IDs, so the first field in most every table will be 'id', set as primary key with auto increment. Then when updating you would do WHERE id = $userID. When they login, the user id would be stored in the session as well as username, and any queries would reference them by id. It also makes it a lot easier/faster to query/track stuff when you start doing table joins

try the following
END;
echo $display;
$update_username = $_POST['update_username'];
$current_username = $_SESSION['username'];
$current_id = mysql query select id where username = $current_username
$sql_update = "UPDATE users SET username = '$update_username' WHERE id = '$current_id'";
$result_update = mysqli_query($mysqli, $sql_update) or die (mysqli_error($mysqli));
hope you can fix my pseudo code in $current_id variable

Related

PHP database user selection

Alright, so I have setup a very simple login in and sign up database, it is working perfectly.
However, one of the page I have created where users can check their acccount information (Username and Email) is not working fully.
I have a database that has four columns ID, username, email and password.
All I am doing is taking the user information from the database (Who is logged in) and displaying their username and email on the page.
The problem is that the code is logging every user within the database, I only want it to select one user (The user that is logged in.)
Code:
<?php
// SQL query
$strSQL = "SELECT * FROM users";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
echo $row['email'] . "<br />";
echo $_SESSION['username'];
}
// Close the database connection
mysql_close();
?>
I'm thankful for the help !
You probably need to store the username value in a $_SESSION in your login session.
if (!isset($_SESSION)) {
session_start();
$_SESSION['id'] = the_id_of_your_logged_username;
}
Then using the value that is stored in the $_SESSION to retrieve the logged user.
session_start();
$id = $_SESSION['id'];
$query = "SELECT * FROM users WHERE id='$id'";
In these way, you can retrieve the logged user, just commonly on how users login and gets their profile directly.
Your SQL query should look something like this...
"SELECT * FROM users WHERE ID = '$user_id'"
Remember to fix any SQL vulnerabilities
$user_id = mysql_real_escape_string($user_id);

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

MySQL Insert/Update issue

So right now I'm working on a basic session system for my C# Application. I have a table with id,username, password and a session table with id, code, start.
the id columns of both tables are relative to the user logged in (id of user table is the same as session table). What I want to do is that when it sets the session it first checks to see if a session is already active, if it is then it will just update the current one, if there isn't one it will insert a new one. This works fine. My problem is that no matter what user I log in as the id is always set to 0 so I can have a max of one session active at a time.
Here is what I am currently doing:
//get id of inputted user.
$id = getUserId($username);
//first check if a session already exists that is connected to this username
$query = mysql_query("SELECT * FROM sessions WHERE(`id`='$id')") or die("Couldn't query database: <br> <br> " . mysql_error());;
if(mysql_num_rows($query) > 0) {
//session already exists, update it.
mysql_query("UPDATE sessions SET `code`='$code', `start`='$date' WHERE(`id`='$id')") or die("Failed to update session: <br> <br> " . mysql_error());
} else {
//session doesn't exist so lets create one
mysql_query("INSERT INTO sessions (`id`,`code`,`start`) VALUES('$id','$code', '$date')") or die("Failed to create session: <br> <br> " . mysql_error());
}
Also my getUserId function:
function getUserId($username) {
$query = mysql_query("SELECT * FROM users WHERE(`username`='$username')");
$row = mysql_fetch_row($query);
return $row[0];
}
My question, if you didn't get it already. Is why is it that the 'id' is always being set to 0 even though the getUserId() function is returning the proper id of the user?
Any suggestions?
Just found the mistake on my part.
I have this line which call the setSession function.
//set session
setSession($username. $password);
It is supposed to be only parsing the username, but I forgot tot take $password out. So when it is looking for the username 'user1' for example it will actually be looking for 'user1password' and therefore returning the 0 due to no records existing with those details.

How can i prevent a logged in user to delete post by others users?

I have a problem, I can not prevent a logged in user to delete post by others users?
In my code now, I can delete all users posts, but I want to be able to only delete my posts (the logged
in user posts).
Can somebody help me in the right direction on how to do that?
<div class="deletebtn">Delete post</div>
$id=$_GET['id'];
$sql="DELETE FROM shouts WHERE id='$id'";
$result=mysql_query($sql);
if($result)
{
echo('<div class="deletedpost">You have deleted a post. Tillbaka till Bloggen</div>');
}
else
{
echo "Something went wrong";
}
mysql_close();
Im using a href in one file, linking to another file where a use Sql code.
you can do this via session
check if user is logged in or not. if logged in then delete the post
if(isset($_SESSION['user']))
{
//delete post
}
Store userId in your table and update your delete query like this...
$sql="DELETE FROM shouts WHERE id='$id' and userId = '$_SESSION[user]'";
Check whether the logged in user is the owner for the particular post before deleting.
Write a select query with post id and owner id. If it returns true allow him to delete the post otherwise do not allow.
Don't you have a $_SESSION['id'] of sorts?
And you do have that user id associated in shouts table, so you know who's shout is it right?
DELETE FROM shouts WHERE id='$id' AND user_id='$_SESSION['id']'
You should treatthe inputs though.
use this kind of query, here it will delete only logged in user's post.
$sql="DELETE FROM shouts WHERE id='$id' and user_id = '$loggedin_session_id'";
I would suggest that upon the user signing up, you assign them a unique id (or let the database do it with auto increment) and save it in the database. Then, whenever they log in, you can pull that user_id from the database and store it in a session variable. When shouts are created, you store the user_id of the person who created the shout alongside the shout itself in the shouts table of the database. When a user attempts to delete a shout, you first check to make sure that that shout belongs to them before allowing them to delete it.
An example:
<?php
//when user logs in
$email = 'example#example.com';
$password = 'default';
$sql = "SELECT id FROM user_table WHERE email = '$email' AND password = '$password'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$_SESSION['user_id'] = $row['id'] //'id' is the user's id; assign it to the session variable
//user creates the shout
$user_id = $_SESSION['user_id']; //get the user_id from the logged-in user
$shout = $_POST['shout'];
$sql = "INSERT INTO shout_table (user_id, shout) VALUES ('$user_id','$shout')"; //store user id alongside the shout for future queries
mysql_query($sql);
//user about to delete the shout
$id = $_GET['id'];
$user_id = $_SESSION['user_id'];
//the sql to check in the shout_table to see if the shout they are deleting belongs to them
$sql = "SELECT * FROM shout_table WHERE user_id = '$user_id' AND id = '$id'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
if ($row)
{
//everything is alright; this user can delete the shout, so prepare the DELETE query to do so
}
else
{
//the user is not allowed to delete the shout because it's not theirs; tell them so with an echo or whatever you're using for error handling
}
?>
The example above is rife with SQL injections. Validate and sanitize, of course. As well, mysql_query functions will be deprecated as of PHP 5.5, so get in the hang of using mysqli_query functions instead. Better yet, see if you can use PDO. :)

php update password or save default if it is blank

Can someone point me out how can I save the default password if it is blank?
Its an update issue. Im making an update page when the user update their profile.
Its a long profile info. I did not post it all here coz my only problem is the password field.
Even if it is leave as blank it still updating the field on the database.I use md5 for encryption. Below is the code. Please just add the code, your code. Thank you.
The id is=1 because im just testing it. Ill only have one data in the userstest table.
$desire= $_POST['desired'];//username field
$password = md5(trim(mysql_prep($_POST['password'])));//password field
$passconfirm = md5(trim(mysql_prep($_POST['confirmpassword']))); //confirmpasswor field
$sql = mysql_query("UPDATE userstest SET username = '$desire',password='$password',confirmpassword='$passconfirm' WHERE id=1");
if(mysql_affected_rows()==1){
echo "Update Successfull";
}else{
echo "Update Failed" . mysql_error();
}
Add a if condition while building query
$sql = "UPDATE userstest SET username = '$desire'";
if($password) {$sql += ",password='$password',confirmpassword='$passconfirm'";}
$sql += " WHERE id=1";
then run the query mysql_query($sql);
Don't update the password or confirmpassword columns if those fields are blank. Just don't add them to the SQL query in that case.
By the way, why are you even saving the confirmpassword? Shouldn't this always be the same as password? It's usually only used in an if statement in the PHP script to see that the user didn't do a typo.

Categories