I have a postgresql (V 8.4) function that returns SETOF a custom type. An example of the string output from this function is the following 4 rows:
(2,"CD,100"," ","2010-09-08 14:07:59",New,0,,,,,,"2010-09-06 16:51:51","2010-09-07 16:51:57",)
(5,CD101,asdf,"2010-08-08 14:12:00",Suspended-Screen,1,10000,,,,,,,)
(4,DNR100,asdf,"2010-09-08 14:10:31",Suspended-Investgate,0,,,,,,"2010-09-06 16:51:51","2010-09-07 16:51:57",)
(3,MNSCU100," ","2010-09-08 14:09:07",Active,0,,,,,,,,)
I need to work with this data in PHP and I'm trying to figure out the best way to work with it. What I would love is if there was a way for postgresql to return this like a table where columns represent each value within a record rather than as a comma-separated string.
Is this possible? If not, what is the best way to work with this comma-separated string of values in PHP?
I've see this post (Convert PostgreSQL array to PHP array) and can use the function mentioned there but I wanted to ask if anyone has other ideas or suggestions.
Thanks,
Bart
There's str_getcsv() which'll parse a string as CSV data and return an array of the individual fields
Yep, its real easy, just change the way you are calling the function.
Instead of
SELECT my_srf(parm1);
Do either:
SELECT * FROM my_srf(parm1);
SELECT (my_srf(parm1)).*;
You'll even get the column names out this way.
Related
I simply want to know how to access array elements retrieved from a database. I have the following code to get the names of each item in my database.
$plat_options = $this->db->get('tblplatform_options')->select('name')->result();
How do I go about accessing the name from the array $plat_options? Typically I would do $plat_options[0] for the first element in C#, how is this done in php/codeigniter?
In PHP/Codeigniter, can be done in the same way:
$plat_options[0] //if you have this element, usually is better to check if exists.
You can retrieve all the elements with foreach($plat_options as $option){...}
You can cast to object: https://www.kathirvel.com/php-convert-or-cast-array-to-object-object-to-array/
Or use a Codeigniter Helper (assuming you are using CI3): http://www.codeigniter.com/user_guide/helpers/array_helper.html
I recomend to know which is your array format and retrieve that way (if you don't know, you can do a: var_dump($plat_options) ) to know if is an associative array.
You can use the result_array() function:
$data = $plat_options->result_array();
echo($data[0]['name']);
or:
$data = array_shift($q->result_array());
echo($data['name']);
I extracted this last part from: Codeigniter $this->db->get(), how do I return values for a specific row? that you could check too.
If you don't know a lof of CI, the best you can do is do a simple tutorial to understand how the data + ActiveRecord works.
Hope it helps!
Is there a resource of MySQL data types (varchar, int...) available in PHP?
Or perhaps a function that checks if a string is a valid MySQL data type?
If not is there a CSV list somewhere that could be copy/pasted into a project without having to manually enter every single datatype (there are about 40 different types)?
I am creating a database helper class and I would like to check a string against a list of valid MySQL data types.
This would have been very helpful to have found something like this for quick copy/paste. I thought I would post it as someone else might find it useful. If I am missing anything please let me know.
array('CHAR','VARCHAR','TINYTEXT','TEXT','BLOB','MEDIUMTEXT','TINYBLOB','MEDIUMBLOB','BLOB','LONGBLOB','LONGTEXT','TINYINT','SMALLINT','MEDIUMINT','INT','BIGINT','FLOAT','DOUBLE','DECIMAL','REAL','BIT','BOOLEAN','SERIAL','BINARY','VARBINARY','DATE','DATETIME','TIMESTAMP','TIME','YEAR','ENUM ','SET','GEOMETRY','POINT','LINESTRING','POLYGON','MULTIPOINT','MULTILINESTRING','MULTIPOLYGON','GEOMETRYCOLLECTION');
here is the function I was using it in:
function isValidDatatype($datatype){
$mysqlDatatypes = array('CHAR','VARCHAR','TINYTEXT','TEXT','BLOB','MEDIUMTEXT','TINYBLOB','MEDIUMBLOB','BLOB','LONGBLOB','LONGTEXT','TINYINT','SMALLINT','MEDIUMINT','INT','BIGINT','FLOAT','DOUBLE','DECIMAL','REAL','BIT','BOOLEAN','SERIAL','BINARY','VARBINARY','DATE','DATETIME','TIMESTAMP','TIME','YEAR','ENUM ','SET','GEOMETRY','POINT','LINESTRING','POLYGON','MULTIPOINT','MULTILINESTRING','MULTIPOLYGON','GEOMETRYCOLLECTION');
return in_array($datatype,$mysqlDatatypes);
}
I want to return values I retrieve from the db using group_concat as an array of data. Is it possible to do this in the mysql query? Or do I need to explode the data into an array?
GROUP_CONCAT(sh.hold_id) as holds
returns this
[holds] => 3,4
I want it to return:
[holds] => array(3,4)
As I said in my comment: you need to explode the data into an array, using php code like this:
$holds = explode(',', $holds);
because mysql has no concept of array-type for data.
This is possible since MySQL 5.7.22 using the JSON_ARRAYAGG() method
Read more: https://dev.mysql.com/doc/refman/5.7/en/aggregate-functions.html#function_json-arrayagg
Example:
SELECT JSON_ARRAYAGG(category.slug) as categories From categories
If you need to do it on the MySQL level, and then you may probably parse it to an object.
You can do the following
SELECT CONCAT("[", GROUP_CONCAT(category.name), "]") AS categories
From categories
MySQL has no concept of arrays. Therefore it is not able to return an array. It is up to your processing code (here the php scripts) to convert the concatenated notation into a php array.
It is possible to return mysql JSON array like so,
json_array(GROUP_CONCAT(sh.hold_id)) as holds
Refer docs for further info.
What would you say is the most efficient way to get a single value out of an Array. I know what it is, I know where it is. Currently I'm doing it with:
$array = unserialize($storedArray);
$var = $array['keyOne'];
Wondering if there is a better way.
You are doing it fine, I can't think of a better way than what you are doing.
You unserialize
You get an array
You get value by specifying index
That's the way it can be done.
Wondering if there is a better way.
For the example you give with the array, I think you're fine.
If the serialized string contains data and objects you don't want to unserialize (e.g. creating objects you really don't want to have), you can use the Serialized PHP library which is a complete parser for serialized data.
It offers low-level access to serialized data statically, so you can only extract a subset of data and/or manipulate the serialized data w/o unserializing it. However that looks too much for your example as you only have an array and you don't need to filter/differ too much I guess.
Its most efficient way you can do, unserialize and get data, if you need optimize dont store all variables serialized.
Also there is always way to parse it with regexp :)
If you dont want to unseralize the whole thing (which can be costly, especially for more complex objects), you can just do a strpos and look for the features you want and extract them
Sure.
If you need a better way - DO NOT USE serialized arrays.
Serialization is just a transport format, of VERY limited use.
If you need some optimized variant - there are hundreds of them.
For example, you can pass some single scalar variable instead of whole array. And access it immediately
I, too, think the right way is to un-serialize.
But another way could be to use string operations, when you know what you want from the array:
$storedArray = 'a:2:{s:4:"test";s:2:"ja";s:6:"keyOne";i:5;}';
# another: a:2:{s:4:"test";s:2:"ja";s:6:"keyOne";s:3:"sdf";}
$split = explode('keyOne', $storedArray, 2);
# $split[1] contains the value and junk before and after the value
$splitagain = explode(';', $split[1], 3);
# $splitagain[1] should be the value with type information
$value = array_pop(explode(':', $splitagain[1], 3));
# $value contains the value
Now, someone up for a benchmark? ;)
Another way might be RegEx ?
I am fetching an array of floats from my database but the array I get has converted the values to strings.
How can I convert them into floats again without looping through the array?
Alternatively, how can I fetch the values from the database without converting them to strings?
EDIT:
I am using the Zend Framework and I am using PDO_mysql. The values are stored one per column and that is a requirement so I can't serialize them.
array_map('floatval', $array) only works on single dimensional arrays.
I can't floatval the single elements when I use them because I have to pass an array to my flash chart.
The momentary, non-generic solution is to extract the rows and do array_map('floatval',$array) with each row.
You could use
$floats = array_map('floatval', $nonFloats);
There is the option PDO::ATTR_STRINGIFY_FETCHES but from what I remember, MySQL always has it as true
Edit: see Bug 44341 which confirms MySQL doesn't support turning off stringify.
Edit: you can also map a custom function like this:
function toFloats($array)
{
return array_map('floatval', $array);
}
$data = array_map('toFloats', $my2DArray);
How are you getting your data? mysql, mysqli or PDO, some other way or even some other database?
you could use array_map with floatval like so:
$data = array_map('floatval', $data);
but that still executes a loop and i think it assumes you only have one column in your data.
you're probably best of casting to float when you use your value, if you have to. php is likely to do a good job of interpreting it right anyway.
LOL... are you working on the same project I am tharkun?
I just finished (last night) creating something, in a ZF based project, that uses pdo_mysql to retrieve and format data and then output it as xml for use in a flash piece. The values were going in as strings but needed to be floats.
Since I'm also the one who wrote the part that gets the data and the one who created the database I just made sure the data was converted to float before it went into the database.
I simply cast the values as float as part of some other formatting, for what it is worth.
protected function _c2f($input)
{
$input = (float)$input;
$output = round(($input * 1.8) + 32, 2);
return $output;
}
I found an easy way for this operation.
You can do this just by adding foreach loop to your code. foreach loop is used to fetch your array string data one by one. and then, you can simply convert this by function number_format. i used 2 place after convert to float value. i.e it used to print value after dot value 2 place.
$example= array("12.20", "15.05", "55.70");
foreach($example as $float)
{
$update_value = number_format($float,2);
echo $update_value."<br>";
}
Not sure what you're asking here? You can cast a string to a float, using (float) $string, but since PHP is dynamically typed, that will happen anyway, when needed. There is no reason to do an explicit cast.
What are you using floating point values for?