$imagesarray[]=explode('&',$data[5]);
$imag_temp = 0;
foreach($imagesarray as $image){
if($imag_temp == 0 )
{
$this->db->query("UPDATE " . DB_PREFIX . "product SET image = 'media/" . $image[0] . "' WHERE product_id = '" . (int)$product_id . "'");
}else{
foreach($image as $img){
$this->db->query("INSERT INTO " . DB_PREFIX . "product_image SET image = 'media/" . $img . "' , product_id = '" . (int)$product_id . "'");
}
}
$imag_temp++;
}
This is my $data[5]=Arizona Diamondbacks.png&arizona-cardinals.png&Atlanta Braves.jpg&...&...&...n number can have..
I have writend query for each for where..in that every first image should insert to one table and remaining all other images should insert to another table..now for every loop first image conidering as first /.
You don't need $imagesarray[] if this is for a single product.
Say
$data[5] = "Arizona Diamondbacks.png&arizona-cardinals.png&Atlanta Braves.jpg";
$imagesarray = explode('&',$data[5]);
Will create an array like
Array
(
[0] => Arizona Diamondbacks.png
[1] => arizona-cardinals.png
[2] => Atlanta Braves.jpg
)
Then using single variable assign the query to perform
foreach($imagesarray as $key => $image){
if($key == 0 )
{
$query = "UPDATE " . DB_PREFIX . "product SET image = 'media/" . $image . "' WHERE product_id = '" . (int)$product_id . "'";
} else {
$query = "INSERT INTO " . DB_PREFIX . "product_image SET image = 'media/" . $image . "' , product_id = '" . (int)$product_id . "'";
}
$this->db->query($query);
}
what is the error you are getting.. your insert query is not correct.
and other thing you have to notice is what type of array you are getting ...
You can edit this as required
this code is working you can modify with your insert and update query..
<?php
$data[5]='Arizona Diamondbacks.png&arizona-cardinals.png&Atlanta Braves.jpg';
$imagesarray[]=explode('&',$data[5]);
foreach ($imagesarray[0] as $key => $value) {
if($key==0){
echo "hello"; // here is your update query
}
else{
echo "sorry"; // here is your insert query
}
}
I don't know what you want, but you have some basic errors. You should learn more about php and sql before try to code something.
You don't need to add [] to the $imagesarray when explode the $data[5]
In the foreach loop the $image variable is a string, not an array
your INSERT query is incorrect, you should take a look to the documentation http://dev.mysql.com/doc/refman/5.7/en/insert.html
Your code should be something like this
$imagesarray = explode('&',$data[5]);
$imag_temp = 0;
foreach($imagesarray as $image){
if($imag_temp == 0 )
{
$this->db->query("UPDATE " . DB_PREFIX . "product SET image = 'media/$image' WHERE product_id = '$product_id'");
}else{
foreach($image as $img){
$this->db->query("INSERT INTO " . DB_PREFIX . "product_image (image, product_id) VALUES ('media/$image', '$product_id')");
}
}
$imag_temp++;
}
Make some research to learn how sql and php work, and make some debug because your code can have more bugs
Related
Data entered by user:
"product_description": [{
"language_id": 1,
"name": "okayt321sd1a"
}
Update database:
foreach ($data['product_description'] as $product_description) {
foreach ($product_description as $key => $value) {
$a[$key] = $value;
if($a[$key]){
$this->db->query("UPDATE " . DB_PREFIX . "product_description SET language_id = '" . (int)$language_id . "', name = '" . $this->db->escape(html_entity_decode($product_description['name'])) . "', meta_keyword = '" . $this->db->escape(html_entity_decode($product_description['meta_keyword'])) . "', meta_description = '" . $this->db->escape(html_entity_decode($product_description['meta_description'])) . "', description = '" . $this->db->escape($product_description['description']) . "', tag = '" . $this->db->escape($product_description['tag']) . "',
page_title = '" . $this->db->escape($product_description['page_title']) . "',
highlight = '" . $this->db->escape($product_description['highlight']) . "',
whatbox = '" . $this->db->escape($product_description['whatbox']) . "' WHERE product_id = '" . (int)$product_id . "',
");
}
}
}
How can I update data based on user enter, for example, if user enter
"language_id": 1,
"name": "okayt321sd1a"
then I only update this 2 data to database other data will remain, if enter 3 data:
"language_id": 1,
"name": "okayt321sd1a"
page_title
then I only update this 3 data to database other data will remain.
You probably want to do a function that will build the sql for you. I am assuming you are using PDO (I don't know, but this example uses PDO). You should bind parameters/values either way. To add in custom fields, just use array_merge(). You can use array_diff() or unset() to remove unwanted values/keys:
function updateProductDesc($array,$where,$db)
{
foreach($array as $key => $value) {
$sKey = ":{$key}";
$bind[$sKey] = htmlspecialchars($value);
$sql[] = "`{$key}` = {$sKey}";
}
$bind[":where"] = (int) $where;
$query = $db->prepare("UPDATE ".DB_PREFIX."product_description SET ".implode(", ",$sql)." WHERE `product_id` = :where");
$query->execute($bind);
}
foreach ($data['product_description'] as $product_description) {
foreach ($product_description as $key => $value) {
$a[$key] = $value;
if($a[$key]){
updateProductDesc($product_description,$product_id,$this->db);
}
}
}
Hi im unable to apply array_diff() for when user edits the stockroom detail to replace with the new result.
Here is the edit function where i call out all the variables via sql.
function einv_editStockrm($srid,$code,$name,$desc,$remark,$cat)
{
//connect to database
base_connectDatabase();
$User = base_getUserDetail($_SESSION['uID']);
$Stockroom = einv_getStockrmDetail($srid);
base_executeSQL("UPDATE einv_stockroom
SET einv_stockrm_code='" . $code . "',
einv_stockrm_name='" . $name . "',
einv_stockrm_desc='" . $desc . "',
einv_stockrm_remark='" . $remark . "',
einv_stockrm_cat = '" . $cat . "'
WHERE einv_stockrm_id=" . $srid . "");
base_addTransactionLog('Manage Stock Room', 'Edit',
"
Stock Room Code = " . $code . " ||
Stock Room Name = " . $name . " ||
Stock Room Description = " . $desc . " ||
Stock Room Remark = " . $remark . " ||
Stock Room Category = " . $cat . "
");
Here is the array_diff() function. There may be unnecessary calling and/or lack of coding..not too sure. This set of codings result in no output. The server basically crashes. Any help on this?
//oldsr is existing stockroom data
//newsr is new stockroom data through edit function
//resultsr is the end result
<?php
$StockroomGetAllDetails = array();
$arr2 = einv_getStockrmDetailFromCode($stockroomCode);
$codearr = explode(",", $arr2['einv_stockrm_code']);
$oldsr = array($codearr);
$newsr = array($codearr);
$resultsr = array_diff($newsr, $oldsr);
if(!count(array_diff($oldsr, $newsr)) && !count(array_diff($newsr, $oldsr))) {
// Arrays are equal
} else {
// Array values are different
echo $resultsr;
}
?>
This code is for redirect.
//go to stock room page
echo '<script type="text/javascript">' . "\n";
echo 'window.location="../einventory/view_stockrm.php?id='. $srid .'";';
echo '</script>';
//close the database
base_closeDatabase();
}
This set of codes able to display the new datas added and removed accordingly :)
$oldCat = $Stockroom["einv_stockrm_cat"];
$oldCatArr = explode(",",$oldCat);
$newCatArr = explode(",",$cat);
//Debugging
//print_r($oldCatArr);
//print_r($newCatArr);
$resultCatAdd = array_diff($newCatArr, $oldCatArr);
$resultCatRemove = array_diff($oldCatArr, $newCatArr);
//Debugging
print_r($resultCatAdd);
print_r($resultCatRemove);
i am working on dynamic array i need to insert these array in the database.when i insert dynamic array into the database instead of inserting all rows it only inserting one row in the database.
below is the array that contain result
$asma[]=GA::select($ga->population,'total',3);
below is code for inserting multiple array in database table ga
<?php
//code not tested check it
//Logic is changed instead of for looping many times
$data = array();
$j = 0;
foreach($asma as $key => $value)
{
$i = 0;
foreach ( $value as $ind => $hObject )
{
if($i==0)
{
$data[$j]['fe'] = mysql_escape_string($hObject->Voltage);
}else{
$data[$j]['fe'.$i] = mysql_escape_string($hObject->Voltage);
}
$i++;
$data[$j]['fe'.$i] = mysql_escape_string($hObject->Duration);
$i++;
$data[$j]['fe'.$i] = mysql_escape_string($hObject->Number);
$i++;
}
$j++;
}// endforeach
//multiple array
foreach($data as $array)
{
//unique array
//$array3 = array_merge($Voltage,$Duration,$Number);
$fields = implode(',',array_keys($array));
//if you want append any new field append it
$fields .= ','.'timestamp,username';
$vals = "'".implode("','",array_values($array))."'";
//if you want append any new values append it
$vals .= ",'".time()."','".$login_session."'";
$q = "INSERT INTO ga (".$fields.") VALUES(".$vals.")";
$result = mysql_query($q);
if ( ! $result ) {
die( 'Insert failed ' . mysql_errno() . ' ' . mysql_error() );
}
}
whenever user enter 3 then after computation result will store in array asma after store result will store in table ga that should be three rows but only one row insert in the table and display instead of three same in case the user enter any value in the text box.
I'm not sure what you mean, i think is an insert statement like this:
INSERT INTO `ga` (`field1`, `field2`, `field3`, `etc`)
VALUES (value11, value21, value31, more_values1),
(value12, value22, value32, more_values2),
(value13, value23, value33, more_values3)
So you should use your foreach cycle to create the values statement.
$sql = "INSERT INTO `ga` (`voltage`, `duration`, `number`, `timestamp`, `username`) VALUES ";
$values = "";
foreach ($asma as $row) {
$values .= ($values != "" ? "," : "") . "(" .
"'" . $row['voltage'] . "', " .
"'" . $row['voltage'] . "', " .
"'" . $row['number'] . "', " .
"'" . time() . "', " .
"'" . $login_session . "'" .
"),";
}
$sql .= substr($values, 0, -1) . ";";
I have the following php array that gets all values from a form full of radios and check-boxes.
foreach(array('buss_type','anotherfield','anotherfield','...etc') as $index)
{
if (isset($this->request->post[$index])) {
$this->data[$index] = $this->request->post[$index];
} else {
$this->data[$index] = NULL;
}
}
Now, I am wondering how to write the query to send those values to my database, to a new table I just created (retailer). Every radio/checkform value has its column in my retailer table, how do I write the query so that all the values contained in $index go to their specific column.
The following is an example of how my other queries look like...
public function addCustomer($data) {
//this is the one I am trying to write, and this one works,
//but I'd have to add every single checkbox/radio name to the
//query, and I have 30!
$this->db->query("INSERT INTO " . DB_PREFIX . "retailer SET buss_t = '" .
(isset($data['buss_t']) ? (int)$data['buss_t'] : 0) .
"', store_sft = '" .
(isset($data['store_sft']) ? (int)$data['store_sft'] : 0) .
"'");
//Ends Here
$this->db->query("INSERT INTO " . DB_PREFIX . "customer SET store_id = '" .
(int)$this->config->get('config_store_id') . "', firstname = '" .
$this->db->escape($data['firstname']) . "', lastname = '" .
$this->db->escape($data['lastname']) . "', email = '" .
$this->db->escape($data['email']) . "', telephone = '" .
$this->db->escape($data['telephone']) . "', fax = '" .
$this->db->escape($data['fax']) . "', password = '" .
$this->db->escape(md5($data['password'])) . "', newsletter = '" .
(isset($data['newsletter']) ? (int)$data['newsletter'] : 0) .
"', customer_group_id = '" .
(int)$this->config->get('config_customer_group_id') .
"', status = '1', date_added = NOW()");
Thanks a lot for any insight you can provide.
the best way would be to create a function that accepts an array and table name as an argument and executes a insert query.
function insertArray($table, $array)
{
$keys =""; $values = "";
foreach($table as $k=>$v)
{
$keys.=($keys != "" ? ",":"").$k:
$values .=($values != "" ? "," :"")."'".$v."'";
}
$this->db->query("INSERT INTO ".$table." (".$keys.") VALUES (".$values.");
}
The array has to be structured like this:
array("db_attribute1"=>"value1","db_attribute2"=>"value2");
Store the column names and column values in separate arrays and use implode() to generate a comma-separated list of columns and values
$values = array();
$columns = array('buss_type','anotherfield','anotherfield','...etc');
foreach($columns as $index)
{
if (isset($this->request->post[$index]))
{
$this->data[$index] = $this->request->post[$index];
$values[] = $this->db->escape($this->request->post[$index]);
}
else
{
$this->data[$index] = NULL;
$values[] = "''";
}
}
$this->db->query("INSERT INTO table_name (" . implode(",", $columns) . ") VALUES (" . implode(",", $values) . ");
hi am having this trouble trying to save in multiple rows in the table "notification" with a for of customers table ids but it only save me one row this is my code:
$customers = tep_get_customers();
$count = 0;
for ($i=0, $n=sizeof($customers); $i<$n; $i++) {
$count ++;
$insert_str_cony .= $customers[$i]['id'];
$split_customers_id = explode("||", $insert_str_cony.'||', -1);
$values .= "('','" . tep_db_input('1') . "', now(), '" . tep_db_input($products_id) . "', '" . tep_db_input($split_customers_id[$count]) . "'),";
$db_values = substr_replace($values, '', -1, 1);
}
if ($action == 'insert_product') {
tep_db_query("insert into notifications (notify_id, prod_notify, notify_added, prod_id, customers_id) values ". $db_values);
} elseif ($action == 'update_product') {
tep_db_query("update notifications set prod_notify = '" . tep_db_input('1mod') . "', notify_last_mod = now(), prod_id = '" . $HTTP_GET_VARS['pID'] . "', customers_id = '" . tep_db_input($customers['customers_id']) . "'");
}
and this is the function tep_get_customers();
function tep_get_customers() {
$customers_query = tep_db_query("select distinct customers_id from " . TABLE_CUSTOMERS . "");
while ($customers = tep_db_fetch_array($customers_query)) {
$customers_array[] = array('id' => '||'.$customers['customers_id']);
}
return $customers_array;
}
plase need help!!! thanks!
That is because Insert + values insert one row in the database . (You can use Insert with a SELECT query to insert multiple rows using Insert command but that's not your case as I can see ).
Therefore you should provide a script containing multiple insert commands (an insert command for each customer) in order to insert multiple rows into the database.