Perl DBI fetchall_hashref - mysql

Consider the following table:
mysql> select * from vCountryStatus;
+-------------+------------+------+---------+--------+-----------------+
| CountryName | CountryISO | Code | Status | Symbol | CurrencyName |
+-------------+------------+------+---------+--------+-----------------+
| Brazil | BR | 55 | LIVE | BRL | Brazilian Real |
| France | FR | 33 | offline | EUR | Euro |
| Philippines | PH | 63 | LIVE | PHP | Philippino Peso |
+-------------+------------+------+---------+--------+-----------------+
3 rows in set (0.00 sec)
I am trying to construct a hash based on this table. For this I do the following:
#!/usr/bin/perl
use DBI;
use Data::Dumper;
my $dbh = DBI->connect("dbi:mysql:database=db", "user", "password", {RaiseError => 1, AutoCommit => 0, FetchHashKeyName => "NAME_lc"}) || die "DB open error: $DBI::errstr";
my $sth = $dbh->prepare("select * from vCountryStatus");
$sth->execute;
my $hash = $sth->fetchall_hashref('countryiso');
print Dumper($hash);
Here is the output this generates:
$VAR1 = {
'PH' => {
'symbol' => 'PHP',
'status' => 'LIVE',
'countryname' => 'Philippines',
'countryiso' => 'PH',
'currencyname' => 'Philippino Peso',
'code' => '63'
},
'BR' => {
'symbol' => 'BRL',
'status' => 'LIVE',
'countryname' => 'Brazil',
'countryiso' => 'BR',
'currencyname' => 'Brazilian Real',
'code' => '55'
},
'FR' => {
'symbol' => 'EUR',
'status' => 'offline',
'countryname' => 'France',
'countryiso' => 'FR',
'currencyname' => 'Euro',
'code' => '33'
}
};
The question is: why is the key of the hash (countryiso) repeated in the values inside the hash?
What I would prefer is the following output:
$VAR1 = {
'PH' => {
'symbol' => 'PHP',
'status' => 'LIVE',
'countryname' => 'Philippines',
'currencyname' => 'Philippino Peso',
'code' => '63'
},
'BR' => {
'symbol' => 'BRL',
'status' => 'LIVE',
'countryname' => 'Brazil',
'currencyname' => 'Brazilian Real',
'code' => '55'
},
'FR' => {
'symbol' => 'EUR',
'status' => 'offline',
'countryname' => 'France',
'currencyname' => 'Euro',
'code' => '33'
}
};
Is it possible using fetchall_hashref DBI method? Or do I have to go the traditional way, looping through each row and constructing the hash on the fly?

No, it cannot be done using fetchall_hashref. But you can iterate over the hash values and delete the key:
delete $_->{countryiso} for values %$hash;

