im fairly new to PHP/MySQL but i found no answers in the net for my problem:
I've got a form with 4 textfields
<form method="post" action="updateuserdatatest.php">
<input type="text" value="Hans" name="username">
<input type="text" value="1234" name="password">
<input type="text" value="desired cell" name="desiredcell">
<input type="text" value="desired value" name="desiredvalue">
<input type="submit">
</form>
I want to update the named "desired cell" with the "desired value".
So i have to type in the username, his password, a column name (i.e. "streetname","postcode" or "city") and after that the stringvalue which shall be submitted to the database.
I use this code:
$pdo = new PDO(everything is OK here! - Checked this out many times);
$sql = 'UPDATE user SET :desiredcell = :desiredvalue WHERE username = :username AND password = :password';
$stmt = $pdo->prepare($sql);
$stmt->bindValue(":desiredcell", $_POST['desiredcell'], PDO::PARAM_STR);
$stmt->bindValue(":desiredvalue", $_POST['desiredvalue'], PDO::PARAM_STR);
$stmt->bindValue(":username", $_POST['username'], PDO::PARAM_STR);
$stmt->bindValue(":password", $_POST['password'], PDO::PARAM_STR);
$stmt->execute();
if ($stmt->errno) { echo "FAILURE!!! " . $stmt->error;
}
else echo "Updated {$stmt->affected_rows} rows";
$response = array();
$response['success'] = true;
echo json_encode($response);
?>
This does not work!
But when i change the sql query to a specific columnname like 'UPDATE user SET streetname = :desiredvalue WHERE username = :username AND password = :password';
then it works! why?
i want to type in the cellname which has to be updated manually!
i tried this with mysqli queries before like UPDATE user SET ?=? WHERE password=? AND username=? same problem there
What am i doing wrong?
Thanks in advance.
EDIT:
seems that i cant post images in a comment, so i make another answer:
this is my dummy table,
when i try to insert the column variable like your example nothing happens inside the table, but i still get the success response.
$column = in_array($_POST['desiredcell'], ['streetname', 'postcode','state']) ? $_POST['desiredcell'] : 'streetname';
$sql = 'UPDATE user SET $column = :desiredvalue WHERE username = :username AND password = :password';
$stmt = $pdo->prepare($sql);
$stmt->bindValue(":desiredvalue", $_POST['desiredvalue'], PDO::PARAM_STR);
$stmt->bindValue(":username", $_POST['username'], PDO::PARAM_STR);
$stmt->bindValue(":password", $_POST['password'], PDO::PARAM_STR);
$stmt->execute();
any tips? =/
EDIT:
Found the solution:
$sql = 'UPDATE user SET '.$column.' = :desiredvalue WHERE username = :username AND password = :password';
thank you guys.
As it mentioned it the comments, you can't bind column names. You should use a variable and make sure the input is a real column name (for security reasons)
Example:
<?php
$column = in_array($_POST['desiredcell'], ["column1", "column2"]) ? $_POST['desiredcell'] : "column1";
$sql = "UPDATE user SET $column = :desiredvalue WHERE username = :username AND password = :password'";
Also bear in mind that storing a plain text passwords in a database is a real bad idea. Check password_hash function.
Related
so i have a table of data in web ui
as soon as I click the button. all of the field data in "Status Email" changed. not just selected field that i meant.
this is the sintaks sql
if($mail->Send())
{
$query = "UPDATE nearly_inactive SET EmailSent = 'Sudah Kirim Email' WHERE EmailSent = 'Belum Kirim Email'";
$update = $con->prepare($query);
$update->execute();
}
how can i get the "update" only the data that I click on the button??
Get specific field
In order to get the specific field from a MYSQL database
Select column FROM databse WHERE x = y
Example:
SELECT id, firstname, lastname FROM MyGuests WHERE lastname='Doe'
The issue
It's best to get a unique identifier, which no other user has used. For example a 10 digit user id code. Check that this code doesn't exist, for it to be unique.
UPDATE:
Easily use the UNIQUE SQL tag to resolve this issue.
CREATE TABLE X (
ID INT UNIQUE
)
Example:
SELECT id, firstname, lastname FROM MyGuests WHERE id=ryan9273__2
Update a specific field
Now that we have fixed the issue we can easily
UPDATE x SET y=z WHERE id=b
Lets fix your code:
UPDATE nearly_inactive SET EmailSent = 'Sudah Kirim Email' WHERE EmailSent = 'Belum Kirim Email'
Lets make it more dynamic
UPDATE nearly_inactive SET :email = :emailaddr WHERE EmailSent = :id
final code:
$query = $con->prepare("UPDATE nearly_inactive SET :email = :emailaddr WHERE EmailSent = :id");
$query->bindParam(':email', $email, PDO::PARAM_STR);
$query->bindParam(':emailaddr', $emailaddr, PDO::PARAM_STR);
$query->bindParam(':id', $id, PDO::PARAM_STR);
$update->execute();
Security Matters
You are using PDO, so use bindParam aswell. Secret code enthusiast answer isn't as secure as the current code i provided!
Practice Makes Perfect
Please don't copy my code right away. learn from it and code it again ! Make it better. Also check the official PHP documentation for more info on these topics
Stay safe !
Regards,
Ryan
you need to determine which record need to be changed based on their unique ID. usually it's the primary key of the table. so, If your primary key is enroller_id, then pass the value of enroller_id, and put it inside your sql.
if($mail->Send())
{
//prepare your query
$statement = $this->mysqli->prepare("UPDATE nearly_inactive SET EmailSent = 'Sudah Kirim Email' WHERE enroller_id = ?");
//check for statement preparation
if ($statement === false) {
trigger_error($this->mysqli->error, E_USER_ERROR);
return;
}
//bind the value
$statement->bindParam("i", $id);
//get id for the query
$id = your_field_enroller_id;
//execute the statement
$statement->execute();
}
where enroller_id is your table primary key, and $id is the value of that field primary key.
<?php
$servername="localhost";
$username="root";
$password="";
$dbname="demon";
//CREATE CONNECTION
$conn=new mysqli($servername,$username,$password,$dbname);
//CHECK CONNECTION
if ($conn->connect_error)
{
die("connection failed:".$conn->connect_error);
}
$sql="UPDATE student set NAME='JohnRambo' where STUDENT_ID=1000";
$result=$conn->query($sql);
if ($result===TRUE)
{
echo"NEW RECORD CREATED SUCCESSFULLY";
}
else
{
echo "ERROR:".$sql."<br>".$conn->error;
}
$conn->close();
?>
I have successfully created registration form with hashed password as shown below. I am not able to log In using the username and hashed password that I have stored in my SQLite db.
I can log in if the password is store as plain text, but I want the password to be hashed. Please help me how can I read the hash password which matches the username to login. I am new to php and this is the first time I am working with SQLite db as well as php. Please help me, I have been trying to do this for past few days now :(
Any help or guidance would be great.
(I have noticed there is not much with php and sqlite that I could find online and the similar questions I have seen on stack flow is related to mysql mostly. Also, I apologize if I am posting it right or if it is too easy of an answer because I am beginner and new to this. Thank you)
Here is how I am storing the password in hash in my registration.php which is working:
if(ISSET($_POST['register'])) {
//setting the variables
$user_id = $_POST['user_id'];
**//hashing the password
$password = PASSWORD_HASH($_POST['password'], PASSWORD_DEFAULT);**
$email = $_POST['email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
//Inserting
$query = "INSERT INTO myTable (user_id, password, email, first_name, last_name) VALUES(:user_id, :password, :email, :first_name, :last_name)";
$stmt = $db->prepare($query);
$stmt->bindParam(':user_id', $user_id);
$stmt->bindParam(':password', $password);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':first_name', $first_name);
$stmt->bindParam(':last_name', $last_name);
//check to see if the exec of the query is success
if($stmt->execute()){
$_SESSION['success'] = "Account is created successfully";
//redirect to login
header("location:index.html");
}
}
Here is my login.php
$user_id = $_POST['user_id'];
$password = ($_POST['password']);
$query = "SELECT count(*) as count FROM myTable WHERE user_id=:user_id AND password=:password";
$stmt = $db->prepare($query);
$stmt->bindParam(':user_id', $user_id);
$stmt->bindParam(':password', $password);
// this is to execute
$result = $stmt->execute();
//this fetching from the db the user name and password. Where SQLite3_NUM returns an array by column number starting at 0 being the first
$row = $result->fetchArray(SQLITE3_NUM);
/*$stmt = $pdo->prepare("SELECT * FROM lit_login_credentials WHERE user_id = ?");
$stmt->execute([$_POST['user_id']]);
$stmt = $stmt->fetch();*/
//This is checking if the input login and user in the db is only entered once then it will go though else if not found then it will stay on the same page.
if($row[0] == 1 /*&& $user_id && password_verify($_POST['password'], $user_id['password'])*/){
//$out = "Success";
header('location: admin.php');
} else {
//$out = "invalid username or password";
//echo "<div class='alert alert-danger'>Invalid username or password</div>";
$_SESSION['error'] = "Invalid username or password";
header('location: index.php');
}
You need to use password_verify to compare the db password to the entered password.
Program should SELECT password from myTable WHERE user matches the entered user code. If any rows are returned (i.e. user is found), use password_verify to compare what is returned from the db and what is entered by the user. (Similar to the commented bit later in the code).
So how do I get single values in each seperate $stmt->bindColumn(3, $username);? What I am trying to do is set values in text fields in a form: name, username, and so on.
I pull the sandbox data from a table with:
SELECT * FROM users WHERE namn = 'sven' AND lösenord = ' ' ORDER BY datetime LIMIT 1
try {
$sql = "SELECT namn FROM user_view";
$stmt = $dbh->getInstance()->prepare($sql);
$stmt->execute();
$results=$stmt->fetchAll();
$stmt->bindColumn(1, $email);
$stmt->bindColumn(2, $name);
$stmt->bindColumn(3, $username);
$stmt->bindColumn(4, $password);
}
catch(PDOException $e) {
echo ($e->getMessage());
}
<input id="text" name="text" value="<?php echo $username ?>" type="text" class="form-control">
Assuming that your table structure is something like...
user_view
> id
> name
> email
> username
> password
And that you want to loop though all users (as you don't have a WHERE clause)...
$pdo = $dbh->getInstance(); // Get PDO instance
$sql = "
SELECT *
FROM user_view
WHERE name = ?
";
$query = $pdo->prepare($sql); // Prepare query
$query->execute([$_POST["name"]]); // Execute query and bind value to place holder (I've assumed it's coming from POST user input)
// Loop through result set
$user = $stmt->fetchObject();
// Access the columns like
# echo $user->name;
# echo $user->email;
# echo $user->username;
# echo $user->password;
// For example
echo "<input id='user_name' name='user_name' value='{$user->name}' type='text' class='form-control'>";
N.B.
You shouldn't be storing passwords in plain text - it's a major security risk.
You can use the following to hash a password on registration...
$password = password_hash($_POST["password"], PASSWORD_DEFAULT);
And to verify...
if( password_verify($_POST["password"], $db_password) ){
// Success, do something...
}
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'] : '';
Im creating a webpage for a game server that only had a registration page. All the users has registred and for some dum reason, it saved the password as username:password, so if the username is Meko and password is 1234, the actually password is "Meko:1234" Im now trying to make a login but im not sure how I should check that password. I have this sql query and tried to add $user_username: in front, but it didnt seem to work:
$query = "SELECT * FROM account
WHERE username = '$user_username'
AND sha_pass_hash = '$user_password'";
It needs to be $user_username:$user_password
I hope you can help me :)
If what you have stored in the database is an SHA1 checksum, then that's what you will need to compare.
The details are pretty sketchy.
Assuming that the row was saved into the database as
INSERT INTO `account` (`username`, `sha_pass_hash`, ...
VALUES ('Meko', SHA1('Meko:1234'), ...
Then to check for the existence of that row, given:
$user_username = 'Meko' ;
$user_password = '1234' ;
if those are the values you want to pass into the database query, then
$sql = 'SELECT ...
FROM account a
WHERE a.username = ?
AND a.sha_pass_hash = SHA1( CONCAT( ? ,':', ? )';
$sth = $dbh->prepare($sql);
$sth->bindValue(1,$user_username, PDO::PARAM_STR);
$sth->bindValue(2,$user_username, PDO::PARAM_STR);
$sth->bindValue(3,$user_password, PDO::PARAM_STR);
$sth->execute();
if( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
// matching row found
} else {
// no matching row found
}
$sth->closeCursor();
If you didn't use the MySQL SHA1 function and used some other function to calculcate the hash, then use that same function when you do the check.
That is, if the row was inserted by a statement of a form more like
INSERT INTO account (username, sha_pass_hash, ... )
VALUES ('Meko','7c4d046a92c441c426ce86f15fa9ecd1fc1fd5f1', ... )
Then to check for the existence of that row, given:
$user_username = 'Meko' ;
$user_password = '1234' ;
Then your query to check for the existence of the row would be something like this:
$sql = 'SELECT ...
FROM account a
WHERE a.username = ?
AND a.sha_pass_hash = ?';
calculate the password hash, the same way as when it was originally done
$user_sha_hash = sha1( $user_username . ':' . $user_password) ;
And prepare and execute the query, passing in the SHA checksum string
$sth = $dbh->prepare($sql);
$sth->bindValue(1, $user_username, PDO::PARAM_STR);
$sth->bindValue(2, $user_sha_hash, PDO::PARAM_STR);
$sth->execute();
if( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
//
} else {
//
)
$sth->closeCursor();
I think you on php ?
$username = 'Meko';
$user_password = '1234';
$altered_pass = $user_username.':'.$user_password;
if($stmt = mysqli_prepare($con,"select * from account where username = ? and sha_pass_hash = ?") ){
mysqli_stmt_bind_param($stmt,'ss',$user_username,sha1($altered_pass));
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt)){
//"yup";
}
else{
//"nope";
}
mysqli_stmt_close($stmt);
}
mysqli_close($con);
You do not specify explicitly but assuming that your sha_pass_hash contains a hashed value of the following format: hash(username:password) then hash '$user_username' + ":" + '$user_password' first and then compare it to your password.
$search = $username.":".$password;
$query = "SELECT * FROM account WHERE password = ".$search;
IMPORTANT:
I very much hope you are preparing your statements and binding your parameters to prevent SQL injection attacks. If you are not, let me know and I can help you out in more detail so that your database is secure.
Also, I recommend that you create another table and fill it in with the values inside this account table. The previous answer is a quick fix so that your users can login meanwhile, but by no means should the previous table stay as it is.
Let me know if you need any more help :)