I am having trouble using this prepare and bind. I have tried the same thing with less variables to bind. I have been successful using prepare with just Fname, Lname, Password, $UserID and using sssi with the bind_param object. Can someone explain what I am doing wrong when using more variables in my bind code? With the code below it only prints out the same data from mysqli and doesn't update it.
if ($stmt = $con->prepare("UPDATE users SET Fname = ?, Lname = ?, Password = ?, UserLevel = ?, Email = ?, WHERE UserID= ?"))
{
$stmt->bind_param("ssssssi", $firstname, $lastname, $PW, $UserLevel, $EM, $UserID);
$stmt->execute();
$stmt->close();
}
// show an error message if the query has an error
else
{
echo "ERROR: could not prepare SQL statement.";
}
// redirect the user once the form is updated
header("Location: admin.php");
Although you haven't specified the data types which makes this tricky, I'll hazard a guess.
Fname = s
Lname = s
Password = s
UserLevel = i (?)
Email = s
I count 4 s' there, yet you have 6.
Try this,
$stmt->bind_param("sssisi", $firstname, $lastname, $PW, $UserLevel, $EM, $UserID);
Edit 1
As #Fred-ii- said, your SQL query is wrong.
Change
"UPDATE users SET Fname = ?, Lname = ?, Password = ?, UserLevel = ?, Email = ?, WHERE UserID= ?"
to,
"UPDATE users SET Fname = ?, Lname = ?, Password = ?, UserLevel = ?, Email = ? WHERE UserID= ?"
You had a training ,.
Related
In my last question people said that I need to use prepared statements to avoid SQL injection.
I'm changing the previous SQL's now to prepared statements, as y'all wanted.
The thing is, it submits the settings, this part:
$stmt_setsettings = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt_setsettings, $usersettings_sql)) {
array_push($errors, "Safe SQL failed, could not insert settings. Contact the helpdesk.");
} else {
mysqli_stmt_bind_param($stmt_setsettings, "sssss", $email_show, $fname_show, $lname_show, $private_account, $profile_style);
mysqli_stmt_execute($stmt_setsettings);
}
But it submits none of the actual info I need (like the username, firstname, ...)
Also, at the end of the code below it should redirect to the new profile, normally if this feels it should display "Something went wrong, refer to the helpcenter. (SE100)" but it like refreshes the sign up page and throws no error, while there is an error: the not submitting info!
I tried searching up similar questions or fixes but nothing useful found.
Can you check out the following code and let me know what is the deal with the not submitting values? Thanks!
// Finally, register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1); // Encrypt the password before saving in the database
$user_ip = $_SERVER['REMOTE_ADDR']; // Getting the IP of the user
$bio = $config['default-bio']; // Setting default biography
$profileimg = $config['default-profileimg']; // Setting default profile image
$timestamp = date('d.m.Y'); // Defining the current date
$activity = "on"; // Defining which state the user profile is in, online
$userdata_sql = "INSERT INTO users (username, bio, activity, profileimg, regdate, email, password, firstname, lastname, gender, birthday, country, ip)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$usersettings_sql = "INSERT INTO usersettings (show_email, show_fname, show_lname, private_acc, profile_style)
VALUES (?, ?, ?, ?, ?)";
$stmt_signup = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt_signup, $userdata_sql)) {
array_push($errors, "Safe SQL failed, could not sign up. Contact the helpdesk.");
} else {
mysqli_stmt_bind_param($stmt_signup, "sssssssssssss", $username, $bio, $activity, $profileimg, $regdate, $email, $password, $fname, $lname, $sex, $bday, $country, $user_ip);
mysqli_stmt_execute($stmt_signup);
}
$stmt_setsettings = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt_setsettings, $usersettings_sql)) {
array_push($errors, "Safe SQL failed, could not insert settings. Contact the helpdesk.");
} else {
mysqli_stmt_bind_param($stmt_setsettings, "sssss", $email_show, $fname_show, $lname_show, $private_account, $profile_style);
mysqli_stmt_execute($stmt_setsettings);
}
session_regenerate_id();
$_SESSION['username'] = $username;
$_SESSION['loggedin'] = true;
// Generate user id
$generateid_sql = "SELECT id FROM users WHERE username=? ORDER BY id";
$stmt_generateid = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt_generateid, $generateid_sql)) {
array_push($errors, "Safe SQL failed, could not generate a new ID. Contact the helpdesk.");
} else {
mysqli_stmt_bind_param($stmt_generateid, "s", $username);
mysqli_stmt_execute($stmt_generateid);
$generateid_result = mysqli_stmt_get_result($stmt_generateid);
}
while ($id = mysqli_fetch_assoc($generateid_result)) {
if ($id['username'] <= 0) { // Checking if the user id is a valid id (not below or equal to 0), and if not, displaying a critical error
array_push($errors, "Something went wrong whilst signing up, please refer to the helpcenter. (SE100)");
}
if ($id['username'] > 0) { // Redirecting the user to his or her profile if it is a valid id
header('location: /content/users/profile?id=' . $id['username'] . '');
}
}
}
}
First off, PLEASE don't ever store passwords like this:
$password = md5($password_1); // <-- Totally insecure
Instead use the built-in password_hash() and password_verify() functions. See https://www.php.net/manual/en/faq.passwords.php for a good overview of why md5() is not secure and examples how to handle password storage correctly.
Also, I'd recommend pulling the user out of the database and validating the password, BEFORE setting $_SESSION['loggedin'] = true.
Regarding your question, I'd recommend adding some additional error handling and result checking around your calls to $conn->prepare() and $stmt->bind_param. See mysqli_stmt_execute() does not execute the prepared query for examples of how to check $stmt->errors.
Another general recommendation is checking $stmt->affected_rows to see if your insert statements are actually being executed as you expect. Your inserts should each be affecting 1 row.
Lastly, turning on the MySQL query log can be a great troubleshooting tool: How to show the last queries executed on MySQL? . Are all the SQL queries in your code showing up in the log? Try running the queries manually and see if the results look right.
// Finally, register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1); // Encrypt the password before saving in the database
$user_ip = $_SERVER['REMOTE_ADDR']; // Getting the IP of the user
$bio = $config['default-bio']; // Setting default biography
$profileimg = $config['default-profileimg']; // Setting default profile image
$timestamp = date('d.m.Y'); // Defining the current date
$activity = "on"; // Defening wich state the user profile is in, online
$userdata_sql = "INSERT INTO users (`username`, `bio`, `activity`, `profileimg`, `regdate`, `email`, `password`, `firstname`, `lastname`, `gender`, `birthday`, `country`, `ip`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$usersettings_sql = "INSERT INTO usersettings (`show_email`, `show_fname`, `show_lname`, `private_acc`, `profile_style`)
VALUES (?, ?, ?, ?, ?)";
$stmt_signup = $conn->prepare($userdata_sql);
$stmt_signup->bind_param("sssssssssssss", $username, $bio, $activity, $profileimg, $timestamp, $email, $password, $fname, $lname, $sex, $bday, $country, $user_ip);
if(!$stmt_signup->execute()){
array_push($errors,mysqli_error($conn));
}
$stmt_setsettings=$conn->prepare($usersettings_sql);
$stmt_setsettings->bind_param("sssss", $email_show, $fname_show, $lname_show, $private_account, $profile_style);
if(!$stmt_setsettings->execute()){
array_push($errors,mysqli_error($conn));
}
session_regenerate_id();
$_SESSION['username'] = $username;
$_SESSION['loggedin'] = true;
// Generate user id
$generateid_sql = "SELECT `id`,`username` FROM `users` WHERE `username`=? ORDER BY `id` limit 1";
$stmt_generateid=$conn->prepare($generateid_sql);
$stmt->generateid->bind_param("s", $username);
if(!$stmt_generateid->execute()){
array_push($errors,mysqli_error($conn));
}else{
$generateid_result = $stmt_generateid->get_result();
}
$username_assoc = mysqli_fetch_assoc($generateid_result);
if ($username_assoc['id'] > 0) {
// Redirecting the user to his or her profile if it is a valid id
header('location: /content/users/profile?id=' . $username_assoc['username'] . '');
}else{
array_push($errors, "Something went wrong whilst signing up, please refer to the helpcenter. (SE100)");
}
}
I've run into some trouble trying to figure out how to update two mysql tables using prepared statements. The first table is updated with the new data but not the second. Can anyone tell me what I've got wrong? Thanks.
/Update Databases
$stmt = $db_conx->prepare('UPDATE tbl_users SET user_name=?, role=?, user_email= ?, company = ?, bio = ?, website = ? WHERE user_id=?');
$stmt->bind_param('sssssss',$user_name,$role,$user_email,$company,$bio,$website,$phone_no, $user_id);
$stmt->execute();
//Update second table
$stmt = $db_conx->prepare('UPDATE useroptions SET user_name=? WHERE user_id=?');
$stmt->bind_param('ss',$user_name,$user_id);
$stmt->execute();
//
if($stmt){
echo
'success";
}
else{ echo "An error occurred!"; }
You have a wrong number of argument in first query 7 ? 7 s but 8 $var ($phone_no )
//Update Databases
$stmt = $db_conx->prepare('UPDATE tbl_users SET user_name=?, role=?, user_email= ?, company = ?, bio = ?, website = ? WHERE user_id=?');
$stmt->bind_param('sssssss',$user_name,$role,$user_email,$company,$bio,$website,$phone_no, $user_id);
^^^^^^
$stmt->execute();
//Update second table
$stmt = $db_conx->prepare('UPDATE useroptions SET user_name=? WHERE user_id=?');
$stmt->bind_param('ss',$user_name,$user_id);
$stmt->execute();
//
Okay I have one question. I need to check if the user already exists but the question is now what I need to type in the if() I can't fetch because I have closed but if I didn't close i got an error because there can't run 2 statements. So I think if there are someone who can help me? I have the rest code but I only give the code here.
Here is my code:
$result = $mysqli->prepare("SELECT username FROM user WHERE username=?");
$result->bind_param("s", $username);
$result->execute();
$result->bind_result($username);
$result->close();
if (){
$register = $mysqli->prepare("INSERT INTO user
(username, password, email, rr, rank)
VALUES (?, ?, ?, ?, ?)");
$register->bind_param("sssii", $username, $kode, $email, $rr, $rank);
$register->execute();
$register->close();
} else {
echo "User already exists!";
}
UPDATED: more logical statement
$result = $mysqli->prepare("SELECT username FROM user WHERE username=?");
$result->bind_param("s", $username);
$result->execute();
$found = $result->fetch();
$result->close();
if ($found){
echo "User already exists!";
} else {
$register = $mysqli->prepare("INSERT INTO user
(username, password, email, rr, rank)
VALUES (?, ?, ?, ?, ?)");
$register->bind_param("sssii", $username, $kode, $email, $rr, $rank);
$register->execute();
$register->close();
}
Hello I have a question when I use my $stmt to execute an insert query into my database it works perfectly fine, however when I use a $stmt2 after that execute to UPDATE a different table it won't update the table even though to my understanding the code is correct.
The code I have tried to fix many times is as so
$mysqli= my database connection
$stmt = $mysqli->prepare("INSERT INTO `test_table`(datenow,test1,test2,test3,test4,test5,test6,test7,test8,
test9,test10,test11,test12,test14,test15,test16,test17,test18,)
VALUES (CURRENT_TIMESTAMP, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
$stmt->bind_param('ssssssssssssssssss',$test1,$test2,$test3,$test4,$test5,$test6,$test7,$test8,$test9,$test10,$test11,$test12,$test13,$test14, $test15,$test16,$test17,$test18);
$stmt1 = $mysqli->prepare("UPDATE `users` SET productID='1', purchase_date=CURRENT_TIMESTAMP, end_date=DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL 30 DAY) WHERE username = ?");
$stmt1->bind_param('s', $username);
$stmt1->execute();
$stmt->execute();
Any help would be very appreciated thanks!
A prepared statement can only execute one MySQL query. You can prepare as many statements as you want in different variables
so you can change it as:
$stmt1 = $link->prepare("UPDATE `users` SET productID='1', purchase_date=CURRENT_TIMESTAMP, end_date=DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL 30 DAY) WHERE username = ?");
$stmt1->bind_param('s', $username);
to
$stmt1 = $mysqli->prepare("UPDATE `users` SET productID='1', purchase_date=CURRENT_TIMESTAMP, end_date=DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL 30 DAY) WHERE username = ?");
$stmt1->bind_param('s', $username);
see no need of $link, you can prepare many statement for different variable...Thanks
I have a prepared statement to update several fields. I get the data from a formular, but not all fields are required. So it's possible that some fields are not set. I set them default to NULL. Now I don't want to overwrite the old value by NULL. How can I tell MySql not to Update the value if it's NULL?
$insert_stmt = $mysqli->prepare("
UPDATE members SET username=?, email=?, $password=?, $random_salt=?, level=?, customerID=?, name=?, surname=?, phone=?, quantities=? WHERE id=?
");
$insert_stmt->bind_param('ssssissss', $username, $email, $password, $random_salt, $level, $customerID, $firstname, $surname, $phone);
$insert_stmt->execute();
In my case it's the password and random_salt value that could be NULL. It will be very bad to overwrite the password just by NULL ;)
You could change your query as follows:
UPDATE members SET
username = IFNULL(?, username),
email = IFNULL(?, email) -- and so on for all fields
WHERE...
It could also be more efficient to check the value of your parameters first, and build the query dynamically, including only fields for which you have a non-null value to update with.
You could try this:
$insert_stmt = $mysqli->prepare("UPDATE members SET username=?, email=?, password=IF(LENGTH('?')=0, password, '?'), random_salt=IF(LENGTH('?')=0, random_salt, '?'), level=?, customerID=?, name=?, surname=?, phone=?, quantities=? WHERE id=?");
the If condition translates to:
IF( < YOUR_CONDITION >, < VALUE_IF_TRUE >, < VALUE_IF_FALSE >).
Assuming id is PK you can use :
INSERT INTO members (
id,
username,
email,
password,
random_salt,
level,
customerID,
name,
surname,
phone,
quantities
) VALUES (
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?
) ON DUPLICATE KEY UPDATE
username = IF(username <> '',VALUES(username),username),
email = IF(email <> '',VALUES(email),email),
password = IF(password <> '',VALUES(password),password)
...
Read your query fields and data carefuly. Set of fields and set of data in bind are not match.
UPDATE members SET username=?, email=?, $password=?, $random_salt=?, level=?, customerID=?, name=?, surname=?, phone=?, quantities=? WHERE id=?
$insert_stmt->bind_param('ssssissss', $username, $email, $level, $customerID, $firstname, $surname, $phone);
Your bind list has no: password, random_salt, id