Insert Data to mysql database from Associative array in PHP - php

I have the following Associative array
Array (
[0] => Array
(
[0] => Liane Lanford
[1] => Ken Christenson
[2] => Melissa Jaramillo
)
[1] => Array
(
[0] => $310.40
[1] => $134.75
[2] => $951.78
)
[2] => Array
(
[0] => $0.00
[1] => $0.00
[2] => $0.00
)
[3] => Array
(
[0] => $325.92
[1] => $141.49
[2] => $999.37
)
)
There are 3 customers in the array. The number may be 4,5 or more. I want to insert the data from the array to the database like following table
How can i write the foreach loop. I tried the following but not working
foreach ($array as $payment_type => $payment) {
foreach ($array[payment_type] as $pay => $value) {
mysqli_query($link, "INSERT INTO table(name,subtotal,holdback,total) VALUES ('$pay[0]','$pay[1]','$pay[2]','$pay[3]') ");
}
}

All you need to do is loop the array and then use the index to access all the other values sub array values. I also used the correct prepare and bind mechanism to avoid SQL Injection
$stmt = $link->prepare("INSERT INTO table (name,subtotal,holdback,total) VALUES (?,?,?,?)");
foreach ($array[0] as $idx => $payment) {
$stmt->bind_param('sdsd', $payment,
$array[1][$idx],
$array[2][$idx],
$array[3][$idx]
);
$stmt->execute();
}

Some code to start with, using prepared statements to prevent SQL-injections:
$stmt = $link->prepare('INSERT INTO table(name,subtotal,holdback,total) VALUES (?, ?, ?, ?)');
foreach ($array[0] as $key => $value) {
$stmt->bind_param('ssss', $value, $array[1][$key], $array[2][$key], $array[3][$key]);
$stmt->execute();
}

Related

PDO duplicate values in array

I need to get some currency ids from db, this is my code
$arr = [];
$currency_codes = array("USD", "RUB");
$currency_codes_in = implode(',', array_fill(0, count($currency_codes), '?'));
$query = "SELECT `curr_id` FROM `dictionary_currency` WHERE `curr_code` IN (". $currency_codes_in .")";
$stmt = $db->prepare($query);
foreach ($currency_codes as $k => $id) {
$stmt->bindValue(($k+1), $id);
}
$stmt->execute();
$currencies = $stmt->fetchAll();
foreach($currencies as $currency)
{
foreach($currency as $key => $value)
{
$arr[] = $value;
}
}
print_r($arr);
exit();
this is $currencies array
Array
(
[0] => Array
(
[curr_id] => 643
[0] => 643
[curr_code] => RUB
[1] => RUB
)
[1] => Array
(
[curr_id] => 840
[0] => 840
[curr_code] => USD
[1] => USD
)
)
and this is $arr
Array
(
[0] => 643
[1] => 643
[2] => 840
[3] => 840
)
I don't understand why I get duplicate values in arrays and how to prevent it?
PDO is a database wrapper that can do many things for you. For example,
bind input values right in execute()
get you returned data already in the desired format
So in fact you need two times less code than you have now:
$currency_codes = array("USD", "RUB");
$currency_codes_in = implode(',', array_fill(0, count($currency_codes), '?'));
$query = "SELECT `curr_id` FROM `dictionary_currency` WHERE `curr_code` IN ($currency_codes_in)";
$stmt = $db->prepare($query);
$stmt->execute($currency_codes);
$arr = $stmt->fetchAll(PDO::FETCH_COLUMN);
or I would rather propose to make it like
$query = "SELECT curr_code, curr_id FROM dictionary_currency WHERE `curr_code` IN ($currency_codes_in)";
$stmt = $db->prepare($query);
$stmt->execute($currency_codes);
$arr = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
The loop is problematic:
foreach($currencies as $currency) {
foreach($currency as $key => $value) {
$arr[] = $value;
}
}
Just use a simple
foreach($currencies as $currency) {
$arr[] = $currency[0];
}
Edit #1:
Using your $currencies and old query, I got the following:
Array
(
[0] => Array
(
[curr_id] => 643
[0] => 643
[curr_code] => RUB
[1] => RUB
)
[1] => Array
(
[curr_id] => 840
[0] => 840
[curr_code] => USD
[1] => USD
)
)
Array
(
[0] => 643
[1] => 643
[2] => RUB
[3] => RUB
[4] => 840
[5] => 840
[6] => USD
[7] => USD
)
I know this question is getting old. But here is the solution to prevent the duplicate values from PDO.
Just using this:
$stmt->fetchAll(PDO::FETCH_ASSOC);
Instead of this:
$stmt->fetchAll();
use following query
$query = "SELECT DISTINCT curr_id FROM dictionary_currency WHERE curr_code IN (". $currency_codes_in .")";

