Right now the update only works if all textboxes are filled out, so the user can't just update productName for example. There isn't an error, but if the other textboxes are left blank then the database is updated with blanks and 0's. I want this to update whatever textboxes receive input, be it one or all, and leave the rest of the info alone if nothing is entered.
If productName for that row is Samsung, description is 'A phone' wholesalePrice is 179.99 and I just update the productName textbox only I still want the description and wholesalePrice to stay the same. Right now if I just update the productName only then the wholesalePrice shows as 0.00 and the description is blank. I tried using OR statements rather than commas in the query and whatever textbox I entered info in returned a 0.
if(isset($_POST['id'])) {
try {
$query = "UPDATE products SET productName = :productName, description = :description, wholesalePrice = :wholesalePrice,
retailPrice = :retailPrice, category = :category, quantityOnHand = :quantityOnHand
WHERE productID = :productID";
$statement = $db->prepare($query);
$statement->bindValue(':productID', $_POST['id']);
$statement->bindValue(':productName', $productName);
$statement->bindValue(':description', $description);
$statement->bindValue(':wholesalePrice', $wholesalePrice);
$statement->bindValue(':retailPrice', $retailPrice);
$statement->bindValue(':category', $category);
$statement->bindValue(':quantityOnHand', $quantityOnHand);
$statement->execute();
$statement->closeCursor();
//reload page after data is entered into the table and display a message if successful for 3 seconds before redirect
$page = $_SERVER['PHP_SELF'];
header('Location: ' . $_SERVER["HTTP_REFERER"] );
exit;
You can use a helper array for your columns to bind values dynamically if each $_POST value is set. Then you can create the update query for only those values.
$fields = array('productName', 'description', 'wholesalePrice', 'retailPrice', 'category', 'quantityOnHand');
$values = array();
$binds = array();
foreach($fields as $key => $value) {
if (isset($_POST[$value])) {
$values[] = $value.' = :'.$value;
$binds[':'.$value] = $_POST[$value];
}
}
if (!empty($values)) {
$query = "UPDATE products SET ";
$query .= implode(', ', $values);
$query .= " WHERE productID = :productID";
$binds[':productID'] = $_POST['id'];
$statement = $db->prepare($query);
$statement->execute($binds);
$statement->closeCursor();
}
EDIT:
If you have the values stored in variables then you can use variable variables:
foreach($fields as $key => $value) {
if (isset($$value)) {
$values[] = $value.' = :'.$value;
$binds[':'.$value] = $$value;
}
}
You need to pass all existing values to form fields so existing data is passed to the sql update if nothing changes. On submit validate the data, then do the update.
<textarea name="description">'.$row['description'].'</textarea>
if(isset($_POST['id'])) {
$productname = $_POST['productname'];
$description = $_POST['description'];
// etc ....
try {
// sql
}catch{
// error
}
}
Related
With this query I update images fields in database:
$sql = $connection->prepare('UPDATE ads img1 = ?, img2 = ?, img3 = ? WHERE id = ?');
$sql->bind_param("ssss", $nameImg1, $nameImg2, $nameImg3, $id);
But this work fine if user update all 3 images, not only one or two. if user change just one image, for example change img2, img1 and img3 going to update to empty value because I use this condition:
$img1 = $_POST["img-1-val"];
$img2 = $_POST["img-2-val"];
$img3 = $_POST["img-3-val"];
if($img1 != 'NULL'){
$nameImg1 = $date.'_'.$adsid.'_1';
}
if($img2 != 'NULL'){
$nameImg2 = $date.'_'.$adsid.'_2';
}
if($img3 != 'NULL'){
$nameImg3 = $date.'_'.$adsid.'_3';
}
in html:
<input type="hidden" name="img-1-val" value="NULL"/>
<!-- this already has image -->
<input type="hidden" name="img-2-val"/>
<input type="hidden" name="img-3-val"/>
If each image has image, value is NULL if there is no image set, it is empty, if user change any image, it set base64 value.
But the main problem is, I don't want to update any img field in database if $_POST return NULL as value, already it update all fields, img1, img2, img3,and this cause of removing previously data. How can I update database field if value not equal to NULL?
Consider these codes run in edit page.
Also my problem is mysqli query not if condition.
You can make your update query dynamic like this :
/* function to build SQL UPDATE string */
function build_sql_update($table, $data, $where)
{
$cols = array();
foreach($data as $key=>$val) {
if($val != NULL) // check if value is not null then only add that colunm to array
{
$cols[] = "$key = '$val'";
}
}
$sql = "UPDATE $table SET " . implode(', ', $cols) . " WHERE $where";
return($sql);
}
In this way, only those columns will be updated which has valid values.
So, you have to just check with different variable with query.
This will check one by one image and if all the images have values then it will update all three images otherwise one by one.
This may help.
if((isset($img1)) && ($img1 != 'NULL')){
$nameImg1 = $date.'_'.$adsid.'_1';
$sql = $connection->prepare('UPDATE ads img1 = ? WHERE id = ?');
$sql->bind_param("ss", $nameImg1, $id);
}
if((isset($img2)) && ($img2 != 'NULL')){
$nameImg2 = $date.'_'.$adsid.'_2';
$sql = $connection->prepare('UPDATE ads img2 = ? WHERE id = ?');
$sql->bind_param("ss", $nameImg2, $id);
}
if((isset($img3)) && ($img3 != 'NULL')){
$nameImg3 = $date.'_'.$adsid.'_3';
$sql = $connection->prepare('UPDATE ads img3 = ? WHERE id = ?');
$sql->bind_param("ss", $nameImg3, $id);
}
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.
I have an array: productid = [1,2]. Now I want to fetch data from product table by using this part of code:
$sql = 'SELECT name FROM product WHERE id=:id';
$s = $pdo->prepare($sql);
foreach($productid as $id)
{
$s->bindValue(':id', $id);
$s->execute();
}
when I returned the names as follow:
foreach($s as $row)
{
$name[] = array(
'name' => $row['name']
);
}
I just got the product name of second id and didn't get both names.
What's the problem?
I just got the product name of second id and didn't get both names. What's the problem?
You've got to put your $name[] = $row['name']; (yes, that's right notation) code inside of the foreach loop, as well as code that actually fetches the data.
You may also form a IN() statement that should be looks like IN (?,?,?,?) and run it in one query. Something like this (not tested):
$in = trim(str_repeat('?,',count($productid)).",");
$sql = "SELECT name FROM product WHERE id IN ($id)";
$stmt = $db->prepare($sql);
$stmt->execute($productid);
$name = $stmt->fetchAll();
I have an array that grabs checkbox data and posts certain information into the database if the checkbox data isn't a copy of something already in the database. What I would like to know is how can I create a code that scans through the database and finds data that wasn't part of my checkbox data and delete it from the database.
Okay, for example let's say I have values 1,2,3,4 in my database, but in my checkboxes I only get back 1,2,4. I would like a code that scans my database and deletes that value(s) (in this case 3) from the database.
Here is my current code:
foreach($_POST['publish'] as $index => $val){
$matches = mysql_query("SELECT * FROM `$blog_table` WHERE `postID` = '$val");
if (mysql_num_rows($matches) > 0)
{
// do nothing
} else {
$query3 = "insert into `$blog_table`
(`postID`)values
('$val')";
mysql_query($query3);
}
}
Here would be the code I would use with escaped input
if (!empty($_POST['publish']))
{
$inserts = array();
$deletes = array();
foreach ($_POST['publish'] as $val)
{
$deletes[] = intval($val);
$inserts[] = '('.intval($val).')';
}
$delete = "DELETE FROM `".$blog_table."` WHERE postID NOT IN (".implode(',',$deletes).");";
$insert = "INSERT INTO `".$blog_table."` (`postID`) VALUES ".implode(',',$inserts)."";
}
you should use query like this:
delete from table where id NOT in (3)
in php like:
$query = "DELETE FROM `$blog_table` WHERE `postID` NOT IN (" . implode(',', $array) . ")";
For the MySQL query, you can use NOT IN:
DELETE FROM tablename
WHERE col1 NOT IN (1, 2, 4)
i have an array of company name, i insert each company name as separate record.below is the code
<input type="text" name="company_name[]">
$company_name = $_POST['company_name'];
if($company_name)
{
foreach($company_name as $company)
{
$mycompany[] = $company;
}
}
$val="('".implode("'), ('",$mycompany)."')";
$sql = "INSERT INTO `table`
(`company_name`) VALUES ".$val."";
The above query look like this and it successfully inserted 2 records in table.
INSERT INTO `table` (`company_name`) VALUES ('DELL'), ('IBM')
Now the problem is that with every company_name there is a company_code which i want to insert with each record and there is 3rd values lets suppose order_num which i also want to insert but the order_num should be same in all records,i need the query below
INSERT INTO `table` (`order_num`,`company_name`,`company_code`) VALUES ('123','DELL','axc89'), ('123','IBM','bxc90')
Okay, at last you endeavored to produce something understandable
1) This this code is absolutely useless:
$company_name = $_POST['company_name'];
if($company_name)
{
foreach($company_name as $company)
{
$mycompany[] = $company;
}
}
as $mycompany being an exact duplicate of $company_name
2) To get your "very complex" query
foreach($_POST['company_name'] as $key => $value)
{
$name = mysql_real_escape_string($value);
$code = mysql_real_escape_string($_POST['company_code'][$key]);
$mycompany[] = "(123,'$name','$code')";
}
$sql = "INSERT INTO `table` (order_num,company_name,company_code) VALUES ";
$sql .= implode(",",$mycompany);
INSERT INTO `table` (`order_num`,`company_name`,`company_code`) VALUES ('123','DELL','axc89');
INSERT INTO `table` (`order_num`,`company_name`,`company_code`) VALUES ('123','IBM','bxc90');
You can use an array
$arrray_to_be_inserted=array
(
[0]=>array('123','DELL','axc89'),
[1]=>array('123','IBM','bxc90')
);
Instead of passing value to a new variable in foreach , try to access as $key and $value, try this and see if it can help you
<?php
$company_name = array("DEL","IBM");
$company_code = array("1","2");
$order_num = array("4","5");
if($company_name)
{
foreach($company_name as $key => $value)
{
$mycompany[] = $value;
$mycompanycode[] = $company_code[$key];
$myordernum[] = $order_num[$key];
}
}
?>
Just make sure names and their values are corresponding to each other .