update only not null input value in mysql using PHP - php

i have a database contain thousands of row, the user can update his/her row by providing the updated values, i need to update the row only with a non null values provided by the user, if the value provided by user is null the previous data should be remain, for example:
id=1
name = John
address = USA
if the user provide name with null value and address with UK value then the data should be:
id=1
name =John
address = UK
any help with php code example will be highly appreciated.

You should loop through the $_POST superglobal and construct a new array for insertion that does not include the nulls, then use that for your query instead of $_POST directly.
$update = array();
foreach ($_POST as $key => $value) {
if(!is_null($value) && !($value == ''))
$update[$key] = $value;
}
Then use $update for your query parameters, which should not contain any null or blank values.

I use PDO connection
First create a table and insert as follows
create table testing(id int(11), name varchar(100),address varchar(200));
insert into testing values(100,'Null','California');
insert into testing values(200,'sectona','California');
pdo_connect.php
<?php
$db = new PDO (
'mysql:host=localhost;dbname=yourdbname;charset=utf8',
'root', // username
'root' // password
);
?>
<?php
pdo_connect.php
// from form inputs
/*
$id=$_POST["id"];
$name=$_POST["name"];
$address=$_POST["address"];
*/
// direct variable initialisation
/*
$id='100';
$name = 'John';
$name = 'Null';
$address = 'California';
*/
// initialize a null value
$check ='Null';
// check null value for name variable in the first insert statement
$resultn = $db->prepare('SELECT * FROM testing where name = :name');
$resultn->execute(array(
':name' => 'Null'
));
while ($row = $resultn->fetch())
{
$nm = $row['name'];
}
if ($nm == $check)
{
echo '<b><font color=red><b></b>You cannot update with a Null Value</font></b>';
exit();
}
// update if name is not null
$update = $db->prepare('
UPDATE testing SET
name = :name,address = :address
WHERE id= :id');
$update->execute(array(
':name' => 'yourname',
':address' => 'USA',
':id' => '100'
));
echo 'update successful';
?>
finall to update using a non null value from database, then substitute the code below in the query statements
$resultn = $db->prepare('SELECT * FROM testing where name = :name');
$resultn->execute(array(
':name' => 'sectona'
));

Related

Update as NULL Mysql

<form action="hi.php" method="post">
<input type="text" name="id" />
<input type="hidden" name="name" value="name" />
</form>
I send this input with no value. I want to update id column as NULL.
$id = $_POST['id'];
$name = $_POST['name'];
$mysqli->query("UPDATE table SET id=$id WHERE name='$name');
However that updates it as empty not NULL. How I can insert NULL in $id?
If I send a value with <input name="id">, it updates it correctly. However if I send it empty, column becomes empty, I want it as NULL.
When using prepared statements and parameters, a NULL value in one of the parameters will also be treated as NULL by the MySQL server.
HTTP parameters are transported as strings. If no value has been given for an input control, the value for the key/value-pair will be an empty string (!=NULL). But you can still have somethig like if(emptystring) use NULL in your script.
e.g.
<?php
// only for this example; otherwise leave _POST alone....
$_POST['id'] = 1;
$_POST['name'] = '';
$mysqli = new mysqli('localhost', 'localonly', 'localonly', 'test');
if ($mysqli->connect_errno) {
trigger_error( sprintf('mysqli connect error (%d) %s', $mysqli->connect_errno, $mysqli->connect_error), E_USER_ERROR);
die;
}
mysqli_report(MYSQLI_REPORT_STRICT|MYSQLI_REPORT_ALL); // that's all the "error handling" for this example....
setup($mysqli);
// even if the user didn't fill in any value, the parameters should be in the request
// as empty strings
if ( !isset($_POST['name'], $_POST['id']) ) {
echo 'missing POST paramete';
}
else {
// <-- maybe some plausiblity checks here anyway; e.g. some assumptions about the id you can test, leaving it out as optional for now --->
// decision point: applying trim() to _POST[name] and _then_ consider it NULL or not - you might disagree about the specifics, just an example.
$name = trim($_POST['name']);
if ( 0===strlen($name) ) {
$name = NULL;
}
// <-- actually it would suffice to establish the databse connection here....
$stmt = $mysqli->prepare('UPDATE soFoo set name=? WHERE id=?');
$stmt->bind_param('ss', $name, $_POST['id']);
$stmt->execute();
printTable($mysqli);
}
function printTable($mysqli) {
$result = $mysqli->query('SELECT * FROM soFoo ORDER BY id');
foreach( $result as $row ) {
var_export($row); echo "\r\n";
}
}
function setup($mysqli) {
$mysqli->query('CREATE TEMPORARY TABLE soFoo (id int, name varchar(32), primary key(id))');
$mysqli->query("INSERT INTO soFoo (id,name) VALUES(1,'oldname1'),(2,'oldname2')");
}
prints
array (
'id' => '1',
'name' => NULL,
)
array (
'id' => '2',
'name' => 'oldname2',
)
I suggest you use PDO, and not mysql() but this will give you the idea:
$id = $_POST['id'];
if($id==''){
$id='NULL';
}
else{
$id = mysql_real_escape_string($id);
}
$qr = 'Update table SET id='.$id;
mysql_query($qr);

Update MYSQL row with non null value only

i have a table contain huge number of rows and i need to update row with specific ID, for example assume i have a row with below details:
Id= 1
Name= lessa
Address = USA
now i used below PHP code to update the row:
<?php
$con = mysqli_connect("localhost","MyUserName","MyPassword","DB");
$id = '1';
$name = "";
$address = "UK";
// update only non value items
$r=mysqli_query($sql);
mysqli_close($con);
?>
now my issue since the value of address is changed from USA to UK i need to update this value only, also since the name value is nothing the name should be remain so after update the row should be like below:
ID=1
Name = lessa
Address = UK
Also if in another time the name value changed and address remain the same i need to update the name only.
also assume i have 100 column not only three as this example.
any help for write the update statement will be appreciated.
Update:
I use below code but no update happen:
<?php
$con = mysqli_connect(DB info);
$id = 'jo_12';
$name = "";
$address = "UK";
$sql = "UPDATE info
SET name = IF(? = '', name, ?),
address = IF(? = '', address, ?)
WHERE id = ?";
$stmt = $con->prepare($sql);
$stmt->bind_param("ssssi", $name, $name, $address, $address, $id);
$stmt->execute();
mysqli_close($con);
?>
Put tests in the UPDATE query:
$sql = "UPDATE yourTable
SET name = IF(? = '', name, ?),
address = IF(? = '', address, ?)
WHERE id = ?";
$stmt = $con->prepare($sql) or die ($con->error);
$stmt->bind_param("sssss", $name, $name, $address, $address, $id);
$stmt->execute();
The IF() tests assign the old value of the column back to it if the variable is empty.
Try to use this SQL query:
UPDATE table_name SET Address='UK' WHERE ID=1
You can of course substitute ID=1 for any other number.

PDOStatement->prepare and PDOStatement->bindParam() combination not working [duplicate]

This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 8 years ago.
I have some code that should loop through values and change entries in a table. The 5 values of the variables $change_val, $column, and $id all echo out correctly, so I assume there is something wrong with my usage of bindParam (but I am not sure what it is).
$connection = new PDO("mysql:host=localhost;dbname=logbook", $username, $password);
$perform_edit = $connection->prepare("UPDATE contacts SET :column = :value WHERE name_id = :name_id");
[Definition of Arrays]
for ($i = 1; $i <= 5; $i++) {
if (!empty($_POST[ $change_array[$i]])) {
$change_val = $_POST[$change_array[$i]];
$column = $column_array[$i];
$id = $_POST["name_id_ref"];
$perform_edit->bindParam(":column", $column, PDO::PARAM_STR);
$perform_edit->bindParam(":value", $_POST[$change_array[$i]], PDO::PARAM_STR);
$perform_edit->bindParam(":name_id", $_POST["name_id_ref"], PDO::PARAM_INT);
$perform_edit->execute();
}
}
The $_POST statement is there because the value I want is actually passed from another file. When I place appropriate echo statements within the loop, though, they all print out their correct value.
I've also tried bindValue, but that did not work either. I see no errors and things at least compile smoothly—just not as they should. Nothing in the table is changed.
What's wrong here?
You cannot use place holders for table or column names it would defeat the purpose of preparing a statement ahead of time if the structure of that statement changed.
You would need to pre-build your prepare statement with the correct column names, whether you name them by hand, string replacement, or implode a list of column names.
I don't have an environment to test on right now but something like:
//Some random values and DB column names
$arrLocation = array ('Victoria','Washington','Toronto','Halifax','Vancouver');
$arrName = array ('Sue', 'Bob', 'Marley', 'Tim', 'Fae');
$arrColumn = array (1 => 'name', 2 => 'age', 3 => 'location');
/* Build column & named placeholders
* $strSet = '`name` = :name, `age` = :age, `location` = :location';
*/
$strSet = '';
foreach ($arrColumn as $column) {
$strSet .= "`$column` = :$column, ";
}
$strSet = rtrim($strSet, ', ');
$connection = new PDO($dsn, $user, $pass);
/*
* Prepared statement then evaluates to:
* UPDATE `table` SET `name` = :name, `age` = :age, `location` = :location
* WHERE `id` = :id;
*/
$stmt = $connection->prepare("UPDATE `table` SET $strSet WHERE `id` = :id;");
$arrChange = array (
1 => $arrName[(rand(0, count($arrName)-1))],
2 => rand(0, 30),
3 => $arrLocation[(rand(0, count($arrLocation)-1))]
);
$idToUpdate = 1;
$stmt->bindParam(':id', $idToUpdate, PDO::PARAM_INT);
foreach($arrChange as $key=>$value) {
$stmt->bindValue(":$arrColumn[$key]", $value);
}
$stmt->execute();

save pdo execution results into an array?

I am using the following to update a table in my db with various values (I have shortened this example to two). Given an array of users ($user_set) I check to see if settings for the user exist... if they do I update the users row... if they do not then I create a row for the user.
The code below works fine, however, I need to return an array of the rows I just changed so I can update the page display with js.
Essentially what I want to do is $result_array[] = $stmt->execute($binding); (all values of the row updated/inserted)
This way I could echo json_encode($result_array); and have an array of all rows I just updated/inserted for use with js.
Is something like this possible or will I need to create the array on my own in php to return?
<?php
//set bindings
$binding = array(
'one' => $settings['one'],
'two' => $settings['two'],
'user_id' => $user['user_id']
);
foreach($user_set as $key)
{
// check if program settings exist or not
$stmt = $db->prepare("SELECT * FROM settings WHERE user_id = ?");
$stmt->execute(array($key['user_id']));
// program_settings result is
$result = $stmt->fetch(PDO::FETCH_ASSOC);
// if result then settings exist and update... if not insert one
if($result)
{
//prepare update statement
$stmt = $db->prepare("UPDATE settings SET one = :one, two = :two WHERE user_id = :user_id");
}
else
{
//prepare insert statement
$stmt = $db->prepare("INSERT INTO settings (user_id, one, two) VALUES (:user_id, :one, :two)");
}
//set comp id
$binding['user_id'] = $key['user_id'];
// execute the update
$stmt->execute($binding);
}
?>
After you use a stmt->execute(); to execute some sql, you can use stmt->fetchAll(); to take all of the rows that has been affected by your sql statement.

Why does this UPDATE procedure update every row?

I have a MySQL stored procedure like this
UPDATE `Discounts` SET `Occupation`=occupation,
`Organization`=organization,
`LastName`=lastName,
`FirstName`=firstName,
`Email`=email,
`Phone`=phone,
`Description`=description,
`ExpirationDate`=expiration,
`Notes`=notes
WHERE `ID` = id
and I'm calling it with this PHP
$occupation = $_POST["occupation"];
$organization = $_POST["organization"];
$last = $_POST["last"];
$first = $_POST["first"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$description = $_POST["description"];
$notes = $_POST["notes"];
$expiration = date("Y-m-d H:i:s", strtotime($_POST["expiration"]));
$id = intval($_POST["id"], 10);
$password = $_POST["password"];
$mysqli = new mysqli("localhost", "xxx", $password, "xxxxxxxx");
if ($mysqli->connect_errno) {
die("Could not connect");
}
$stmt = mysqli_stmt_init($mysqli);
if (mysqli_stmt_prepare($stmt, 'CALL UpdateDiscount(?,?,?,?,?,?,?,?,?,?)')) {
mysqli_stmt_bind_param($stmt, "isssssssss",
$id,
$occupation,
$last,
$first,
$email,
$phone,
$description,
$organization,
$notes,
$expiration);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo "Success!";
}
The update works exactly as I expected except that it updates every single row instead of the one row corresponding to the ID. I can't understand why this is happening, I have a WHERE 'ID'=id check. What is going on? How can I make it so that it only updates a single row?
Because `ID` is the case sensitive name of your column and id is the case insensitive name of the same column.
edit this is wrong: You should be using a PHP variable where the lowercase id is. Something like $id.
In your case you're calling a procedure with bound parameters.
Use a different name for the id parameter.
It's an issue of name-scoping local variable beloging to the procedure, versus argument variable belonging to the procedure versus the table column name.
In stored procedures, when a name conflict occurs between field and parameter names, the parameters are used.
Your query is parsed as:
UPDATE ...
WHERE :id = :id
which is always true (unless you pass a NULL)
Prepend the parameter names with an underscore:
CREATE PROCEDURE myprc (_id, _occupation, ...)
AS
BEGIN
UPDATE mytable
SET occupation = _occupation
WHERE id = _id;
END;

Categories