multiple form insert query mysql

is there anyone know how to format this array in a loop so that it will insert in a database in a single query but in a loop way using php.
I'm making a multiple form by the way.
here's the array format of the field and this is my form looks like attendance
Array
(
[sup_payroll_type] => Array
(
[0] => 1
[1] => 2
[2] => 1
)
[sup_month] => Array
(
[0] => January
[1] => January
[2] => May
)
[sup_year] => Array
(
[0] => 2015
[1] => 2015
[2] => 2015
)
[sup_late_days] => Array
(
[0] => 1
[1] => 1
[2] => 2
)
[sup_absent_days] => Array
(
[0] => 2
[1] => 1
[2] => 0
)
[sup_id] => Array
(
[0] => 1
[1] => 5
[2] => 6
)
[sup_emp_id] => Array
(
[0] => 24
[1] => 24
[2] => 24
)
[save_edit_satt] => Array
(
[0] => SAVE
)
)
any help would be appreciated.
Please try below loop:-
$insertQuery = 'INSERT INTO attendence (sup_payroll_type, sup_month, sup_year,
sup_late_days, sup_absent_days, sup_id, sup_emp_id,
save_edit_satt) VALUES';
foreach($attendenceArray AS $key => $value){
$insertQuery .= '("'.$value['sup_payroll_type'].'","'.$value['sup_month'].'",
"'.$value['sup_year'].'","'.$value['sup_late_days'].'",
"'.$value['sup_absent_days'].'","'.$value['sup_id'].'",
"'.$value['sup_emp_id'].'","'.$value['save_edit_satt'].'"),';
}
$insertQuery = rtrim($insertQuery,',');
$insertQuery contains ur insert query.
$attendenceArray contains ur example array.
If ur using mysqli then used mysqli_query($mysqli,$insertQuery) to execute ur query. $mysqli is connection object.
You can do with using a loop only
$insertQuery = 'INSERT INTO attendence (sup_payroll_type, sup_month, sup_year,
sup_late_days, sup_absent_days, sup_id, sup_emp_id,
save_edit_satt) VALUES';
foreach($attendenceArray['sup_payroll_type'] AS $key => $value){
$insertQuery .= '("'.$value.'","'.$attendenceArray['sup_month'][$key].'",
"'.$attendenceArray['sup_year'][$key].'","'.$attendenceArray['sup_late_days'][$key].'",
"'.$attendenceArray['sup_absent_days'][$key].'","'.$attendenceArray['sup_id'][$key].'",
"'.$attendenceArray['sup_emp_id'][$key].'","'.$attendenceArray['save_edit_satt'][$key].'"),';
}
echo $insertQuery; // Query for insert
i figured it out.
$ctr = 0;
foreach($_POST['sup_payroll_type'] as $row){
$upd_value = array();
$upd_value['sup_payroll_type'] = $_POST['sup_payroll_type'][$ctr];
$upd_value['sup_month'] = $_POST['sup_month'][$ctr];
$upd_value['sup_year'] = $_POST['sup_year'][$ctr];
$upd_value['sup_late_days'] = $_POST['sup_late_days'][$ctr];
$upd_value['sup_absent_days'] = $_POST['sup_absent_days'][$ctr];
$upd_value['sup_emp_id'] = $_POST['sup_emp_id'][$ctr];
$upd_result = $db_conn->mysql_update($upd_value,'tbl_attendance_support','sup_id='.$_POST['sup_id'][$ctr],'db_norkis');
$ctr++;
}
BTW thanks Pankaj K and Shijin for sharing your idea =)

