php update password or save default if it is blank - php

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.

Related

How can I verify a form with an SQL databse?

So I have an SQL database that has a table for accounts and info, and another one for storing comments on articles. I Have a form for submitting comments and it works just fine, but I wanted to implement a feature to prevent spam and non registered accounts. I was trying to find a way to make the following code work so that it would call upon my account table and check to see if the username section matches what was entered in the form.
I want it to check through my username column on the table to see if what was entered in the box is actually in the database as well, that way if it hasn't been registered it won't submit.
My problem I keep running into is that I try this
<?
if ($_POST['Uname']==`username`){
$strSQL="INSERT INTO `comments`
(`name`,`comment`,`date`,`#`) VALUES
('".$_POST['Uname']."','".$_POST['Comment']."',
'".$_POST['Date']."','".$_POST['#']."')";
}
else{
echo "Username invalid";
}
}
?>
But when I do this it thinks that "username" is what the username needs to be in order to submit properly.
I do not want every username to need to be "username" in order for them to submit, I just want it to check through my username column to see if what was entered is one of the registered usernames in the SQL column.
Im not sure if this is possible, or if I am making any sense, but this is my first post on this site and I would appreciate any help I could get.
Full code is below
<?
if ($_POST['Enter']=='Enter'){
$con = mysql_connect
("sql***.*******.com","*****","*******");
$db_selected = mysql_select_db("*********",$con); //My login
$test2=$_GET['ID']; //Ignore
$_POST['#']=$test2; //Ignore
$sql="Select * from `Articles` and `Accounts`"; //For pulling data
mysql_query($strSQL,$con);
if ( ? == ? ){ //What should go here?
$strSQL="INSERT INTO `comments`
(`name`,`comment`,`date`,`#`) VALUES
('".$_POST['Uname']."','".$_POST['Comment']."',
'".$_POST['Date']."','".$_POST['#']."')";
}
else{
echo "Username invalid";
}
}
?>
Edit
So after making the changes needed, should my previous code end up like this?
<?
if ($_POST['Enter']=='Enter'){
$con = mysql_connect
("*******","********","*****");
$db_selected = mysql_select_db("*****",$con);
$test2=$_GET['ID'];
$_POST['#']=$test2;
$username = $_POST['Uname'];
$sql = "Select `id` from `Accounts` where `username` = $username";
mysqli_num_rows($sql,$result);
$row_cnt = mysqli_num_rows($result);
printf("Result set has %d rows.\n", $row_cnt);
echo $result;
if ($row_cnt!=''){
$strSQL="INSERT INTO `comments`
(`name`,`comment`,`date`,`#`) VALUES ('".$_POST['Uname']."',
'".$_POST['Comment']."',
'".$_POST['Date']."',
'".$_POST['#']."')";
}
else{
echo "Username invalid";
}
}
?>
Obviously what you doing is not correct, as of now you are putting condition as :
if ($_POST['Uname']==`username`)
which means you saying any user who's name is 'username' should be able to comment, but what you want to achieve is, any user who is valid user and is exist in db should be able to comment. So for that you should write a select sql to check the user, :
$username = $_POST['Uname'];
$sql = "select id from yourusertable where username = $username";
then,
perform
mysqli_num_rows
to check if you get anything greater than zero. If yes, then allow to submit comments.
Simply apply the check that only loggedIn user can comment. So if the user will not exist in users table it will not be loggedIn nor can comment.

How to give the users the ability to update their information

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

How to update database using `id`?

i want to update my database using id, I have already a database which have their name
Now when i update my database using WHERE college='1' it works successfully but when i update my database using id it's not working please help, and my database id=1 for which i'm working for..
here is my source code:
<?php
$con=mysqli_connect("localhost","root","Bhawanku","members");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM admin");
while($row = mysqli_fetch_array($result))
{
echo "(".$row['id'].") ".$row['first_name']." ".$row['last_name'];
}
mysqli_query($con,"UPDATE admin SET first_name='Rajendra', last_name='Arora'
WHERE id='$id'");
mysqli_close($con);
?>
EDITED
after putting $id it's showing an error undefined variable id.. what's that meaning?
$id is not set in your code, referencing it will generate a warning and run the following query:
UPDATE admin SET first_name='Rajendra', last_name='Arora' WHERE id=''
You need to set $id somewhere.
Also be aware of SQL injection depending on where this value is coming from, if it is from user input it needs to either be casted to an integer or escaped if it is a string.
If it is an integer you need not include quotes around it (WHERE id=1 as opposed to WHERE id='1').
First your ID should be set and second your ID is probably not a string (varchar, char or text) in the database. It would be and should be numeric. In that the case, don't wrap the id in ''. Only string data should be wrapped in ''.
id is a number, not a string. Change it to:
mysqli_query($con,"UPDATE admin SET first_name='Rajendra', last_name='Arora' WHERE id=".$row['id']);
EDIT
Your id is only used inside your loop. Try changing it from while to if
$result = mysqli_query($con,"SELECT * FROM admin limit 0, 1");
if ($row = mysqli_fetch_array($result)) {
mysqli_query($con,"UPDATE admin SET first_name='Rajendra', last_name='Arora' WHERE id=$row['id']");
}
Any other way, using while, will change all user names in the table.
If you have more that one row in this table you'll need another approach.
try something like this,Remove single quotes
// Assign ID here
$id= 1;
mysqli_query($con,"UPDATE admin SET first_name='Rajendra', last_name='Arora' WHERE id='$id'");
Define $id and then something like this should work:
if ($stmt = mysqli_prepare($conn, "UPDATE admin SET first_name='Rajendra', last_name='Arora' WHERE id=?")) {
mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
}
If $id comes from a $_GET or $_POST variable, be sure to never embed it in a query directly!

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

Updating SQL database value in PHP script

I have an IPN script that is doing some work on the amount of a payment received, and when a certain amount is received, it is updating their license code in the database after verifying it with PayPal's IPN service.
This SQL isn't right, it's not updating. The rest of my code is fine because it sends an email, but where's the SQL error at? It's really late and I'm spacing out...
if ($amt == "77.00")
{
mysql_query("UPDATE login_users SET license_code = 3 WHERE username = ". $username ."") or die(mysql_error());
// Change license code in database
}
You need quotes around the user name if it's a string.
WHERE username = '". $username ."'
Also make sure $username is properly sanitized:
$username = mysql_real_escape_string(... wherever the value is coming from ...);
Put SET before WHERE and add single quotes around username
"UPDATE login_users SET license_code = 3 WHERE username = '". $username ."'";

Categories