PDO Fetch data returns array of string - php

I am trying to get data from a MySQL database with PDO but unfortunately PDO returns the result as an array of strings. I want to keep the native MySQL data types in the result array.
I have tried setting PDO::ATTR_DEFAULT_FETCH_MODE to both PDO::FETCH_ASSOC AND PDO::FETCH_OBJ but it was still returning INT data as string.
Here is the result of dump:
array (size=1)
0 =>
object(stdClass)[27]
public 'id' => string '3' (length=1)
public 'avatar' => string '' (length=0)
public 'fullName' => string 'Mikheil Janiashvili' (length=19)
public 'email' => string 'xxxxx#yyyyy.com' (length=17)
public 'phone' => string '23 3537 20 03544' (length=12)
public 'educationGE' => string '' (length=0)
public 'educationEN' => string '' (length=0)
public 'educationRU' => string '' (length=0)
public 'experienceGE' => string '' (length=0)
public 'experienceEN' => string '' (length=0)
public 'experienceRU' => string '' (length=0)
public 'descriptionGE' => string '' (length=0)
public 'descriptionEN' => string '' (length=0)
public 'descriptionRU' => string '' (length=0)

When you instantiate your PDO object, you need to tell it to use MySQL's native prepared queries:
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
Assuming you're using PHP >= 5.3 you will be using the mysqlnd library, which can return proper data types from prepared queries.
Example:
$ php -a
Interactive shell
php > $db = PDO("mysql:host=localhost;dbname=test", "test", "");
php > $res = $db->query("SELECT 1, PI()");
php > var_dump($res->fetch());
array(4) {
[1]=>
string(1) "1"
[2]=>
string(1) "1"
["PI()"]=>
string(8) "3.141593"
[3]=>
string(8) "3.141593"
}
php > $db = PDO("mysql:host=localhost;dbname=test", "test", "", [PDO::ATTR_EMULATE_PREPARES=>false]);
php > $res = $db->query("SELECT 1, PI()");
php > var_dump($res->fetch());
array(4) {
[1]=>
int(1)
[2]=>
int(1)
["PI()"]=>
float(3.1415926535898)
[3]=>
float(3.1415926535898)
}
php >

Related

Select certain data in PHP Array

I get the following output when using this line of code var_dump($ticket->find()); How would I access only the identifiers throughout ALL objects?
I tried var_dump($ticket->find()->identifier); but it returned null.
array (size=2)
0 =>
object(stdClass)[9]
public 'tid' => string '1' (length=1)
public 'uid' => string '22' (length=2)
public 'subject' => string 'iPhone 8' (length=8)
public 'issue' => string 'iPhone 8 screen replacement' (length=27)
public 'device' => string 'iPhone 8' (length=8)
public 'created' => string '2017-05-25 00:01:11' (length=19)
public 'identifier' => string '29cd54bf' (length=8)
public 'status' => string 'New' (length=3)
public 'tech' => string 'None' (length=4)
1 =>
object(stdClass)[11]
public 'tid' => string '2' (length=1)
public 'uid' => string '22' (length=2)
public 'subject' => string 'iPhone 7' (length=8)
public 'issue' => string 'iPhone 7 screen replacement' (length=27)
public 'device' => string 'iPhone 7' (length=8)
public 'created' => string '2017-05-25 00:27:42' (length=19)
public 'identifier' => string 'b47f2c82' (length=8)
public 'status' => string 'New' (length=3)
public 'tech' => string 'None' (length=4)
You could use array_map to select the properties that you need from each item in the array returned by find:
$filteredFields = array_map(function ($item) {
// Return whatever properties you want here:
return [$item->tid, $item->$uid, $item->issue];
}, $ticket->find());
$filteredFields will be an array of arrays:
array(2) {
[0]=> array(3) {
[0]=> string(1) "1"
[1]=> string(2) "22"
[2]=> string(8) "iPhone 7"
}
[1]=> array(3) {
[0]=> string(1) "2"
[1]=> string(2) "22"
[2]=> string(8) "iPhone 7"
}
}
If you just need one of the properties, it may be easier to use array_column:
$subjectFields = array_column($ticket->find(), "subject");
This will return something that looks like this:
array(2) {
[0]=> string(8) "iPhone 8"
[1]=> string(8) "iPhone 7"
}
You can also get an associative array indicating which field to use as the key with the third parameter:
$subjectsByTid = array_column($ticket->find(), "subject", "tid");
This will return:
array(2) {
["1"]=> string(8) "iPhone 8"
["2"]=> string(8) "iPhone 7"
}

