PDO duplicate values in array - php

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

Related

Insert Data to mysql database from Associative array in 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();
}

sum arrays while sql->fetch()

My code looks like this:
$sql = $pdo->prepare('SELECT source_clicks,source_impr,source_spend FROM `statistic` WHERE camp_id =? AND date BETWEEN ? AND ?');
$sql->bindColumn('source_clicks',$source_clicks);
$sql->bindColumn('source_impr',$source_impr);
$sql->bindColumn('source_spend',$source_spend);
$sql->execute([$_POST['get_source_stat'],$date[0],$date[1]]);
while ( $sql->fetch()) {
$data = explode(',',$source_clicks);
print_r($data);
}
the output i get is:
Array ( [0] => 30 [1] => 30 [2] => 51 [3] => 108 ) Array ( [0] => 30 [1] => 30 [2] => 51 [3] => 228 )
i need to sum this arrays saving their keys and get something like this:
array ([0] => 60 [1] => 60 [2] => 102 [3] => 336)
Can you tell me how can i do it?
One way to do this would be to push each exploded $source_clicks value into an array, and then use array_sum and array_column to get the results e.g.
$data = array();
while ($sql->fetch()) {
$data[] = explode(',',$source_clicks);
}
$sums = array();
foreach (array_keys($data[0]) as $column) {
$sums[$column] = array_sum(array_column($data, $column));
}
print_r($sums);

Not able to Print MultiDimensional array in PHP

I am trying to fetch one array from an Oracle database and another from a MySQL database.
But the arrays I get back are in different formats, and I am not able to display them in an HTML table.
$result = $instance->prepare("SELECT * from dd ");
$result->execute();
while ($row = $result->fetchAll(PDO::FETCH_ASSOC))
{
$rows2 = $row;
}
$array = oci_parse($conn, "SELECT * FROM DD");
oci_execute($array);
while($row=oci_fetch_array($array, OCI_ASSOC))
{
$rows1 =$row;
}
print_r($rows1);
print_r($rows2);
$output = array_merge($rows1,$rows2);
print_r($output);
Here $instance and $conn are the respective connection variables.
The outputs I get after printing the two arrays are:
Array from Oracle:
Array ( [CLIENTID] => 2 [CLIENTNAME] => dsd [PHONENO] => 53556535 [ADDRESS] => Mumbai [ROUTE] => 4323 )
Array from MySQL:
Array ( [0] => Array ( [ClientId] => 3 [ClientName] => PQR [PhoneNo] => 786483744 [Address] => Pune [Route] => 3329 ) )
And after merging I get this array:
Array ( [CLIENTID] => 2 [CLIENTNAME] => dsd [PHONENO] => 53556535 [ADDRESS] => Mumbai [ROUTE] => 4323 [0] => Array ( [ClientId] => 3 [ClientName] => PQR [PhoneNo] => 786483744 [Address] => Pune [Route] => 3329 ) )
How do I print this in a table in HTML format?
You can not just merge two arrays in this case.try code below;
$all = array();
$all[] = $rows1;
foreach($rows2 as $k2=>$v2) {
$new=array();
$new['CLIENTID'] = $v2['ClientId'];
$new['CLIENTNAME'] = $v2['ClientName'];
$new['PHONENO'] = $v2['PhoneNo'];
$new['ADDRESS'] = $v2['Address'];
$new['ROUTE'] = $v2['Route'];
$all[]=$new;
}
$str='<table><tr><th>CLIENTID</th><th>CLIENTNAME</th><th>PHONENO</th><th>ADDRESS</th><th>ROUTE</th></tr>';
foreach($all as $arr) {
$str.='<tr><td>'.$arr['CLIENTID'].'</td><td>'.$arr['CLIENTNAME'].'</td><td>'.$arr['PHONENO'].'</td><td>'.$arr['ADDRESS'].'</td><td>'.$arr['ROUTE'].'</td>';
}
$str.='</table>';
echo $str;
If $rows1 is an array-array like $rows2, you should iterate same loop for $rows1 also

two dimensional array to Update into mysql database

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.

How can I create multidimensional arrays from a string in PHP?

So My problem is:
I want to create nested array from string as reference.
My String is "res[0]['links'][0]"
So I want to create array $res['0']['links']['0']
I tried:
$result = "res[0]['links'][0]";
$$result = array("id"=>'1',"class"=>'3');
$result = "res[0]['links'][1]";
$$result = array("id"=>'3',"class"=>'9');
when print_r($res)
I see:
<b>Notice</b>: Undefined variable: res in <b>/home/fanbase/domains/fanbase.sportbase.pl/public_html/index.php</b> on line <b>45</b>
I need to see:
Array
(
[0] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 1
[class] => 3
)
)
)
[1] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 3
[class] => 9
)
)
)
)
Thanks for any help.
So you have a description of an array structure, and something to fill it with. That's doable with something like:
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
// unoptimized, always uses strings
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
array_create( $res, "[0]['links'][0]", array("id"=>'1',"class"=>'3') );
array_create( $res, "[0]['links'][1]", array("id"=>'3',"class"=>'9') );
Note how the array name itself is not part of the structure descriptor. But you could theoretically keep it. Instead call the array_create() function with a $tmp variable, and afterwards extract() it to achieve the desired effect:
array_create($tmp, "res[0][links][0]", array(1,2,3,4,5));
extract($tmp);
Another lazy solution would be to use str_parse after a loop combining the array description with the data array as URL-encoded string.
I have a very stupid way for this, you can try this :-)
Suppose your string is "res[0]['links'][0]" first append $ in this and then put in eval command and it will really rock you. Follow the following example
$tmp = '$'.'res[0]['links'][0]'.'= array()';
eval($tmp);
Now you can use your array $res
100% work around and :-)
`
$res = array();
$res[0]['links'][0] = array("id"=>'1',"class"=>'3');
$res[0]['links'][0] = array("id"=>'3',"class"=>'9');
print_r($res);
but read the comments first and learn about arrays first.
In addition to mario's answer, I used another function from php.net comments, together, to make input array (output from jquery form serializeArray) like this:
[2] => Array
(
[name] => apple[color]
[value] => red
)
[3] => Array
(
[name] => appleSeeds[27][genome]
[value] => 201
)
[4] => Array
(
[name] => appleSeeds[27][age]
[value] => 2 weeks
)
[5] => Array
(
[name] => apple[age]
[value] => 3 weeks
)
[6] => Array
(
[name] => appleSeeds[29][genome]
[value] => 103
)
[7] => Array
(
[name] => appleSeeds[29][age]
[value] => 2.2 weeks
)
into
Array
(
[apple] => Array
(
[color] => red
[age] => 3 weeks
)
[appleSeeds] => Array
(
[27] => Array
(
[genome] => 201
[age] => 2 weeks
)
[29] => Array
(
[genome] => 103
[age] => 2.2 weeks
)
)
)
This allowed to maintain numeric keys, without incremental appending of array_merge. So, I used sequence like this:
function MergeArrays($Arr1, $Arr2) {
foreach($Arr2 as $key => $Value) {
if(array_key_exists($key, $Arr1) && is_array($Value)) {
$Arr1[$key] = MergeArrays($Arr1[$key], $Arr2[$key]);
}
else { $Arr1[$key] = $Value; }
}
return $Arr1;
}
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
$input = $_POST['formData'];
$result = array();
foreach ($input as $k => $v) {
$sub = array();
array_create($sub, $v['name'], $v['value']);
$result = MergeArrays($result, $sub);
}

Categories