mysqli prepared statement - do not update NULL values - php

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

Related

Update already existing values while adding new ones

I'm inserting some values into my database.
$stmt = $conn->prepare("INSERT INTO `members` (`id`, `name`, `nickname`, `prefix`, `suffix`) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("sssss",$row['member_id'], $row['name'], $row['nickname'], $row['prefix'], $row['suffix']);
$stmt->execute();
This does what I want: if a new user has joined this will add them to members. However, if an already existing member has changed their nickname this info doesn't get updated. I would like to 1) add new members like it currently does but also 2) update the nicknames for already existing members if there are any changes.
I tried adding the following code after the one above (first add members and then update) but it doesn't seem to work as I wanted.
$stmt = $conn->prepare("UPDATE members SET nickname = '?' WHERE id = '?'");
$stmt->bind_param("ss",$row['nickname'], $row['id']);
$stmt->execute();
You can use REPLACE INTO instead of INSERT INTO
Your prepare() would have
REPLACE INTO `members` (`id`, `name`, `nickname`, `prefix`, `suffix`) VALUES (?, ?, ?, ?, ?)
REPLACE updates the new data if the primary key value already exists.
More details here: https://dev.mysql.com/doc/refman/5.5/en/replace.html

How to fix stmt prepare and bind

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 ,.

Issue On Inserting Auto Incremented ID in MySQL Using Prepared Statement

I have table in MySQL database called MyGuests which has 4 fields as : id (PK and Auto Increment), name,age and email. I am using following code to insert data from user input form to the database:
<?php
$sql = mysqli('localhost','user','password','database');
$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];
$query = $sql->prepare("INSERT INTO MyGuests ( id, name, age, email) VALUES (?, ?, ?, ?)");
$query->bind_param("isis",$name,$age,$email);
$query->execute();
?>
now I am confused how to insert value for id which is auto incremented field using the Prepared statement! As you can see I passed 4 parameters as (?, ?, ?, ?) for data entry and used the "isis" for bind_param(); but not sure what must put in $name,$age,$email for id?
Can you please help me to figure this out?
Thanks
Just omit the id in the query i.e.
INSERT INTO MyGuests ( name, age, email) VALUES (?, ?, ?)
It will automatically add the incremented id, hence the name :)
one more option is supplying null value to the auto-increment column:
ie.
instead of $query = $sql->prepare("INSERT INTO MyGuests ( id, name, age, email) VALUES (?, ?, ?, ?)"); use $query = $sql->prepare("INSERT INTO MyGuests ( id, name, age, email) VALUES (null, ?, ?, ?)");

Prepare Statement Issue sending encrypted information

This is my current statement. Everything was working fine until I added the key
Key is just a generated hash for the user to activate the account.
$stmt = $mysqli->prepare("INSERT INTO Account (accountUsername,accountPassword,accountEmail,accountActivate,accountKey) VALUES (?, ?, ?,?,?)");
$stmt->bind_param('sssiss', $username, $newPassword, $email,0,$key,time());
When I'm doing this code I'm getting an error.
Cannot pass parameter 5 by reference
Do you know what could be the issue?
Thanks!
Edit Code:
$stmt = $mysqli->prepare("INSERT INTO Account (accountUsername,accountPassword,accountEmail,accountActivate,accountKey,accountCreated) VALUES (?, ?, ?,?,?,?)");
$stmt->bind_param('sssisi', $username, $newPassword, $email,0,$key,$time);
http://i.stack.imgur.com/Th5tl.png
If you use bind_param that 0 needs to be in a variable since bind_param passes by reference.
$somevar=0;
$stmt = $mysqli->prepare("INSERT INTO Account (accountUsername,accountPassword,accountEmail,accountActivate,accountKey) VALUES (?, ?, ?, ?,?,?)");
$stmt->bind_param('sssiss', $username, $newPassword, $email,$somevar,$key,$time);

is it possible to utilize two $stmt mysqli

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

Categories