update database based on user enter from array - php

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);
}
}
}

Related

How to save different Json data to same database table of Mysql using Php

I'm trying to save some json data that gets generated randomly . It can have 6 keys or just 3 keys as shown below.
Array sample:
sample 1:
{
"report": {
"a-key": "a-value",
"b-key": "b-value",
"c-key": "c-value",
"d-key": "d-value",
"e-key": "e-value",
"f-key": "f-value",
}
}
Sample 2:
{
"report": {
"a-key": "a-value",
"c-key": "c-value",
"f-key": "f-value",
}
}
Database Table name : plogs
columns: id,logdate, logtime, a, b, c, d, e,
id is unique key that auto increments
Below is the Php code i tried to use. I was able to successfully generate a text file for each json input without any errors.however I'm not able to save the values to the database. Can you please let me know where im making a mistake.
P.S Part of the code i got it off some tutorials
<?php
// Send `204 No Content` status code.
http_response_code(204);
// Get the raw POST data.
$data = file_get_contents('php://input');
$newfilename = date('Y-m-d-H-i-s') . ".txt";
file_put_contents($newfilename, $data);
// a new json file with one of the 2 sample arrays
$date1 = date('Y-m-d');
$time1 = date('H:i:s');
$b = NULL;
$d = NULL;
$f = NULL;
$connect = mysqli_connect("localhost", "dbuser", "dbpassword", "dbname") or die ("error"); //Connect PHP to MySQL Database
$query = '';
$array = json_decode($data, true); //Convert JSON String into PHP Array
function array_keys_exist(array $array, $keys)
{
$count = 0;
if (!is_array($keys)) {
$keys = func_get_args();
array_shift($keys);
}
foreach ($keys as $key) {
if (isset($array[$key]) || array_key_exists($key, $array)) {
$count++;
}
}
return count($keys) === $count;
}
foreach ($array as $row) //Extract the Array Values by using Foreach Loop
{
if (array_keys_exist($array, 'b-key', 'd-key', 'f-key'))
{
$query .= "INSERT INTO plogs(logdate, logtime, a, b, c, d, e, f) VALUES ('" . $date1 . "', '" . $time1 . "', '" . $row["a-key"] . "', '" . $row["b-key"] . "', '" . $row["c-key"] . "', '" . $row["d-key"] . "', '" . $row["e-key"] . "', '" . $row["f-key"] . "' ); ";
} else
{
$query .= "INSERT INTO plogs(logdate, logtime, a, b, c, d, e, f) VALUES ('" . $date1 . "', '" . $time1 . "', '" . $row["a-key"] . "', '" . $s1 . "', '" . $row["c-key"] . "', '" . $s2 . "', '" . $row["e-key"] . "', '" . $s1 . "'); ";
}
}
mysqli_multi_query($connect, $query);
mysqli_close($connect);
in the code of the foreach loop you are checking if the array keys are in the array variable, you should check in the $row variable as in:
if (array_keys_exist($row, 'b-key', 'd-key', 'f-key')) {
SIDE NOTE: remember to sanitize strings if they come from users, otherwise your code will be unsecure.
EDIT: for real security, as Dharman pointed out in comments, the proper way to proceed is to use prepared statements with parameter binding.
cheers

Opencart: Error No:1062 Duplicate entry '1' for key 'PRIMARY'

I'm developing a carousel extension for opencart that has Item ID, Item Name, Link, Image, Sort Order. The carousel had an issue while saving it will change the item id so I had to modify the code to get fixed ID queryed to the DB, however now I get the 1062 Error.
Notice: Error: Duplicate entry '1' for key 'PRIMARY' Error No: 1062
INSERT INTO crousal SET crousal_id = '1', name = 'Baby & Toys', link =
'/index.php?route=product/product&product_id=7570', image =
'data/carousel/banner2.jpg', sort_order = '0' in
/home/user/public_html/system/database/mysql.php on line 49
Sharing the model/carousel.php editCarousel Function
public function editCrousal($crousal_image) {
$crousal_id = $this->db->getLastId();
$this->db->query("DELETE FROM " . DB_PREFIX . "mobiapp_crousal WHERE crousal_id = '" . (int)$crousal_id . "'");
if (isset($crousal_image['crousal_image'])) {
foreach ($crousal_image['crousal_image'] as $crousal_image) {
$this->db->query("INSERT INTO " . DB_PREFIX . "mobiapp_crousal SET crousal_id = '" . (int)$crousal_id . "', name = '" . $this->db->escape($crousal_image['name']) . "', link = '" . $this->db->escape($crousal_image['link']) . "', image = '" . $this->db->escape($crousal_image['image']) . "', sort_order = '" . (int)$crousal_image['sort_order'] . "'");
$crousal_id = $this->db->getLastId();
}
}
}
Any advice why I'm getting this error and how to resolve, thank you in advanced.
P.S.: Opencart 1.5.x
Edited: DB Structure & Module info
$this->db->query("
CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "mobiapp_crousal` (
`crousal_id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
`link` VARCHAR(255) NOT NULL,
`image` VARCHAR(255) NOT NULL,
`sort_order` INT(3) NOT NULL,
PRIMARY KEY (`crousal_id`)
) ENGINE=MyISAM DEFAULT COLLATE=utf8_general_ci;");
Model File
public function addCrousal($crousal_image) {
$this->db->query("INSERT INTO " . DB_PREFIX . "mobiapp_crousal SET name = '" . $this->db->escape($crousal_image['name']) . "', sort_order = '" . (int)$crousal_image['sort_order'] . "'");
$crousal_id = $this->db->getLastId();
if (isset($crousal_image['crousal_image'])) {
foreach ($crousal_image['crousal_image'] as $crousal_image) {
$this->db->query("INSERT INTO " . DB_PREFIX . "mobiapp_crousal SET crousal_id = '" . (int)$crousal_id . "', link = '" . $this->db->escape($crousal_image['link']) . "', image = '" . $this->db->escape($crousal_image['image']) . "'");
$crousal_id = $this->db->getLastId();
}
}
}
public function editCrousal($crousal_image) {
$crousal_id = $this->db->getLastId();
$this->db->query("DELETE FROM " . DB_PREFIX . "mobiapp_crousal WHERE crousal_id = '" . (int)$crousal_id . "'");
if (isset($crousal_image['crousal_image'])) {
foreach ($crousal_image['crousal_image'] as $crousal_image) {
$this->db->query("INSERT INTO " . DB_PREFIX . "mobiapp_crousal SET crousal_id = '" . (int)$crousal_id . "', name = '" . $this->db->escape($crousal_image['name']) . "', link = '" . $this->db->escape($crousal_image['link']) . "', image = '" . $this->db->escape($crousal_image['image']) . "', sort_order = '" . (int)$crousal_image['sort_order'] . "'");
$crousal_id = $this->db->getLastId();
}
}
}
public function getCrousalImages() {
$crousal_image_data = array();
$crousal_image_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "mobiapp_crousal ORDER BY sort_order ASC");
foreach ($crousal_image_query->rows as $crousal_image) {
$crousal_image_description_data = array();
$crousal_image_description_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "mobiapp_crousal WHERE crousal_id = '" . (int)$crousal_image['crousal_id'] . "'");
$crousal_image_data[] = array(
'crousal_image' => $crousal_image,
'link' => $crousal_image['link'],
'name' => $crousal_image['name'],
'crousal_id' => $crousal_image['crousal_id'],
'image' => $crousal_image['image'],
'sort_order' => $crousal_image['sort_order']
);
}
return $crousal_image_data;
}
I did review for this module. Seems like this module has totally wrong structure. As you can see in method addCrousal foreach-statement with insertion to database. But in this insert carousal_id not incrementing so in the table will be records with not unique carousal_id. So this column can't be PRIMARY.
I suggest you to rewrite module with two tables "Slides" with relations (has many) "Images". Or you can remove PRIMARY index and operation will pass but it's not true solution.

ForEach loop data insert into two database table

$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

jquery jtable inserting/updating record with apostrophe

I have jtable working perfectly fine with adding/editing/removing records however I cant insert/update a record that contains an apostrophe ! Someone please help!
Below is a snapshot fo my code
Blockquote //Updating a record (updateAction)
$result = mysql_query("UPDATE teg_priority SET CustomerName = '" . $_POST["CustomerName"] . "', Service_Manager = '" . $_POST["Service_Manager"]. "', NGM = '" . $_POST["NGM"] . "', Tag = '" . $_POST["Tag"] . "', CBS = '" . $_POST["CBS"]. "' WHERE CIDN = " . $_POST["CIDN"] . ";");
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
print json_encode($jTableResult);
}
Blockquote
You can use addslashes on the variables before putting them in the query.
$result = mysql_query("UPDATE teg_priority SET CustomerName = '" . addslashes($_POST["CustomerName"]) . "', Service_Manager = '" . addslashes($_POST["Service_Manager"]). "', NGM = '" . addslashes($_POST["NGM"]) . "', Tag = '" . addslashes($_POST["Tag"]) . "', CBS = '" . addslashes($_POST["CBS"]). "' WHERE CIDN = " .addslashes( $_POST["CIDN"]) . ";");

How to write query for a php array?

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) . ");

Categories