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) . ");
Related
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
I`m stuck for some time to fix this trouble. I followed this article https://www.sitepoint.com/creating-a-scrud-system-using-jquery-json-and-datatables/
to create SCRUD System. But I stuck when I need to add a new record to PostgreSQL.
The working MySQL part of the code is:
$db_server = 'localhost';
$db_username = 'root';
$db_password = '123456';
$db_name = 'test';
$db_connection = mysqli_connect($db_server, $db_username, $db_password, $db_name);
$query = "INSERT INTO it_companies SET ";
if (isset($_GET['rank'])) { $query .= "rank = '" . mysqli_real_escape_string($db_connection, $_GET['rank']) . "', "; }
if (isset($_GET['company_name'])) { $query .= "company_name = '" . mysqli_real_escape_string($db_connection, $_GET['company_name']) . "', "; }
if (isset($_GET['industries'])) { $query .= "industries = '" . mysqli_real_escape_string($db_connection, $_GET['industries']) . "', "; }
if (isset($_GET['revenue'])) { $query .= "revenue = '" . mysqli_real_escape_string($db_connection, $_GET['revenue']) . "', "; }
if (isset($_GET['fiscal_year'])) { $query .= "fiscal_year = '" . mysqli_real_escape_string($db_connection, $_GET['fiscal_year']) . "', "; }
if (isset($_GET['employees'])) { $query .= "employees = '" . mysqli_real_escape_string($db_connection, $_GET['employees']) . "', "; }
if (isset($_GET['market_cap'])) { $query .= "market_cap = '" . mysqli_real_escape_string($db_connection, $_GET['market_cap']) . "', "; }
if (isset($_GET['headquarters'])) { $query .= "headquarters = '" . mysqli_real_escape_string($db_connection, $_GET['headquarters']) . "'"; }
$query = mysqli_query($db_connection, $query);
I managed to write this and it fails to work for PostgreSQL:
$conn_string = "dbname=test user=postgres password=123456";
$query = "INSERT INTO it_companies VALUES ";
if (isset($_GET['rank'])) { $query .= "('" . pg_escape_string($db_connection, $_GET['rank']) . "', "; }
if (isset($_GET['company_name'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['company_name']) . "', "; }
if (isset($_GET['industries'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['industries']) . "', "; }
if (isset($_GET['revenue'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['revenue']) . "', "; }
if (isset($_GET['fiscal_year'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['fiscal_year']) . "', "; }
if (isset($_GET['employees'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['employees']) . "', "; }
if (isset($_GET['market_cap'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['market_cap']) . "', "; }
if (isset($_GET['headquarters'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['headquarters']) . "');"; }
$query = pg_query($db_connection, $query);
The message I gets from the system is: "Add request failed: parsererror"
The Edit and remove functions are working well.
I follow to build this clause from the PGSQL site example:
INSERT INTO films VALUES
('UA502', 'Bananas', 105, '1971-07-13', 'Comedy', '82 minutes');
Any what I`m doing wrong? Thanks!
UPDATE
The echo of the query and the error was the id column. In Mysql code there was no problem with the ID colum. Why when i use pgsql it does?:
INSERT INTO it_companies (rank,company_name,industries,revenue,fiscal_year,employees,market_cap,headquarters)
VALUES ('1', 'asd', 'asd', '1', '2000', '2', '3', 'asdf');
Warning: pg_query(): Query failed: ERROR: duplicate key value violates unique constraint "it_companies_pkey" DETAIL: Key (company_id)=(2) already exists. in C:\WEB\Apache24\htdocs\datatableeditor\data.php on line 121
{"result":"error","message":"query error"
,"data":[]}
UPDATE2
The working code with one bug:
$query = "INSERT INTO it_companies (rank,company_name,industries,revenue,fiscal_year,employees,market_cap,headquarters) VALUES ";
if (isset($_GET['rank'])) { $query .= "('" . $_GET['rank'] . "', "; }
if (isset($_GET['company_name'])) { $query .= "'" . $_GET['company_name'] . "', "; }
if (isset($_GET['industries'])) { $query .= "'" . $_GET['industries'] . "', "; }
if (isset($_GET['revenue'])) { $query .= "'" . $_GET['revenue'] . "', "; }
if (isset($_GET['fiscal_year'])) { $query .= "'" . $_GET['fiscal_year'] . "', "; }
if (isset($_GET['employees'])) { $query .= "'" . $_GET['employees'] . "', "; }
if (isset($_GET['market_cap'])) { $query .= "'" . $_GET['market_cap'] . "', "; }
if (isset($_GET['headquarters'])) { $query .= "'" . $_GET['headquarters'] . "') RETURNING company_id;"; }
echo $query;
After this query, the message "Add request failed: parsererror" is still there. But after a manual refresh of the page, the new data is saved. Any idea why this message apears and not loading the data automatically?
UPDATE 3 - Success
I forgot to remove echo $query; from the code causing the error message.
All works now. Thanks for the help to all! :)
You need a little more work in your query string building.
You only add the open parenthesis ( if rank is present
You only add the closing parenthesis ) if headquarters is present.
Also you need specify what field column get which value, otherwise you end with headquarter name into the fiscal_year field. If columns are not specified the values are add it on the same order as define on the table.
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
And as other have comment check the $query to see what you have.
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);
}
}
}
$queryb = "SELECT product, imei, country, warranty, config from PRODUCT WHERE product_slno = '$mnserialno' ";
$resultb = mysql_query($queryb, $gndbconn) ;
if(mysql_num_rows($resultb) > 0)
{
$queryc = "UPDATE PRODUCT SET product='$desc', product_slno='$mnserialno',imei='$imei',country='$country',warranty='$warranty',config='$config' WHERE product_slno = '.$mnserialno.' ";
$resutc = mysql_query($queryc, $gndbconn) ;
}
else{
$querya = "INSERT INTO PRODUCT SET product='$desc', product_slno='$mnserialno',imei='$imei',country='$country',warranty='$warranty',config='$config'";
$resulta = mysql_query($querya, $gndbconn) ;
}
I want to check the serial number if that serial number already exist in database so records get update, otherwise it get insert into the database.
but the code inserting the records only, no updation, what is the fault i am not getting,
how to prevent the duplicate entry?
INSERT INTO PRODUCT SET
(`product`, `product_slno`, `imei`, `country`, `warranty`, `config`)
VALUES
('" . $desc . "', '" . $mnserialno . "', '" . $imei . "', '" . $country . "', '" . $warranty . "', '" . $config . "')
ON DUPLICATE KEY UPDATE
product='" . $desc . "',
product_slno='" . $mnserialno . "',
imei='" . $imei . "',
country='" . $country . "',
warranty='" . $warranty . "',
config='" . $config . "'";
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.