how to insert array values in the database that are called in the class as an object in php

i need to store the array value that are called in the class as an object in the database.
coding
<?php
echo "BEST SELECTED POPULATION";
debug(GA::select($ga->population,'total',3)); //The best
$asma[]=GA::select($ga->population,'total',3); //The best
}
print_r($asma);
?>
$array1 is the array in which i get the output value,this array is dynamic that is the number of values increases in it depend on the user input.
<?php
include('config.php');
//database connection
//query
$new_array = array($asma);
foreach($new_array as $key => $value) {
foreach ( $value as $ind => $data ) {
/*
You now have access to field values like this
$data['Voltage']
$data['Number']
$data['Duration']
*/
// query makes no sense 3 fields mentioned and 4 parameters given???
// you will have to decide which of the fields from $data[] you want to load
// to which fields in the database.
$sql = "INSERT INTO ga (gaid,fe,fe1,timestamp) VALUES ('', '$key', '$value', '".date("Y-m-d H:i:s")."')";
$stmt = mysql_query($sql) or die(mysql_error());
} // endforeach
} // endforeach
?>
if i used above code for insertion it display no error but it enter value in table ga like this
gaid fe fe1 timestamp
1 0 array -
the above code which i used for inserting in my table ga
the output of print_r($asma);
Array (
[0] => Array (
[0] => H Object (
[Voltage] => 12
[Number] => 1
[Duration] => 3
)
[1] => H Object (
[Voltage] => 26
[Number] => 4
[Duration] => 8
)
[2] => H Object (
[Voltage] => 26
[Number] => 4
[Duration] => 8
)
)
[1] => Array (
[0] => H Object (
[Voltage] => 18
[Number] => 1
[Duration] => 4
)
[1] => H Object (
[Voltage] => 38
[Number] => 4
[Duration] => 10
)
[2] => H Object (
[Voltage] => 36
[Number] => 2
[Duration] => 8
)
)
)
i need to store all values in the database in above output 6 values.
this is table ga
gaid fe fe1 fe2 timestamep
It does not help that you keep talking about array1 in your description but I dont see anything called array1 in your code.
But making the assumption that array1 = $new_array here is a suggestion.
<?php
include('config.php');
//database connection
//query
/*
* This achieves nothing other than adding an extra level of array
* Try removing it
*/
//$new_array = array_combine($asma,$asma);
foreach($asma as $key => $value) {
foreach ( $value as $ind => $hObject ) {
$q = "INSERT INTO ga (fe, fe1, f2, timestamp ) VALUES (%d, %d, %d, '%s' );
$qs = sprintf( $q, $hObject->Voltage,$hObject->Duration,
$hObject->Number, date("Y-m-d H:i:s") );
$result = mysql_query($qs);
if ( ! $result ) {
die( 'Insert failed ' . mysql_errno() . ' ' . mysql_error() );
}
} // endforeach
} // endforeach
?>

array_splice removing more than one item