Why are int columns returned as string when using WordPress's $wpdb to get database rows?

I've created a table to use within my Wordpress site, with columns using date, int and varchar as the type.
However, when I use var_dump to get the values of particular rows and results, it displays all the columns as string.
I haven't seen this actually affect the operation of the DB calls and functions, but I'm just wondering why they're all returning as strings, where I've seen core Wordpress functions in var_dump returning int values sometimes.
$bv_set = $wpdb->get_row('SELECT * FROM wp_before_after WHERE ID = '.$bv_id );
var_dump($bv_set);
C:\wamp64\www\bellavou\wp-content\plugins\bv-before-afters\views\edit.php:8:
object(stdClass)[6915]
public 'ID' => string '1' (length=1)
public 'created' => string '0000-00-00' (length=10)
public 'before_date' => string '2015-04-08' (length=10)
public 'after_date' => string '2015-04-21' (length=10)
public 'patientID' => string '2137' (length=4)
public 'procedureID' => string '238' (length=3)
public 'patient_display' => string '1' (length=1)
public 'procedure_display' => string '1' (length=1)
public 'gallery_display' => string '1' (length=1)
public 'before_img' => string '2200' (length=4)
public 'after_img' => string '2199' (length=4)
public 'period_taken' => string '1week' (length=5)
public 'notes' => string '' (length=0)
Reading through the code of $wpdb->get_row, you can see that it eventually calls $wpdb->query, which in turn calls mysqli_fetch_object (line 1822 at time of writing):
while ( $row = mysqli_fetch_object( $this->result ) ) {
$this->last_result[$num_rows] = $row;
$num_rows++;
}
Now, taking a look at the PHP documentation for mysqli_fetch_object:
Returns an object with string properties that corresponds to the fetched row or NULL if there are no more rows in resultset.
Which provides an answer to the question.
Highly depends on the mysql connector and it's type castings based on the DB field options like "null" values. Might also be related to some notorious php type castings (see https://www.sitepoint.com/3-strange-php-facts-you-may-not-know/ )

PHP and JSON from Openstreetmap search

