i created update code for updating password in a table using id.This is the url from where i am getting id using $_GET but its not working.
http://www.example.com/en/resetPaSS.php?id=1&token=779d2aa48de104db46d66e29de576aac
The code:
if(isset($_POST['sub']))
{
$pass_hash = PassHash::hash($_POST['pass']);
$sql = "UPDATE user SET password='$pass_hash' WHERE id='$_GET[id]'";
$resu = mysqli_query($link,$sql);
//echo $sql;
if(!$resu)
{
$error="Unable to change Password. Try Again!";
}
else
{
echo"changed";
}
}
I also echo $sql and it shows UPDATE user SET password='$2a$10$bed9ad8e6cb910e0f1f12uXJldZLQ79f5HVrIiIAIZeZ9088Rre9.' WHERE id=''
Also tried $_REQUEST but still not works.
EDIT:
I am using this url for reseting password to send to the user which is created using
http://www.example.com/en/resetPaSS.php?id=$id&token=$token
try this:
$sql = "UPDATE user SET password='$pass_hash' WHERE id='" . mysqli_real_escape_string($_GET['id']) . "'";
If you use a form, then the id is not in the action url. You can also post the id by using a hidden input field
You must use prepared statement to prevent sql injection:
$sql = "UPDATE user SET password='?' WHERE id=?";
$stmt = $link->prepare($sql);
/* bind parameters */
$stmt->bind_param("si", $pass_hash, $_GET['id']);
/* execute query */
$stmt->execute();
EDIT
By clicking the link you will be go to your page where a form is. You have to edit the the id to the form or action url to make your script working by doing the following steps
make a variabele named id like this:
$id = isset($_GET['id']) ? $_GET['id'] : $_POST['id'];
also add hidden field to the form:
<input type="hidden" name="id" value="<?php echo $id; ?>">
Change the query bind_param to:
$stmt->bind_param("si", $pass_hash, $id);
If you know, that id is number, do this:
$id = intval($_GET['id']);
$sql = "UPDATE user SET password='$pass_hash' WHERE id='$id';";
Related
I have a form tag on my site that leads to the PHP page with email and/or/without description. Based on that the code generates a query, the query needs to update these credidentials. That part of the code works and has been tested. The problem is that the database is not updating the e-mail credidential, but if i put it to update the description it does so. The code has 3 checks, if the user puts only his email, if he puts only his description or puts both. Based on that the code works like this :
<?php
session_start();
include_once 'connection.php';
$id = $_SESSION['user_id'];
if(isset($_POST['emailChange']) || isset($_POST['descChange'])){
$desc = $_POST['descChange'];
$email = $_POST['emailChange'];
if(empty($email)){
$query = "UPDATE users SET description = :descr WHERE user_id= :id ;";
$stmt = $conn->prepare($query);
$stmt->bindParam(":descr", $desc);
} else if(empty($desc)){
$query = "UPDATE users SET user_email= :email WHERE user_id= :id ;";
$stmt = $conn->prepare($query);
$stmt->bindParam(":email", $email);
} else{
$query = "UPDATE users SET description = :descr AND user_email = :email WHERE user_id= :id;";
$stmt = $conn->prepare($query);
$stmt->bindParam(":email", $email);
$stmt->bindParam(":descr", $desc);
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
header("Location: ../profile.php?error=invalidEmail");
exit();
}
$stmt->bindParam(":id", $id);
$stmt->execute();
}
The form itself looks like this :
<form action="assets/upload.php" method="POST">
<input type="text" name="emailChange" class="inputs" id="changeEmail" placeholder = "Enter your new E-mail">
<input type="text" name="descChange" class="inputs" id="changeDesc" placeholder="Enter your description">
<button type="submit" id="btnconfirmCreds" name="changeCreds">Confirm Changes</button>
</form>
The names in the database looks like this :
[user_id][user_username][user_email][user_password][role_id][user_image][description][num_of_posts]
You should set up PDO error logging.
From Comments; paraphrased for clarity:
My user_id column is int(11) auto_increment
Your problem is you are trying to insert a string value into a numerical column in MySQL.
user_id / id in database parlance is usually a numerical value, but you have not set the value type in your SQL, so it defaults to string.
Because your :id value is a numeric value in PHP you need to do this:
$stmt->bindParam(":id", $id, 'i'); // i = integer type.
It is highly recommended to explicitly set the value of the data type supplied each and every time .
If the data given to the PDO does not match the value-type given, then the PDO transaction will void and will not complete. This is a security measure.
For example:
$id = 3;
$stmt->bindParam(":id", $id);
This is the same as saying:
$stmt->bindParam(":id", 3, 's'); // default type value is 's' for string.
Obviously the value 3 is not a string so this transacion ($stmt) is never performed.
i assume it's because it views the description as a special word, if that is true then i should change the name in my database. Thoughts?
"description" is neither a Keyword or a reserved word in MySQL 5.5-->5.7 (in MySQL 8.0.4 DESCRIPTION is a keyword but is not a reserved word)
You can view a list of MySQL Keywords and Reserved words .
Some notes about the logic:
if(isset($_POST['emailChange']) || isset($_POST['descChange']))
{
$desc = $_POST['descChange'];
$email = $_POST['emailChange'];
...
First you check, if at lease one parameter exists, but then you access both. You can argue, that the form send always both, but never believe user input: Manipulating data is so easy!
Either change your if(...) to:
if( isset($_POST['emailChange']) && isset($_POST['descChange']) )
The following line is a shorter form with identical semantics:
if( isset( $_POST['emailChange'], $_POST['descChange'] ) )
The other ways is to change the 2 other lines, for example by:
$desc = isset($_POST['descChange']) ? $_POST['descChange'] : '';
$email = isset($_POST['emailChange']) ? $_POST['emailChange'] : '';
I have this small piece of code.
echo $token;
$selstmt=$conn->Prepare("SELECT UserID FROM USER WHERE Token LIKE ?");
$selstmt->bind_param('s', $token);
echo $token;
$selstmt->execute();
$selstmt->store_result();
$selstmt->bind_result($userid);
$selstmt->fetch();
echo $userid;
$selstmt->close();
If I remove the bind_param and directly insert the value in the prepare statement, the query works fine. I echo the value of token twice to check if the value is changed but the $token is same and the value is there. So why is this not working?
This may work for you, if you include the % signs
$sql = 'SELECT UserID FROM USER WHERE Token LIKE ?';
$stmt = $conn->prepare($sql);
$stmt->execute(array("%$token%"));
#$result = $stmt->fetch();
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!
I have the code below that lists all of the data from columns: Firstname & Surname, I also want it so that when they are clicked it takes you to a "profile" page where you can see the rest of their data. I have made a link directly to the profile.php page and before it I set it so that $_POST = id, I'm hoping to have it so that the $_POST['id'] will be changed to the users when they click on the link.
<?PHP
$result = mysql_query("SELECT id, firstname, surname FROM members WHERE createdby = '" . $_SESSION['myusername'] ."'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
while($row = mysql_fetch_row($result))
{
$id=$row[0];
$_POST['id'] = $id;
echo ("<a href=profile.php>".$row[1]." ".$row[2]."</a></br>");
}
?>
It loads the page up fine and all works just it's not setting $_POST to $id.
EDIT: I'm now using $_GET["id"] which works, but it only echoes out that value I can't use it in a query:
$id=$_GET["id"];
$sql="SELECT * FROM $tbl_name WHERE id='$id'";
$result=mysql_query($sql);
Setting a value for $_POST["id"] will work on that very page but it does not mean that when you redirect to another page after that then your $_POST value will be automatically sent to that page. Rather you can try $_GET for this purpose. You can modify your link to be like
profile.php?id=$id
and on your profile.php page you can use $_GET["id"] rather than $_POST
Use session in place of post -- $_SESSION['id']
Trying to follow a tutorial, but i get a database error on line six of the executable php file (second code below)
<?php
mysql_connect("localhost","root","") or die("Error: ".mysql_error()); //add your DB username and password
mysql_select_db("beyondmotors");//add your dbname
$sql = "select * from `TestTable` where ID = 1";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)){
$id = $row['ID'];
$fname = $row['FName'];
$lname = $row['LName'];
$phone = $row['PHON'];
//we will echo these into the proper fields
}
mysql_free_result($query);
?>
<html>
<head>
<title>Edit User Info</title>
</head>
<body>
<form action="updateinfo.php" method="post">
userid:<br/>
<input type="text" value="<?php echo $id;?>" name="id" disabled/>
<br/>
Last Name:<br/>
<input type="text" value="<?php echo $fname;?>" name="fname"/>
<br/>
Last Name:<br/>
<input type="text" value="<?php echo $lname;?>" name="lname"/>
<br/>
Phone Number:<br/>
<input type="text" value="<?php echo $phone;?>" name="phon"/>
</br>
<input type="submit" value="submit changes"/>
</form>
</body>
</html>
and here is the executable
<?php
mysql_connect("localhost","root","") or die("Error: ".mysql_error()); //add your DB username and password
mysql_se lect_db("beyondmotors");//add your dbname
//get the variables we transmitted from the form
$id = $_POST[''];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$phon = $_POST['phon'];
//replace TestTable with the name of your table
$sql = "UPDATE `TestTable` SET `FName` = '$fname',`LName` = '$lname',
`PHON` = '$phon' WHERE `TestTable`.`ID` = '$id' LIMIT 1";
mysql_query($sql) or die ("Error: ".mysql_error());
echo "Database updated. <a href='editinfo.php'>Return to edit info</a>";
?>
everything is good until i hit submit changes; than i get error on line 6. I'm new to database so please be specific if possible. Thank you! also if anyone could point me to a similar, "working" tutorial that would help ALOT!
trying to follow this tutorial: http://teamtutorials.com/web-development-tutorials/editing-mysql-data-using-php
i'm using wamp server, so the database log in is correct. I mean it displays the data, just doesn't edit it..
The error i'm getting is :
Notice: Undefined index: ID in C:\wamp\www\test\updateinfo.php on line 6
i get that even if i change post to $id = $_POST['ID'];
Ok I changed the $_POST['']; to $_POST['id']; , still had the same error.
Than I read online to add a # to the front so now it looks like this: #$_POST['id'];
That too off all the errors. but not my data base is not been updated. Everything goes through with no errors but no data is been changed??
Also when i tried to remove backticks I get this error:
Parse error: syntax error, unexpected T_STRING in C:\wamp\www\test\updateinfo.php on line 12
So i left them the way they were...
Could it be because i'm using a local server? This should be all simple not sure what i'm doing wrong here.. I mean i literary copied everything over from the tutorial.
First and foremost, you should be warned that your code is completely vulnerable against sql injections. Escaping your POST data before inserting it into the database is a good start in protecting your database.
Also, learning the mysql extension is useless for new systems because it is deprecated. You might think about looking into the PDO interface or the mysqli extension. There are many beginner tutorials for both and you will gain much more.
Now, as for your error
Make sure you are defining which ID you want to update in your database. In your second block of code you have:
//get the variables we transmitted from the form
$id = $_POST[''];
needs to change to:
$id = $_POST['id'];
You said you get the error even if you change post to $id = $_POST['ID'], but if you look at your form, the id input has name = 'id' and PHP is case sensitive.
Now, in your sql query, all of those back ticks are unnecessary. Also, there is no point in specifying which table ID because this is all being done in ONE table, TestTable.
//replace TestTable with the name of your table
$sql = "UPDATE TestTable SET FName = '$fname',LName = '$lname',
PHON = '$phon' WHERE ID = '$id' LIMIT 1";
EDIT:
Although the query above is syntactically correct, you should consider using mysqli or PDO due to reasons mentioned above. Below are examples using mysqli and PDO.
Mysqli
mysqli Manual
/* connect to the database */
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
/* build prepared statement */
$stmt = $mysqli->prepare("UPDATE TestTable SET FName=?, LName=?, PHON=? WHERE ID=?)");
/* bind your parameters */
$stmt->bind_param('sssi', $fname, $lname, $phon, $id);
/* execute prepared statement */
$stmt->execute();
/* close connection */
$stmt->close();
PDO
PDO Manual
/* connect to the database */
$dbh = new PDO('mysql:host=localhost;dbname=database', $user, $pass);
/* build prepared statement */
$stmt = $dbh->prepare("UPDATE TestTable SET FName = :fname, LName = :lname, PHON = :phon WHERE ID = :id");
/* bind your parameters */
$stmt->bindParam(':fname', $fname);
$stmt->bindParam(':lname', $lname);
$stmt->bindParam(':phon', $phon);
$stmt->bindParam(':id', $id);
/* update one row */
$fname = 'John'; # or use your $_POST data
$lname = 'Doe';
$phon = '123-456-7890';
$id = 1;
/* execute prepared statement */
$stmt->execute();
/* use it again!1! */
$fname = 'Jane';
$lname = 'Doe';
$phon = '123-456-7890';
$id = 2;
/* execute prepared statement */
$stmt->execute();
/* close connection */
$dbh = null;
Remove backticks:
UPDATE TestTable SET FName = '$fname',LName = '$lname',PHON ='$phon'
WHERE TestTable.ID = '$id' LIMIT 1";