Ignore blank empty fields from update using php mysql - php

I need a little help to update mysql. I don't want blank/empty input fields to update but when i keep them blank or empty it automatically updates the fields
here is my code
$sql="UPDATE `tblsitesetup` SET
`site_name` = '".mysqli_real_escape_string($conn,$sitename_new)."',
`site_hometitle` = '".mysqli_real_escape_string($conn,$sitetitle_new)."',
`site_homedescrp` = '".mysqli_real_escape_string($conn,$final_description)."',
`site_homekeywords` = '".mysqli_real_escape_string($conn,$final_keywords)."',
`site_analytics` = '".mysqli_real_escape_string($conn,$final_analytics)."',
`site_ad1` = '".mysqli_real_escape_string($conn,$final_ad1)."',
`site_ad2` = '".mysqli_real_escape_string($conn,$final_ad2)."',
`site_ad3` = '".mysqli_real_escape_string($conn,$final_ad3)."'
WHERE `site_id` = '1'";
$result=mysqli_query($conn,$sql);

The correct way to do it is not to put those items in the query at
all:
$updates = array();
if (!empty($sitename_new))
$updates[] = 'sitename_new="'.mysql_real_escape_string($sitename_new).'"';
if (!empty($sitetitle_new))
$updates[] = 'sitetitle_new="'.mysql_real_escape_string($sitetitle_new).'"';
// .......
// ....... fill all cases here
$updates = implode(', ', $updates);
$sql = "UPDATE tblsitesetup` SET $updates WHERE `site_id` = '1'";
Obviously it would be cleaner to put the changes in an associative array or object, and then loop through them.
Reference: mysql update - skip blank fields?

$update=array('site_name'=>$sitename_new
'site_hometitle' => $sitetitle_new
/* etc ... */
'site_ad3' => $final_ad3 );
$sets=array();
foreach($update as $field => $value )
if( "$value" != "" )
$sets[]="`$field` = ". mysqli_real_escape_string($conn,$field);
if($sets)
{
$sql="UPDATE `tblsitesetup` SET \n".implode(",\n",$sets)."
WHERE `site_id` = '1'";
$result=mysqli_query($conn,$sql);
}
else
{
$result=NULL;
}

Build your SQL string using if statements:
$sql = 'UPDATE TABLE SET ';
If (trim($field)!='') $sql.=' FIELD=$field ';
And so on...
Be sure to have a valid SQL statement at the end.

Related

Update multiple rows in single query php mysql

