I need to generate a mysql insert query with this array , where the column name are the field_name & values are field_values. i tried using implode, here its nested array & troubling me lot.
Array
(
[0] => Array
(
[field_name] => Date
[field_value] => 01/02/2013
)
[1] => Array
(
[field_name] => Time
[field_value] => 03:20 PM
)
[2] => Array
(
[field_name] => submitted_lat
[field_value] => 13.06114
)
[3] => Array
(
[field_name] => submitted_long
[field_value] => 80.2371547
)
[4] => Array
(
[field_name] => submitted_on
[field_value] => 2013-02-01 15:20:10
)
[5] => Array
(
[field_name] => submitted_by
[field_value] => superadmin#gmail.com
)
[6] => Array
(
[field_name] => pdf
[field_value] =>
)
)
Try this
$sql = "INSERT INTO `table_name` SET ";
$sql_fields='';
foreach($array_name as $k=>$v){
$sql_fields .= "`".$v['field_name']."`='".$v['field_value']."', ";
}
$sql_fields = substr($sql_fields,0,-2);
$sql .= $sql_fields;
echo $sql;
A very simple approch would be this :
$query = 'insert into table ';
foreach($inputs as $input) {
$query .= ' '.$input['field_name'].' = '.$input['field_value'];
}
echo $query;
$fields=array();
$values=array();
for($i=0;$i<count($array);$i++)
{
$fields[]=$array[$i]['field_name'];
$values[]=$array[$i]['field_value'];
}
if(count($array) > 0)
{
$query="Insert into tablename (".implode(",", $fields).") values (".implode(",", $values).")";
mysql_query($query);
}
You need to ensure that your values are correct and protected to avoid SQL Injection. Building dynamically your own SQL query and inserting directly in your database is not safe.
Anyway you can use array_map() to do something like this:
$arr = array(array("name" => "column1", "value" => "value1"),
array("name" => "column2", "value" => "value2"),
array("name" => "column3", "value" => "value3"));
$columns = array_map(function($item) { return $item['name'];}, $arr);
$values = array_map(function($item) { return "'". $item['value'] . "'";}, $arr);
$columnsList = implode(',', $columns);
$valuesList = implode(',', $values);
$sql = "INSERT INTO mytable($columnsList) VALUES ($valuesList)";
EDIT: As said in introduction this would not be safe and it would be better to use MySQLi or PDO. But you would also need to know the type of the column you want to insert into.
Related
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 .")";
I have this array:
Array (
[0] => Array
(
[0] => 2
)
[1] => Array
(
[0] => 2015-07-20
)
[2] => Array
(
[0] => 2
[1] => 5
)
[3] => Array
(
[0] => 70
[1] => 17
)
[4] => Array
(
[0] => 4
[1] =>
)
[5] => Array
(
[0] => 66
[1] => 17
)
)
Now I want Update to database like this
Array
(
[0] => Array
(
[0] => 2
[1] => 2015-07-20
[2] => 2
[3] => 70
[4] => 4
[5] => 66
)
[1] => Array
(
[0] => 2
[1] => 2015-07-20
[2] => 5
[3] => 17
[4] =>
[5] => 17
)
)
Is it possible? Or qny other way to UPdate record from array?
I have foreach loop OUTPUT like this:-
UPDATE update_shopwise_stock SET shop_id =2 datetime =2015-07-20 item_id =2 item_id =5 before_sale_totitem_qty =70 before_sale_totitem_qty =17 after_sale_totitem_qty =4 after_sale_totitem_qty = restOfItem =66 restOfItem =17 note =NULL WHERE shop_id =2
But I Want to this:-
UPDATE update_shopwise_stock SET shop_id =2 datetime =2015-07-20 item_id =2 before_sale_totitem_qty =70 after_sale_totitem_qty =4 restOfItem =66 note =NULL WHERE shop_id =2
UPDATE update_shopwise_stock SET shop_id =2 datetime =2015-07-20 item_id =5 before_sale_totitem_qty =17 after_sale_totitem_qty = restOfItem =17 note =NULL WHERE shop_id =2
Any help?
If i understand your question you need transform data from first array to second array and after you can make this foreach?
If yes there is transform to array with default values from 0 index. Works for multiple versions so you can add index 3,5, etc. and it will works still.
$default = array();
$versions = array();
foreach($array as $key => $values){
foreach($values as $version => $value){
if($version === 0){
$default[$key] = $value;
continue;
}
if(!array_key_exists($version, $versions)){
}
$versions[$version][$key] = $value;
}
}
$return = array(
0 => $default,
);
foreach($versions as $version => $versionData){
$return[$version] = $versionData+$default;
}
If you need foreach to build your SQL query it is here to:
$columns = array(
'shop_id', 'datetime', 'item_id', 'before_sale_totitem_qty', 'after_sale_totitem_qty', 'restOfItem'
);
foreach($return as $version => $data){
$columnData = array();
foreach($data as $columnIndex => $value){
$columnData[] = sprintf('%s = %s', $columns[$columnIndex], $value);
}
$sql = sprintf('UPDATE update_shopwise_stock SET %s WHERE shop_id=%d', implode(', ', $columnData), $data[0]);
}
But my personal recommendation is not use sql like this, but use PDO for prepare statement and better security. For prepare statement is for loop here:
$columns = array(
'shop_id', 'datetime', 'item_id', 'before_sale_totitem_qty', 'after_sale_totitem_qty', 'restOfItem'
);
foreach($return as $version => $data){
$columnPrepare = array();
$columnData = array();
foreach($data as $columnIndex => $value){
$columnName = $columns[$columnIndex];
$columnPrepare[] = sprintf('%s = :%s', $columnName, $columnName);
$columnData[$columnName] = $value;
}
$query = $db->prepare(sprintf("UPDATE update_shopwise_stock SET %s WHERE shop_id=:shop_id", implode(', ', $columnPrepare)));
foreach($columnData as $column => $value){
$query->bindParam(sprintf(':%s', $column), $value);
}
$query->execute();
}
Everything is untested and can have some bugs, eventually performance issue. It is based on question issue and show only way how to solve this issue.
i just cant get the right approach to this problem, i have two arrays .
first array $attendance which has the following keys and values
Array
(
[attendance] => Array
(
[1] => 1
[2] => 1
[3] => 0
[4] => 1
[5] => 1
[6] => 0
[7] => 0
)
This is coming from a checkbox if checked value is 1 else value is 0
The second array is $remark
[remark] => Array
(
[1] =>
[2] =>
[3] => 'sick'
[4] =>
[5] =>
[6] => 'leave'
[7] => 'On assignment'
)
Now this is what the key 1- 7 stands for, the script is for employee's attendance the key 1-7 is the employeeID in the employee table in my database.
Now what i want to achieve is concatenate the array in such a way to look like this
Array
(
[0] => Array
(
[employeeID] => 7
[attendance] => 0
[remark] => 'On assignment'
)
[1] => Array
(
[employeeID] => 6
[attendance] => 0
[remark] => 'leave'
)
[2] => Array
(
[employeeID] => 5
[attendance] => 1
[remark] =>
)
//and so on
)
I am using Codeigniter If i am able to concatenate it i will also love to know how i will insert the multiple data into the employee table which looks like this,
employee's table
employeeID | date | status | remarks
the date i planned using CURDATE() then status will hold either 0 or 1 from attendance
Again: the keys from 1- 7 both on the remark and attendance's array is the employeeID
update!!
this is what i tried but did not work.
$att = $_POST['attendance'];
$remarks = $_POST['remark'];
foreach($att as $employee_id=>$status)
{
$x=0;
$employee[$x]['employee_id']=$employee_id;
$employee[$x]['status']=$status;
foreach($remarks as $employee_id=>$remark)
{
$employee[$x]['remark']=$remark;
$x++;
}
}
$attendance = $_POST['attendance'];
$remarks = $_POST['remark'];
$collect = array();
foreach ($attendance as $employeeID => $attending) {
$collect[] = array(
"employeeID" => $employeeID,
"attendance" => $attending,
"remark" => isset($remarks[$employeeID]) ? $remarks[$employeeID] : ""
);
}
$values = array();
foreach ($collect as $entry) {
$values[] = "(" . ((int) $entry["employeeID"]) . ",
CURDATE(),
" . ((int) $entry["attendance"]) . ",
'" . sql_escape($entry["remark"]) . "'
)";
}
$query = "INSERT INTO `attendance`
(`employeeID`, `date`, `status`, `remarks`)
VALUES
(" . implode(",", $values) . ")";
Make sure you replace sql_escape by the appropriate escape function. If you're using PDO use that.
Easy enough, to be honest...
$numOfEmployees = 8;
$concatArray = array();
foreach($attendance as $k => $v)
{
$concatArray[] = array("employeeID" => $k, "attendance" => $v, "remark" => $remark[$k];
}
If your attendance table is in anything like SQL, you could go about it with foreach on the above mentioned concatArray:
foreach($concatArray as $key => $value)
{
$remark = $value['remark'];
// sanitize remark for database
$query = "INSERT INTO employees (ID, Date, Status, Remarks) VALUES ({$value['employeeID']}, NOW(), {$value['attendance']}, '{$value['remark']}');";
// perform the actual query
}
Keep in mind that this is a very general example, making a lot of assumptions about the database.
As Frits notes, the remark field should be sanitized, perhaps by using mysqli_real_escape_string for MySQLi or quote for PDO - depends on what you are using.
Array
(
[pid] => Array
(
[0] => 2
[1] => 3
)
[price] => Array
(
[0] => 20
[1] => 20
)
[qty] => Array
(
[0] => 2
[1] => 1
)
)
i have an outcome of the above array from some processing. with this i need to update to database like below table
pid price qty
2 20 2
3 20 1
$i = 0;
while( $i < count( $YourArray['pid']) ) {
$query = "INSERT INTO `tableName`(`pid`, `price`, `qty`) VALUES( ?, ?, ? )";
$stmt = $con->prepare( $query );
$stmt->execute(
array(
$YourArray['pid'][$i],
$YourArray['price'][$i],
$YourArray['qty'][$i]
)
);
$i++;
}
Where, I used the pdo method of insertion.
for(i=0;i<amount;i++){
echo $array['pid'][i];
echo $array['price'][i];
echo $array['qty'][i];
}
Where amount must be a count of the amount of rows you have
Try this :
$array = array("pid" => array(2,3),"price" => array(20,20),"qty" => array(2,1));
array_unshift($array, null);
$res = call_user_func_array('array_map', $array);
echo "<pre>";
print_r($res);
Output :
Array
(
[0] => Array
(
[0] => 2
[1] => 20
[2] => 2
)
[1] => Array
(
[0] => 3
[1] => 20
[2] => 1
)
)
loop this array and add to DB - So that you can add two entries in DB
this is a wrong way of doing it, i would use an indexed array, and then build a foreach loop that will handle each 1 separately, something like:
$values = array();
$values[] = array(
'pid' => 2,
'price' => 20,
'qty' => 2
);
$values[] = array(
'pid' => 3,
'price' => 20,
'qty' => 1
);
and from this then build a foreach loop and run each query there
foreach ($values as $value) {
$query = "insert into blah
set pid = " . $value['pid'] . ",
price = " . $value['price'] . ",
qty = " . $value['qty'] . ";";
mysql_query($query);
}
I have an array $product_array, and when I use print_r($product_array);. The array shows like this
Array
(
[0] => Array
(
[ID] => P00100
[NAME] => Edina
[PRICE] => $20.00
)
[1] => Array
(
[ID] => P00101
[NAME] => Richfield
[PRICE] => $21.00
)
[2] => Array
(
[ID] => P00102
[NAME] => Bloomington
[PRICE] => $22.00
)
)
I set my database table in 4 columes, first one is mainid, and which is auto increment, following with ID, NAME, PRICE, as the keys showed above.
I would like to insert this array $product_array into mysql.
Can anyone help? Would be very much appreciated!
tks.
$sql = array();
foreach( $myarray as $row ) {
$sql[] = '('.$row['ID'].', "'.mysql_real_escape_string($row['NAME']).'",
"'.$row['PRICE'].'")';
}
mysql_query('INSERT INTO table (ID, NAME,PRICE) VALUES '.implode(',', $sql));
see more details :
insert multiple rows via a php array into mysql
You can try this code (quick 'n' dirty):
foreach($product_array as $v) {
$query = 'insert into tablename values (null, \'' . $v['id'] . '\', \'' . $v['name'] . '\', ' . $v['price'] . ');'
mysql_query($query);
}