I am trying to use Openstreetmap and PHP to point to a place on a map.
As you can see below, I retrieve a JSON array, but PHP returns a NULL value.
Note that my $url is a valid JSON (you can check it here).
<?
$url = 'http://nominatim.openstreetmap.org/search/Piazza%20Duomo%20Trento?format=json&addressdetails=1&limit=1&polygon_svg=1';
$html = file_get_contents($url);
$jsonout = json_decode($html);
echo $jsonout[0];
?>
What am I doing wrong?
What am I doing wrong?
First of all, your openning tag is not correct :
<? ----> <?php
Then, you cannot echo an array like that. Use var_dump on your array to see the structure.
When I try your code with the corrections, I got this :
array (size=1)
0 =>
object(stdClass)[1]
public 'place_id' => string '8577656' (length=7)
public 'licence' => string 'Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright' (length=84)
public 'osm_type' => string 'node' (length=4)
public 'osm_id' => string '924463183' (length=9)
public 'boundingbox' =>
array (size=4)
0 => string '46.0675164' (length=10)
1 => string '46.0676164' (length=10)
2 => string '11.1217498' (length=10)
3 => string '11.1218498' (length=10)
public 'lat' => string '46.0675664' (length=10)
public 'lon' => string '11.1217998' (length=10)
public 'display_name' => string 'Piazza Duomo, Piazza del Duomo, centro storico Trento, Trento, TN, TAA, 38122, Italia' (length=85)
public 'class' => string 'highway' (length=7)
public 'type' => string 'bus_stop' (length=8)
public 'importance' => float 0.311
public 'icon' => string 'http://nominatim.openstreetmap.org/images/mapicons/transport_bus_stop2.p.20.png' (length=79)
public 'address' =>
object(stdClass)[2]
public 'bus_stop' => string 'Piazza Duomo' (length=12)
public 'pedestrian' => string 'Piazza del Duomo' (length=16)
public 'suburb' => string 'centro storico Trento' (length=21)
public 'city' => string 'Trento' (length=6)
public 'county' => string 'TN' (length=2)
public 'state' => string 'TAA' (length=3)
public 'postcode' => string '38122' (length=5)
public 'country' => string 'Italia' (length=6)
public 'country_code' => string 'it' (length=2)
public 'svg' => string 'cx="11.1217998" cy="-46.067566399999997"' (length=40)
In answer to your question, except for trying to output an array with the following statement
echo $jsonout[0];
Which will throw a Catchable fatal error: Object of class stdClass could not be converted to string
Everything is ok.
If this is about accessing the members of the json_decode return, see below
$jsonout is an array with one element,
that one element is an object, you can access its members like this
print $jsonout[0]->licence;
Which will output
Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright
If you'd like an associative array, you can pass the second argument for json_decode, like this
$jsonout = json_decode($html,true);
print $jsonout[0]['display_name'];
Which will decode the json into an associative array and will display in a similar way
Piazza Duomo, Piazza del Duomo, centro storico Trento, Trento, TN, TAA, 38122, Italia
please use print_r() in place of echo
$url = "http://nominatim.openstreetmap.org/search/Piazza%20Duomo%20Trento?format=json&addressdetails=1&limit=1&polygon_svg=1";
$html = file_get_contents($url);
$jsonout = json_decode($html);
print_r($jsonout[0]);
and you will get your result.
or you can print $jsonout[0]["license"]

properly render an array of numeric values, not an array with strings