I have the following method:
public function selectFinal(){
$db = new Database();
for($i = 0; $i < 5; $i++){
$key_id = mt_rand(0, count($this->candidates) - 1);
$itm = $this->candidates[$key_id];
$host = $itm["host"];
$item = $itm["item"];
$db->query("insert ignore into trends (trend_id, host, item) values (?, ?, ?)", array($this->nextId, $host, $item));
array_splice($this->candidates, $key_id, -1);
print_r($this->candidates);
$this->nextId++;
}
}
For the print_r() I am getting this output:
Array
(
[0] => Array
(
[host] => www.youtube.com
[item] => IytNBm8WA1c
)
[1] => Array
(
[host] => www.youtube.com
[item] => kffacxfA7G4
)
[2] => Array
(
[host] => www.youtube.com
[item] => kXYiU_JCYtU
)
[3] => Array
(
[host] => www.youtube.com
[item] => 7AVHXe-ol-s
)
[4] => Array
(
[host] => www.youtube.com
[item] => qkM6RJf15cg
)
)
Array
(
[0] => Array
(
[host] => www.youtube.com
[item] => IytNBm8WA1c
)
[1] => Array
(
[host] => www.youtube.com
[item] => qkM6RJf15cg
)
)
Array
(
[0] => Array
(
[host] => www.youtube.com
[item] => qkM6RJf15cg
)
)
Array
(
[0] => Array
(
[host] => www.youtube.com
[item] => qkM6RJf15cg
)
)
Array
(
[0] => Array
(
[host] => www.youtube.com
[item] => qkM6RJf15cg
)
)
The array will start with 5 or more items in it. What I would like to do is select a random item from the array and insert it into the database then remove it from the array. I want to do this 5 times to get 5 random items from the array. But for some reason it is selecting 1 then removing 3 items from the array, and I am not sure why (shown in the second section of code).
Edit: Final Working Result
public function selectFinal(){
$db = new Database();
for($i = 0; $i < 5; $i++){
$key_id = mt_rand(0, count($this->candidates) - 1);
$itm = array_values(array_merge([$this->nextId], array_splice($this->candidates, $key_id, 1)[0]));
$db->query("insert ignore into trends (trend_id, host, item) values (?, ?, ?)", $itm);
$this->nextId++;
}
}
You are more safe in splicing the element out and use that outtake. In case you made an error with that, you notice by not having correct values to store. This will make you more aware of a potential problem:
$key_id = mt_rand(0, count($this->candidates) - 1);
$itm = array_splice($this->candidates, $key_id, -1);
var_dump($itm);
See? You then can better pin-point the problem, e.g. -1 is not 1. See http://php.net/array_splice
public function selectFinal() {
$db = $this->db;
for ($i = 0; $i < 5; $i++)
{
$key_id = mt_rand(0, count($this->candidates) - 1);
$values = array_merge(
[$this->nextId], array_splice($this->candidates, $key_id, 1)
###
);
print_r($this->candidates);
$db->query(
"insert ignore into trends (trend_id, host, item) values (?, ?, ?)",
array_values($values)
);
$this->nextId++;
}
}
If you just want delete a array item of a specific key you can use -
unset($this->candidates[$key_id])

Looping through array of array/objects

I have something similar to the following structure:
Array
(
[wp_postmeta] => Array
(
[0] => stdClass Object
(
[meta_id] => 1
[post_id] => 2
[meta_key] => _wp_page_template
[meta_value] => default
)
)
[wp_comments] => Array
(
[0] => stdClass Object
(
[comment_ID] => 1
[comment_post_ID] => 1
[comment_author] => Mr WordPress
[comment_author_email] =>
[comment_author_url] => http://wordpress.org/
[comment_author_IP] =>
[comment_date] => 2011-10-20 03:06:23
[comment_date_gmt] => 2011-10-20 03:06:23
[comment_content] => Hi, this is a comment.
[comment_karma] => 0
[comment_approved] => 1
[comment_agent] =>
[comment_type] =>
[comment_parent] => 0
[user_id] => 0
)
)
)
What I'm trying to do here is iterate over these results so I can use them to form a query.
Assume all the data within the wp_postmeta table is deleted from the database and this array contains the data of that table before it was deleted. I want to take this saved data in the array and reset the table with these old values.
I.e Looping through the array and inserting this as sql: INSERT INTO wp_postmeta (meta_id, post_id, meta_key, meta_value) VALUES (1, 2, '_wp_page_template', 'default')
foreach ($outerArray as $tableName => $tableData) { // Loop outer array
foreach ($tableData as $row) { // Loop table rows
$cols = $vals = array();
foreach ($row as $col => $val) { // Loop this row
$cols[] = $col;
$vals[] = $val; // You may need to escape this before using it in a query...
}
// Build the query
$query = "INSERT INTO $tableName (".implode(', ',$cols).") VALUES ('".implode("', '",$vals)."')";
// Do the query here
}
}
You can iterate over object properties just like you can with an array, and in a stdClass everything is public, so the above should work no problem.

Categories