I am trying to update multiple rows in a single query. Data doesnt get updated in my code. I am trying to join the two tables. When user enters a no. The data from the 2 tables will be displayed which is connected through the foreign key.The data from the table1 gets updated. Where as the columns from the table 2 doesnt get updated. I need to update the second table based on unique id
if($_REQUEST["profile"] == "profile")
{
$Id = $_REQUEST["id"];
$firstname = mysql_real_escape_string($_REQUEST["firstname"]);
$serial = mysql_real_escape_string($_REQUEST["serial"]);
$dom = mysql_real_escape_string($_REQUEST["dom"]);
$idno = $_REQUEST["idno"];
$pow = mysql_real_escape_string(stripslashes($_REQUEST["pow"]));
$address = mysql_real_escape_string(stripslashes($_REQUEST["address"]));
$bookno = mysql_real_escape_string(stripslashes($_REQUEST["bookno"]));
$zone = mysql_real_escape_string(stripslashes($_REQUEST["zone"]));
$mobile = mysql_real_escape_string(stripslashes($_REQUEST["phone"]));
$phone = mysql_real_escape_string(stripslashes($_REQUEST["mobile"]));
$mothertongue=mysql_real_escape_string(stripslashes($_REQUEST["mothertongue"]));
$nof=mysql_real_escape_string(stripslashes($_REQUEST["nof"]));
$email=mysql_real_escape_string(stripslashes($_REQUEST["email"]));
$nom=$_REQUEST["nom"];
$nofemale=$_REQUEST["nofemale"];
mysql_query("UPDATE profile SET firstname='".$firstname."',serial='".$serial."',dom='".$dom."',idno='".$idno."',pow='".$pow."',address='".$address."',bookno='".$bookno."',
zone='".$zone."',phone='".$mobile."',mobile='".$phone."',mothertongue='".$mothertongue."',email='".$email."',nof='".$nof."',nom='".$nom."',nofemale='".$nofemale."' WHERE id = '".$_POST['id']."' " ) or die(mysql_error());
for($i=0;$i<count($_REQUEST['slno1']);$i++)
{
$mid=$_REQUEST['mid'][$i];
$slno1 = mysql_real_escape_string(stripslashes($_REQUEST["slno1"][$i]));
$name1 = mysql_real_escape_string(stripslashes($_REQUEST["name1"][$i]));
$rhof1 = mysql_real_escape_string(stripslashes($_REQUEST["rhof1"][$i]));
$dob1 = mysql_real_escape_string(stripslashes($_REQUEST["dob1"][$i]));
$dobapt1 = mysql_real_escape_string(stripslashes($_REQUEST["dobapt1"][$i]));
$doc1 = mysql_real_escape_string(stripslashes($_REQUEST["doc1"][$i]));
$doconf1 = mysql_real_escape_string(stripslashes($_REQUEST["doconf1"][$i]));
$qualification1 = mysql_real_escape_string(stripslashes($_REQUEST["qualification1"][$i]));
$school1 = mysql_real_escape_string(stripslashes($_REQUEST["school1"][$i]));
$occupation1 = mysql_real_escape_string(stripslashes($_REQUEST["occupation1"][$i]));
$run=mysql_query("UPDATE member SET
slno1='".$slno1."',name1='".$name1."',rhof1='".$rhof1."',dob1='".$dob1."',dobapt1='".$dobapt1."',doc1='".$doc1."',doconf1='".$doconf1."',qualification1='".$qualification1."' WHERE mid = '".$mid."' " ) or die(mysql_error());
}
}
Please use PDO so you won't have to escape strings and so your code gets simpler to read. Your query has too many quotes used and this alone can make it easy to fail. Please use following examples and this should help you succeed.
Basic PDO update:
https://www.w3schools.com/php/php_mysql_update.asp
Bind Params:
https://www.w3schools.com/php/php_mysql_prepared_statements.asp
In your query you are using $_POST['mid'] instead of that you should use $mid which you are already reading as
$mid=$_REQUEST['mid'][$i];
As per my understanding UPDATE query is used to update a limited number of records if using the where condition. So the only way that I can think of is using an INSERT query with ON DUPLICATE KEY UPDATE clause. Try the below code:
for($i=0;$i<count($_REQUEST['mid']);$i++) {
$mid[] = $_REQUEST['mid'][$i];
$slno1[] = mysql_real_escape_string(stripslashes($_REQUEST["slno1"][$i]));
$name1[] = mysql_real_escape_string(stripslashes($_REQUEST["name1"][$i]));
$rhof1[] = mysql_real_escape_string(stripslashes($_REQUEST["rhof1"][$i]));
$dob1[] = mysql_real_escape_string(stripslashes($_REQUEST["dob1"][$i]));
$dobapt1[] = mysql_real_escape_string(stripslashes($_REQUEST["dobapt1"][$i]));
$doc1[] = mysql_real_escape_string(stripslashes($_REQUEST["doc1"][$i]));
$doconf1[] = mysql_real_escape_string(stripslashes($_REQUEST["doconf1"][$i]));
$qualification1[] = mysql_real_escape_string(stripslashes($_REQUEST["qualification1"][$i]));
$school1[] = mysql_real_escape_string(stripslashes($_REQUEST["school1"][$i]));
$occupation1[] = mysql_real_escape_string(stripslashes($_REQUEST["occupation1"][$i]));
}
$query = "INSERT INTO `member` (`mid`,`slno1`,`name1`,`rhof1`,`dob1`,`dobapt1`,`doc1`,`doconf1`,`qualification1`) VALUES ";
for ($i = 0; $i < count($mid); $i++) {
$query .= "('".$mid[$i]."','".$slno1[$i]."','".$name1[$i]."','".$rhof1[$i]."','".$dob1[$i]."','".$dobapt1[$i]."','".$doc1[$i]."','".$doconf1[$i]."','".$qualification1[$i]."')";
if ($i != (count($mid) - 1)) {
$query .= ',';
}
}
$query .= ' ON DUPLICATE KEY UPDATE `slno1` = VALUES(`slno1`), `name1` = VALUES(`name1`), `rhof1` = VALUES(`rhof1`), `dob1` = VALUES(`dob1`), `dobapt1` = VALUES(`dobapt1`), `doc1` = VALUES(`doc1`), `doconf1` = VALUES(`doconf1`), `qualification1` = VALUES(`qualification1`);';
$run=mysql_query($query) or die(mysql_error());
Hope This Helps.

How do I create a parameterized database update statement in Yii for an IN() clause?

I tried
$sql = "update ad_group_keyword set status = :status where google_id not in (:google_id)";
Yii::$app->db->createCommand($sql)
->bindValue(':status', Constants::DELETED)
->bindValue(':google_id', join(',',$googleIds), \PDO::PARAM_INT)
->execute();
but it turned the array of ids into one giant string, despite the PDO::PARAM_INT. I also tried
->bindValue(':google_id', $googleIds)
but it gave an 'Array to string conversion' in vendor/yiisoft/yii2/db/Command.php:172. I ended up using
$sql = "update ad_group_keyword set status = :status where google_id not in (" . join(',',$googleIds) . ")";
I suggest use QueryBuilder for this function:
$command = Yii::$app->db->createCommand();
$result = $command->update( // create a update sql
'ad_group_keyword', // table
['status'=>1], // update set
['NOT IN', 'google_id', [1,2,3]] // where
)->execute();
You can read the \yii\db\Command::update() DOC, and how to set condition
You shouldn't have a join in there at that place. That is where it is being turned into a string. You want to iterate through your list of ids and bindValue each one to the variable in turn.
You'll need to bind each of the array values individually. Something like this:
$sql = "UPDATE ad_group_keyword
SET status = :status
WHERE google_id NOT IN(%s)";
$bindValues = array();
$i = 0;
foreach ($googleIds as $value)
{
$bindValues[':googleId'.$i++] = $value;
}
$sql = sprintf($sql, join(', ', array_keys($bindValues)));
$sqlCommand = Yii::$app->db->createCommand($sql);
$sqlCommand->bindValue(':status', Constants::DELETED);
foreach ($bindValues as $key => $value)
{
$sqlCommand->bindValue($key, $value, \PDO::PARAM_INT);
}
$sqlCommand->execute();
However, I'm only basing this example on your code and I'd look into Yii's manual to see if there already isn't a method that does all of this work for you ... it shouldn't be that hard to safely execute an SQL query using IN().

MySQL UPDATE query - dealing with empty inputs

This is my first UPDATE query, I have checked using jQuery for any empty fields. I want the user to input at least one field and then update the field(s). Doing a query with all the $_POST names might generate empty or undefined input fields in my database which doesn't work.. here is my query:
$first = $_POST['first'];
$last = $_POST['last'];
$birth = $_POST['birth'];
$bio = $_POST['bio'];
$UID = $_SESSION['id'];
$query = "UPDATE `user` SET `firstname`=$first,`lastname`=$last,`birthday`=$birth,`biography`=$bio WHERE `user_id` = '$UID'";
$result = mysql_query($query) or die($result . "<br/><br/>" . mysql_error());
The error:
syntax to use near 'birthday=,biography= WHERE user_id = '11'' at line 1
I don't want to go through nested if's to check whether has a value or not. Thanks.
NOTE: Use mysql_real_escape_string() to prevent from sql injection.
if( !empty($first) &&
!empty($last) &&
!empty($birth) &&
!empty($bio) ){
$query = "UPDATE `user`
SET
`firstname`='$first',
`lastname`='$last',
`birthday`='$birth',
`biography`='$bio'
WHERE `user_id` = '$UID'";
}

How do I update a certain column when a value from the same row equals a variable?

I have been trying to do this for hours now, and I can't quite get my head round it. I have a table called "requests" that has the columns "deletekey" and "deleted". "deletekey" is a random unique number (data-type text), and "deleted" is by default set to 0 (data-type boolean), and when the user inputs the deletekey, it changes "deleted" to 1.
But I can't get it to work.
Here is the code I have, and I have no idea what I'm doing wrong:
$key = $_GET["delkey"];
$link = mysqli_connect("localhost","username","password","dbname");
$query = 'UPDATE requests SET deleted = True WHERE deletekey = "$key"';
$result = $link->query($query);
This should help, and will also provide protection against SQL injection:
$link = mysqli_connect("localhost","username","password","dbname");
$key = $link->real_escape_string($_GET["delkey"]);
$query = sprintf("UPDATE requests SET deleted = 1 WHERE deletekey = '%s'", $key);
$result = $link->query($query);
Shouldn't it be WHERE deletekey = '$key', then? The deleted field could NEVER equal whatever's in $key, since deleted is a simple boolean, and $key is probably an int/char/varchar-type thing.
Note that you are vulnerable to SQL injection attacks. Stop working on this sort of code until you've learned about the problem and how to avoid it.
Its deletedkey = "$key" right ? and not deleted = "$key" :
$key = $_GET["delkey"];
$link = mysqli_connect("localhost","username","password","dbname");
$query = 'UPDATE requests SET deleted = true WHERE deletedkey = "$key"';
$result = $link->query($query);
Try this?
$link = mysqli_connect("localhost","username","password","dbname");
$key = $link->real_escape_string($_GET["delkey"]);
$query = "UPDATE `requests` SET `deleted` = true WHERE `deletedkey` = $key";
$result = $link->query($query);
$query = 'UPDATE requests SET deleted = 1 WHERE deletekey = "$key"';
the query is a string. And to add a variable to a string you need to type
$query = 'UPDATE requests SET deleted = True WHERE deleted = '".$key."';
the difference is how to make a variable put into the string. You have to do like this in php.
$query = "randomtext ". $randomvar ." ";
where the important point is to ". $var ." inside the string. This i similar to javas "+ var +"

PHP variable value to NOT update MySQL table field?

I'm updating a MySQL table with posted PHP data.
I first gather the posted data, and put them in appropriate variables. Together with the necessary if/else checks.
Then, I only have to write my query once.
But now I have an if/else to check wether to update a specific field or not. How can I store a "do-not-update" value inside the corresponding variable?
Because otherwise I have to put an if/else check around the whole query, just for one field.
I just want to be as efficient as possible. :)
My query is as follows:
$updateTable = mysql_query("UPDATE myTable SET field1 = '$field1', field2 = '$field2'");
wherever you are get $_POST into variables, do this,
if( $field2 === 'xyz' ) { //if value is 'xyz', do not update
$sql = '';
} else
$sql = ", field2 = '$field2'";
Then in the query,
$updateTable = mysql_query("UPDATE myTable SET field1 = '$field1' $sql");
Edit: if using 1/0 (true or false),
if( $field2 == true ) { //if value is true, do not update
$sql = '';
} else
$sql = ", field2 = '$field2'";
You will need to build up your query, storing it in a PHP string, for example:
$sql = "UPDATE `table` SET ";
if ($_POST['foo']!=='') {
$sql .= " `foo`='".mysql_real_escape_string($_POST['foo'])."',";
}
if ($_POST['bar']!=='') {
$sql .= " `bar`='".mysql_real_escape_string($_POST['bar'])."',";
}
$sql = rtrim($sql,',');
$sql .= " WHERE `id`='".mysql_real_escape_string($_POST['id'])."'"
Then execute your string as the query.
If you are asking whether the field should be updated, you can do one of two things:
1) Specify a criteria that ensures field1 and field2 are only updated if the rows match the criteria. If the criteria does not match, the record will not be updated. This is the most common way.
UPDATE myTable ...
WHERE criteria1 = 1 AND criteria2 = 'Red'
2) Run a query before the UPDATE to see whether to perform an update.
I'm not exactly sure what you are asking for, but perhaps this answers your question:
$updateTable = mysql_query("
UPDATE myTable SET
field1 = IF('$field1'>'','$field1', field1),
field2 = IF('$field2'>'','$field2', field2)
");
Of course, you are opening yourself up to SQL injection with the code, as written.
Lets assume you have gathered the fields to update in an array $fields like this :
array (
'filed1' => 'value' ,
'field2' => ''value
)
Now you need to generate the query, you can do this by looping in the array:
$sql = "UPDATE mytable ";
$sql .= $fields ? "SET " : "" ;
foreach ($fields as $key=>$value) {
$sql.= $value ? "$key = '$value' , " : '' ;
}
//you need to omit the trailing ','
$sql[strlen($sql) -1 ] = "";
Tips :
Do sanitize all user input using mysqli_real_escape_string or something better than that.
Happy coding :)

Categories