I have this code in my symfony controller:
$em=$this->getDoctrine()->getManager();
$queryIndex = $em->createQuery( 'SELECT g.index
FROM MySpaceMyBundle:Graphique g');
$result = $queryIndex->getArrayResult();
$arrayResult = array_map('current', $result);
var_dump($arrayResult);
return $this->render('MySpaceMyBundle:MyFolder:myTemplate.html.twig');
With my var_dump, I have this result:
array (size=10)
0 => string '1700.000' (length=8)
1 => string '1200.000' (length=8)
2 => string '1200.000' (length=8)
3 => string '1304.000' (length=8)
4 => string '1800.000' (length=8)
5 => string '2012.000' (length=8)
6 => string '2048.000' (length=8)
7 => string '1048.000' (length=8)
8 => string '3000.000' (length=8)
9 => string '5421.000' (length=8)
But for the obHighchartBundle (using highchart.js) the result I want is:
[1700,1200,1200,1304,1800,2012,2048,1048,3000,5421]
How can I proceed?
Note that I need to pass a numeric array (the values are decimal types in my database), not array with strings.
Like this?
$result = [];
foreach ($arrayResult as $value) {
$result[] = (int) $value
}
var_dump($result);
You can use a tiny tips like array_walk function to cast your values as float to prevent highchart issue. See the documentation for this function:
http://php.net/manual/fr/function.array-walk.php
Here an example of the tiny function :
<?php
function forceFloat (&$aItems) {
$aItems = (float) $aItems;
}
$arrayResult = array("1.00","4.55","39494");
var_dump($arrayResult);
array_walk($arrayResult, 'forceFloat');
var_dump($arrayResult);
?>
The output :
array(3) {
[0]=>
string(4) "1.00"
[1]=>
string(4) "4.55"
[2]=>
string(5) "39494"
}
array(3) {
[0]=>
float(1)
[1]=>
float(4.55)
[2]=>
float(39494)
}
Best Regards,
TGA

converting array to stdClass in CodeIgniter

I am returning data from two tables in CodeIgniter with the function below
public function test()
{
$this->db->select('*');
$this->db->from('WHOUSE1.DLY_BWR_DLY_PERFORMANCE');
$this->db->join('WHOUSE1.DATE_DIM', 'WHOUSE1.DATE_DIM.DATE_KEY = WHOUSE1.DLY_BWR_DLY_PERFORMANCE.BDP_DATE');
$query = $this->db->get();
return $query->result_array();
}
Using var_dump I am getting the result below
array (size=3226)
0 =>
array (size=121)
'BDP_ID' => string '945149' (length=6)
'BDP_COST_CENTRE_NUMBER' => string '1376' (length=4)
'BDP_DATE' => string '20040807' (length=8)
'BDP_DAY_CODE' => string '6' (length=1)
'BDP_TAKE' => string '4923.78' (length=7)
'BDP_PAYOUT' => string '3779.22' (length=7)
'BDP_ACTUAL_SLIPPAGE' => string '636' (length=3)
1 =>
array (size=121)
'BDP_ID' => string '945150' (length=6)
'BDP_COST_CENTRE_NUMBER' => string '1376' (length=4)
'BDP_DATE' => string '20040809' (length=8)
'BDP_DAY_CODE' => string '1' (length=1)
'BDP_TAKE' => string '2848.3' (length=6)
'BDP_PAYOUT' => string '4190.34' (length=7)
'BDP_ACTUAL_SLIPPAGE' => string '280' (length=3)
But what I will like to get is this
array (size=3226)
0 =>
object(stdClass)[27]
'BDP_ID' => string '945149' (length=6)
'BDP_COST_CENTRE_NUMBER' => string '1376' (length=4)
'BDP_DATE' => string '20040807' (length=8)
'BDP_DAY_CODE' => string '6' (length=1)
'BDP_TAKE' => string '4923.78' (length=7)
'BDP_PAYOUT' => string '3779.22' (length=7)
'BDP_ACTUAL_SLIPPAGE' => string '636' (length=3)
1 =>
object(stdClass)[29]
'BDP_ID' => string '945150' (length=6)
'BDP_COST_CENTRE_NUMBER' => string '1376' (length=4)
'BDP_DATE' => string '20040809' (length=8)
'BDP_DAY_CODE' => string '1' (length=1)
'BDP_TAKE' => string '2848.3' (length=6)
'BDP_PAYOUT' => string '4190.34' (length=7)
'BDP_ACTUAL_SLIPPAGE' => string '280' (length=3)
I can't seem to get a way of converting the array into object(stdClass) Any help will be appreciated as am new to CodeIgniter.
Array to stdClass can be done in php this way.
stdClass:: __set_state(array());
Or a nicer way.
$a = (object) array();
Use this code in Your Model ( change your table name and select, distinct fileds )
$this->db->select('DISTINCT(subcategory)');
$this->db->from('tbl_property');
$this->db->where('status','1');
$data = $this->db->get()->result();
$sub_id = array();
foreach ($data as $row)
{
array_push($sub_id,$row->subcategory);
}
$this->db->from('tbl_subcategory');
$this->db->where_in('id',$sub_id);
$data1 = $this->db->get()->result();
return $data1;
use
return $query->result();
This function returns the query result as an array of objects, or an empty array on failure. Typically you'll use this in a foreach loop, like this:
$query = $this->db->query("YOUR QUERY");
foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->body;
}
Edit:
If you just want to print you can use var_dump() or print_r().
var_dump($obj);
print_r($obj);
If you want an array of all properties and their values use get_object_vars().
$properties = get_object_vars($obj);
print_r($properties);
According to the same documentation for Codeigniter I detail:
result_array()
This function returns the query result as a pure array, or an empty array when no
result `is produced. Typically you'll use this in a foreach loop, like this:`
and ..
result()
This function returns the query result as an array of objects, or an empty array
on failure.
You should return your data in this way
return $query->result();

Categories