I had this same problem but was using multiple keys on fetchall_hashref, so I had to go deeper in the hash references. Not exactly rocket science, but here it is:
(...)
my #keys=('key1','key2','key3');
my $result_ref=$sth->fetchall_hashref(\#keys);
remove_key_values($result_ref,\#keys);
(...)
sub remove_key_values {
my ($href_values,$aref_keys) = (#_);
foreach my $hk (keys %$href_values) {
foreach my $ak (#$aref_keys) {
if ($ak eq $hk) {
delete $href_values->{$hk};
}
}
if (exists $href_values->{$hk} and ref($href_values->{$hk}) eq 'HASH') {
remove_key_values($href_values->{$hk},$aref_keys);
}
}
}

Related

Kartik-Widget GridView Filter TYPEAHEAD inactive

Following code throws out no error,but it's completely inactive, respectively redundant. JQuery is filtering nothing! Any ideas, how to fix this?
Here is code:
[
'attribute' => 'name',
'label' => 'Land',
'value' => function($model) {
if ($model->name) {
return $model->name;
} else {
return NULL;
}
},
'filterType' => GridView::FILTER_TYPEAHEAD,
'filterWidgetOptions' => [
'pluginOptions' => ['highlight' => true],
//'dataset' => [['local' => array_values(\app\models\Country::find()->orderBy('name')->asArray()->one())]
'dataset' => [['local' => array_values(ArrayHelper::map(\app\models\Country::find()->all(), 'id', 'name'))]
]],
'filterInputOptions' => ['placeholder' => 'JQuery will filter...'],
'format' => 'raw'
],
Here is var_dump of
$ausgabe_ = array(array_values(ArrayHelper::map(\app\models\Country::find()->all(), 'id', 'name')));
E:\xampp\htdocs\Yii-WSL\views\country\index.php:145:
array (size=1)
0 =>
array (size=25)
0 => string 'Arabische Emirate' (length=17)
1 => string 'Algerien' (length=8)
2 => string 'Australia' (length=9)
3 => string 'Belgien' (length=7)
4 => string 'Brasilien' (length=9)
5 => string 'Canada' (length=6)
6 => string 'Schweiz' (length=7)
7 => string 'China' (length=5)
8 => string 'Zypern' (length=6)
9 => string 'Germany' (length=7)
10 => string 'Westsahara' (length=10)
11 => string 'France' (length=6)
12 => string 'United Kingdom' (length=14)
13 => string 'Ungarn' (length=6)
14 => string 'India' (length=5)
15 => string 'Laos' (length=4)
16 => string 'Russia' (length=6)
17 => string 'Sudan' (length=5)
18 => string 'Turkmenistan' (length=12)
19 => string 'Ukraine' (length=7)
20 => string 'Uganda' (length=6)
21 => string 'United States' (length=13)
22 => string 'Vatikanstadt' (length=12)
23 => string 'Vietnam' (length=7)
24 => string 'Südafrika' (length=10)
Any further ideas,how to fix this?
P.S.: If I try like this.....:
'dataset' => [
['local' => array_values([ArrayHelper::map(\app\models\Country::find()->orderBy('name')->asArray()->all(), 'id', 'name ')])],
]
....result of
$ausgabe_ = array(array_values(ArrayHelper::map(Country::find()->orderBy('name')->asArray()->all(), 'id', 'name ')));
var_dump($ausgabe_);
is like this:
E:\xampp\htdocs\Yii-WSL\views\country\index.php:146:
array (size=1)
0 =>
array (size=25)
0 => null
1 => null
2 => null
3 => null
4 => null
5 => null
6 => null
7 => null
8 => null
9 => null
10 => null
11 => null
12 => null
13 => null
14 => null
15 => null
16 => null
17 => null
18 => null
19 => null
20 => null
21 => null
22 => null
23 => null
24 => null
Nothing helps to fix this problem. Further ideas?
Worth to note the array must be with integer type indexes and there cannot be missing numbers (indexes) (for example, 0; 1; 2; 3 is fine but 0; 1; 3; 4 is not because index 2 is missing).
The only valid structure (as example):
array(4) {
[0]=>
string(5) "Alpha"
[1]=>
string(4) "Beta"
[2]=>
string(5) "Gamma"
[3]=>
string(5) "Delta"
}
Your array is not valid:
The first (and only) element is 0 that contains other array. It cannot be like that;
That larger array has mixed indexes (read requirement in the first paragraph);
null values are not accepted.
What might solve your problem is if you use array_values:
'dataset' => [
['local' => array_values([ArrayHelper::map(\app\models\Country::find()->orderBy('name')->asArray()->all(), 'id', 'name ')])],
],

Unable to insert array into database

I am inserting multiple data from multiple forms into database but encounter an error at column photo
Unknown column 'Array' in 'field list'
Controller
if(!empty($_FILES['user_profile_file']['name'])){
$filesCount = count($_FILES['user_profile_file']['name']);
for ($i = 0; $i < $filesCount; $i++) {
$studentImg = '';
$_FILES['userFile']['name'] = $_FILES['user_profile_file']['name'][$i];
$_FILES['userFile']['type'] = $_FILES['user_profile_file']['type'][$i];
$_FILES['userFile']['tmp_name'] = $_FILES['user_profile_file']['tmp_name'][$i];
$_FILES['userFile']['error'] = $_FILES['user_profile_file']['error'][$i];
$_FILES['userFile']['size'] = $_FILES['user_profile_file']['size'][$i];
$config['upload_path'] = FCPATH."uploadfiles/users/student-img";
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 0;
$studentImgNew = uniqueId();
$config['file_name'] = $studentImgNew;
$this->load->library('upload', $config);
if($this->upload->do_upload('userFile')){
$fileData = $this->upload->data();
$studentImg[$i]['photo'] = $fileData['file_name'];
$studentData[] = array(
'name' => $_POST['user_name'][$i],
'nric' => $_POST['user_nric'][$i],
'gender' => $_POST['user_gender'][$i],
'photo' => $studentImg,
'email' => $_POST['user_email'][$i],
'password' => md5($_POST['user_password'][$i]),
'is_active' => '0',
);
}
}
}
$this->User_account_model->create($studentData)
Model
function create($studentData){
foreach ($studentData as $key => $studentDatas) {
$insertStudentData[$key] = array(
'parent_id' => $parent_id,
'email' => $studentDatas['email'],
'password' => $studentDatas['password'],
'name' => $studentDatas['name'],
'nric' => $studentDatas['nric'],
'gender' => $studentDatas['gender'],
'photo' => $studentDatas['photo'],
'is_active' => $studentDatas['is_active'],
);
$this->db->insert('users_student', $insertStudentData[$key]);
}
if($this->db->affected_rows() != 1){
return false;
} else {
return true;
}
}
When I do print_r() I can get the exact data to be inserted into the database.
Array
(
[0] => Array
(
[parent_id] => 11
[email] => testing.mael#gmail.com
[password] => e02cb962ac59075b964b07152d234b70
[name] => testing
[nric] => 123123
[gender] => 0
[photo] => Array
(
[0] => Array
(
[photo] => 5955cac09b8f71.jpg
)
)
[is_active] => 0
)
[1] => Array
(
[parent_id] => 11
[email] => testing.mael#gmail.com
[password] => e13cc542ac59075b9643s5152d234g59
[name] => testing sister
[nric] => 123123
[gender] => 0
[photo] => Array
(
[0] => Array
(
[photo] => 5955cac09b8f72.jpg
)
)
[is_active] => 0
)
)
You are trying to insert an array inside the for insertStudentData[key].
Try This:
$insertStudentData[$key] = array(
'parent_id' => $parent_id,
'email' => $studentDatas['email'],
'password' => $studentDatas['password'],
'name' => $studentDatas['name'],
'nric' => $studentDatas['nric'],
'gender' => $studentDatas['gender'],
'photo' => $studentDatas['photo'],
'is_active' => $studentDatas['is_active']['0']['photo'],
);
$this->db->insert('users_student', $insertStudentData[$key]);
if you are trying to insert multiple rows, then you can use insert_batch
I have tried your code on my side and it gets perfectly correct. it added the multiple rows to the table. This is what I have done.
function create($studentData){
$insertStudentData = ''; //Create a Variable
foreach ($studentData => $studentDatas) {
$insertStudentData[] = array(
'parent_id' => $parent_id,
'email' => $studentDatas['email'],
'password' => $studentDatas['password'],
'name' => $studentDatas['name'],
'nric' => $studentDatas['nric'],
'gender' => $studentDatas['gender'],
'photo' => $studentDatas['photo']['0']['photo'],
'is_active' => $studentDatas['is_active']
);
}
$this->db->insert_batch('users_student', $insertStudentData[$key]);
if($this->db->affected_rows() != 1){
return false;
} else {
return true;
}
}
Finally I solved my issue. From my controller I changed the assigning array like this :
if($this->upload->do_upload('userFile')){
$fileData = $this->upload->data();
$studentImg[$i]['photo'] = $fileData['file_name'];
$studentData[] = array(
'name' => $_POST['user_name'][$i],
'nric' => $_POST['user_nric'][$i],
'gender' => $_POST['user_gender'][$i],
'photo' => $studentImg[$i]['photo'], // Edited row
'email' => $_POST['user_email'][$i],
'password' => md5($_POST['user_password'][$i]),
'is_active' => '0',
);
}
And my foreach model I changed to this :
foreach ($studentData as $studentDatas) {
$insertStudentData[] = array(
'parent_id' => $parent_id,
'email' => $studentDatas['email'],
'password' => $studentDatas['password'],
'name' => $studentDatas['name'],
'nric' => $studentDatas['nric'],
'gender' => $studentDatas['gender'],
'photo' => $studentDatas['photo'],
'is_active' => $studentDatas['is_active'],
);
}
$this->db->insert_batch('users_student', $insertStudentData);
And the output of those array :
Array
(
[0] => Array
(
[parent_id] => 11
[email] => testing.mael#gmail.com
[password] => 202cb962ac59075b964b07152d234b70
[name] => testing
[nric] => 123123
[gender] => 0
[photo] => 5955cac09b8f71.jpg
[is_active] => 0
)
[1] => Array
(
[parent_id] => 11
[email] => testing.mael#gmail.com
[password] => e13cc542ac59075b9643s5152d234g59
[name] => testing sister
[nric] => 123123
[gender] => 0
[photo] => 5955cac09b8f72.jpg
[is_active] => 0
)
)
By the way, thank you for everyone that trying to help! I appreciate it.

insert array data to mysql codeigniter 3

How can I insert array data to mysql using code igniter ??
I tried example from CI documentation like this
$data = array(
'id_kls' => 'id_kls',
'fk__id_kls' => 'fk__id_kls',
'id_reg_pd' => 'id_reg_pd',
'nm_pd' => 'nm_pd',
'asal_data' => 'asal_data',
'nilai_angka' => 'nilai_angka',
'nilai_huruf' => 'nilai_huruf',
'nilai_indeks' => 'nilai_indeks',
);
$this->db->insert('master_nilai', $data);
// Executes: REPLACE INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')
But not working ..
I have array data like this
Array
(
[error_code] => 0
[error_desc] =>
[result] => Array
(
[0] => Array
(
[id_kls] => f77294f7-2a5a-4876-860b-824d227d5b19
[fk__id_kls] => 02
[id_reg_pd] => 001be76b-4e58-4cea-96cf-fee2d8e0abdc
[nm_pd] => SUYATNO
[asal_data] => 9
[nilai_angka] =>
[nilai_huruf] => B
[nilai_indeks] => 3.00
)
Make sure you've enable config/autoload.php/$autoload['libraries'] = array('database');
and config/database.php/your hostname,username,dbname!

json column to gridview in yii2

I have a table:
id | name | values |
1 | John | {"data1":{"key1":"abs", "key2":"qwe"}, "data2":{"key1":"asd","key2":"obj"}}
in each row the json has different length. I need to create gridView like:
id | name | abs | asd | ...
1 | John | qwe | obj | ...
My code SqlDataProvider:
$count = Yii::$app->db->createCommand('
SELECT COUNT(id) FROM statistics', [':status' => 0])- >queryScalar();
$dataProvider = new SqlDataProvider([
'sql' => 'SELECT id, name, value
FROM
statistics',
'totalCount' => $count,
'key' => 'id',
]);
return $this->render('statistics',
[
'dataProvider' => $dataProvider,
]);
and GridView:
GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'id',
'name',
],
]); ?>
When I add column 'vlues' the result was like:
1 | John | {"data1":{"key1":"abs", "key2":"qwe"}, "data2":{"key1":"asd","key2":"obj"}}
Please, help!
I think you can add value column like this
'columns' => [
'id',
'name',
[
'attribute' => 'data1',
'value' => function($model){
return (json_decode($model->value)->data1);
}
],
],

How to transform this array in a json?

I have this relation CompanyhasMany Branch
And using $this->Company->find('all') output this:
(int) 1 => array(
'Company' => array(
'id' => '4',
'nome' => 'Somov',
'diretores' => 'Marcelo, Carl'
),
'Branch' => array(
(int) 0 => array(
'id' => '3',
'nome' => 'Serra',
'rua' => 'Rua teste 2 exttttt',
'numero' => '22',
'estado' => 'ES',
'cidade' => 'Etc',
'cep' => '',
'responsavel' => '',
'company_id' => '4',
'cnpj' => ''
)
)
),
(int) 2 => array(
'Company' => array(
'id' => '5',
'nome' => 'Soimpex',
'diretores' => ''
),
'Branch' => array()
)
)
I want to transform this in a json like this to use with Highchart:
[{
name: NAME OF COMPANY (nome),
data: NUMBER OF BRANCHS
}, {
name: NAME OF COMPANY (nome),
data: NUMBER OF BRANCHS
}]
How I do this convertion? Thanks
This will return a json object with only one result.
If we use previous example, can be done like this:
$arr = $this->Company->find('all'); // fetch the array
$arr1 = array();
foreach ($arr as $value) {
$tmp = array();
$tmp['name'] = $value['Company']['nome'];
$tmp['data'] = count($value['Branch']);
$arr1[] = $tmp;
}
return json_encode($arr1);
<?php
$sql=mysql_query("select * from Posts limit 20");
$response = array();
$posts = array();
while($row=mysql_fetch_array($sql))
{
$title=$row['title'];
$url=$row['url'];
$posts[] = array('title'=> $title, 'url'=> $url);
}
$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
?>
This will generate a file called results.json file where your php file is stored on your online server, taking url and title variables from your MySQL db, you can change the variable names to what you want to fetch.
The whole idea is about like this
$arr=$this->Company->find('all'); // fetch the array
$arr1=array();
foreach ($arr as $value) {
$arr1['name']=$value['Company']['nome'];
//some more manual transform to desire format
}
return json_encode($arr1);