Fetch Casted Value from a select query into an array - php

I used cast in order to convert a datatype of one of the columns in my select query.
SELECT cast(user_id as varchar(255)) from cabinet
I need to fetch the result of this value into an array but it returns null value
$listData[] = array(
"member_id" => $row['cast(user_id]
);
How can I display it on array?

SQL:
SELECT cast(user_id AS varchar(255)) AS member_id FROM cabinet
PHP:
$listData = array("member_id" => $row['member_id']);
Basically, you forgot to name the cast function's return in your SQL and used some extremely weird syntax in your PHP. $Array[] = $x; adds element $x as an array item to $Array in PHP. To create a new array, you should run $Array = array();. Some programming languages do indeed force you to put square brackets after a variable's name on value assignation to specify it as an Array/String type, but PHP is not one of them.
To reference an item by key, you have to use the array's name and the key's value in square brackets ($Array[$n], where $n is an integer for arrays with integer indexes, and Array['key'] for arrays with String indexes). 'cast(user_id AS varchar(255))' is not a valid array key, you have to give the SQL function return value a name to be able to reference it as an array item.
Please let me know if this makes sense.
My answer assumes that you are familiar with mySQLi and know how to get $row['member_id'] from the query.

Related

Array as variable for in_array

I have a table that I am reading two columns from using PDO::FETCH_KEY_PAIR. I then need check if a value from another query exists in the array returned by the PDO fetch. To illustrate:
$id = array();
/* array returned by PDO::FETCH_KEY_PAIR query */
$mailTo = array (
'MailTo1' => 6143,
'MailTo2' => 6137,
'MailTo3' => 6137,
);
echo $mailTo['MailTo1']; //6143
$result1['needle'] = 'MailTo1'; //needle from second query to seek
if(in_array($result1['needle'], $mailTo)){
$id['mailTo'] = $mailTo[$result1['needle']]; //null
}
using variable $result['needle'] returns null, but to verify that in_array returns the correct element I have used:
if(in_array('MailTo1', $mailTo)){
$id['mailTo'] = $mailTo[$result['needle']]; //6143
}
Hard coding the needle returns the correct element. Taking the needle out an array and passing as a simple variable also returns null, i.e.
$result = 'MailTo1';
if(in_array($result1, $mailTo)){
$id['mailTo'] = $mailTo[$result1]; //null
}
I cannot figure out why passing the needle as a key=>value variable ($result1['needle']) fails. It seems like this is very common practice...
In order to compare keys you need to use array key exists. in_array only looks at values and not the keys.
array_key_exists("MailTo1",$mailTo)
Another approach would be to get all keys in one array and then you can use in_array()
$mailToKeys = array_keys($mailTo);
in_array("MailTo1", $MailToKeys)
DOH!!! Wrong approach.. array_key_exists is what I should have been using!!

fetch value from an array

I need to fetch value from an array .I need to fetch the value name,value,user_id from an given array
$inner_content='[{"name":"radio","value":"1","id":"1","user_id":"admin#gmail.com","web":"571710720","type":"poll_info","pg":"question_response"},{"name":"fav-color[]","value":"blue"}]'
$id='5'; //value given for expample.
$inner="select * from user_response where POLL_ID=$id";
$inner1=mysql_query($inner);
while($ifet=mysql_fetch_assoc($inner1))
{
$inner_content = $ifet['CONTENT_VALUES'];
$data1 = json_decode($inner_content);
$test1[]=array('name'=>$data1->name);
}
In JSON, square brackets denote an array, and curly braces denote an object. As you can see if you look carefully at $inner_content, it's an array containing a bunch of objects, so you need to index it.
$test1[] = array('name' => $data1[0]->name);
This just gets the name from the first object in the array. If you want to get all the names, you could use a foreach loop on $data1 (but only the first one has all the properties that you say you want).

Php array to MySQL query condition structure

I have following array in PHP:
$arr = [1, 3, '4A', '5A', '5C', '2B', '2C', '2E'];
Somehow I need to convert this array to a string which look like this:
$filter = "(id like '1%') OR
(id like '3%') OR
(id like '4A%') OR
(id like '5A%' OR id like '5C%') OR
(id like '2B%' OR id like '2C%' OR id like '2E%')";
The first character of the array value indicates a unique categorie and is wrapped in parentheses.
In the end I will use this to query the database;
$sql = "SELECT * FROM list WHERE {$filter}";
Can someone help me converting this array to the correct string ? What is the best method to achieve this ?
To give you an idea of what I'm trying:
The 'id' column in my database row looks like; 1B2875. Where the first char (1) indicates a categorie and the second char (B) the subcategorie. The given array is a result of a client-side filter request.
You can use regular expressions in SQL:
SELECT * FROM list WHERE id REGEXP '^(1|3|4A|…)[0-9]+$'
The value inside the parentheses can be generated with the PHP function implode('|', $filter_strings)
Note that you should validate and escape the filter strings first to prevent the user input from manipulating the query. The function preg_quote is useful here.

Retrieve serialize value in the database wordpress

I'm trying to query a serialized array value in the database in wordpress, value will be stored in the table wp_postmeta, in the column meta_value.
Well, first I stored the array by using serialize() function of php.
So for example,
$postID = 1;
$arr = array(1, 2, 3);
$ser_val = serialize($arr);
update_meta_data($postID, '_customvalue', $ser_val);
The stored values is something like this
s:30:"a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}";
Then when I tried to retrieve it by performing wordpress sql query.. What I was expecting that it will be an array since it is stored as array, but after doing so, it display as string not an array.
$get_score = $wpdb->get_row("SELECT meta_value FROM wp_postmeta WHERE meta_key = '_cummulativescore'");
$scr = unserialize($get_score->meta_value);
var_dump($scr);
//output displayed
//string(30) "a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}"
I did check the value using is_array() function, the result is that it is not an array
Any idea on this to get the serialize value as an array?
It looks like your data was converted to a string during serialization.
The data should be stored as
a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}
instead of
s:30:"a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}"
s:30 means string length 30.

Save PHP array to MySQL?

What is a good way to save an array of data to a single mysql field?
Also once I query for that array in the mysql table, what is a good way to get it back into array form?
Is serialize and unserialize the answer?
There is no good way to store an array into a single field.
You need to examine your relational data and make the appropriate changes to your schema. See example below for a reference to this approach.
If you must save the array into a single field then the serialize() and unserialize() functions will do the trick. But you cannot perform queries on the actual content.
As an alternative to the serialization function there is also json_encode() and json_decode().
Consider the following array
$a = array(
1 => array(
'a' => 1,
'b' => 2,
'c' => 3
),
2 => array(
'a' => 1,
'b' => 2,
'c' => 3
),
);
To save it in the database you need to create a table like this
$c = mysql_connect($server, $username, $password);
mysql_select_db('test');
$r = mysql_query(
'DROP TABLE IF EXISTS test');
$r = mysql_query(
'CREATE TABLE test (
id INTEGER UNSIGNED NOT NULL,
a INTEGER UNSIGNED NOT NULL,
b INTEGER UNSIGNED NOT NULL,
c INTEGER UNSIGNED NOT NULL,
PRIMARY KEY (id)
)');
To work with the records you can perform queries such as these (and yes this is an example, beware!)
function getTest() {
$ret = array();
$c = connect();
$query = 'SELECT * FROM test';
$r = mysql_query($query,$c);
while ($o = mysql_fetch_array($r,MYSQL_ASSOC)) {
$ret[array_shift($o)] = $o;
}
mysql_close($c);
return $ret;
}
function putTest($t) {
$c = connect();
foreach ($t as $k => $v) {
$query = "INSERT INTO test (id,".
implode(',',array_keys($v)).
") VALUES ($k,".
implode(',',$v).
")";
$r = mysql_query($query,$c);
}
mysql_close($c);
}
putTest($a);
$b = getTest();
The connect() function returns a mysql connection resource
function connect() {
$c = mysql_connect($server, $username, $password);
mysql_select_db('test');
return $c;
}
Generally, yes, serialize and unserialize are the way to go.
If your data is something simple, though, saving as a comma-delimited string would probably be better for storage space. If you know that your array will just be a list of numbers, for example, then you should use implode/explode. It's the difference between 1,2,3 and a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}.
If not, then serialize and unserialize work for all cases.
Just use the serialize PHP function:
<?php
$myArray = array('1', '2');
$seralizedArray = serialize($myArray);
?>
However, if you are using simple arrays like that you might as well use implode and explode.Use a blank array instead of new.
Serialize/Unserialize array for storage in a DB
Visit http://php.net/manual/en/function.serialize.php
From the PHP Manual:
Look under "Return" on the page
Returns a string containing a byte-stream representation of value that can be stored anywhere.
Note that this is a binary string which may include null bytes, and needs to be stored and handled as such. For example, serialize() output should generally be stored in a BLOB field in a database, rather than a CHAR or TEXT field.
Note: If you want to store html into a blob, be sure to base64 encode it or it could break the serialize function.
Example encoding:
$YourSerializedData = base64_encode(serialize($theHTML));
$YourSerializedData is now ready to be stored in blob.
After getting data from blob you need to base64_decode then unserialize
Example decoding:
$theHTML = unserialize(base64_decode($YourSerializedData));
The best way, that I found to myself is save array as data string with separator characters
$array = array("value1", "value2", "value3", "...", "valuen");
$array_data = implode("array_separator", $array);
$query = "INSERT INTO my_tbl_name (id, array_data) VALUES(NULL,'" . $array_data . "');";
You can then search data, stored in your array with simple query
$query = "SELECT * FROM my_tbl_name WHERE array_data LIKE '%value3%'";
use explode() function to convert "array_data" string to array
$array = explode("array_separator", $array_data);
note that this is not working with multidimensional arrays and make sure that your "array_separator" is unique and had not exist in array values.
Be careful !!! if you just will take a form data and put in database, you will be in trap, becous the form data isn't SQL-safe ! you must handle your form value
with mysql_real_escape_string or if you use MySQLi mysqli::real_escape_string
or if value are integer or boolean cast (int) (boolean) on them
$number = (int)$_POST['number'];
$checked = (boolean) $_POST['checked'];
$name = mysql_real_escape_string($db_pt, $_POST['name']);
$email = mysqli_obj->real_escape_string($_POST['email']);
Serialize and unserialize are pretty common for that. You could also use JSON via json_encode and json_decode for a less PHP-specific format.
As mentioned before - If you do not need to search for data within the array, you can use serialize - but this is "php only". So I would recommend to use json_decode / json_encode - not only for performance but also for readability and portability (other languages such as javascript can handle json_encoded data).
Uhh, I don't know why everyone suggests serializing the array.
I say, the best way is to actually fit it into your database schema. I have no idea (and you gave no clues) about the actual semantic meaning of the data in your array, but there are generally two ways of storing sequences like that
create table mydata (
id int not null auto_increment primary key,
field1 int not null,
field2 int not null,
...
fieldN int not null
)
This way you are storing your array in a single row.
create table mydata (
id int not null auto_increment primary key,
...
)
create table myotherdata (
id int not null auto_increment primary key,
mydata_id int not null,
sequence int not null,
data int not null
)
The disadvantage of the first method is, obviously, that if you have many items in your array, working with that table will not be the most elegant thing. It is also impractical (possible, but quite inelegant as well - just make the columns nullable) to work with sequences of variable length.
For the second method, you can have sequences of any length, but of only one type. You can, of course, make that one type varchar or something and serialize the items of your array. Not the best thing to do, but certainly better, than serializing the whole array, right?
Either way, any of this methods gets a clear advantage of being able to access an arbitrary element of the sequence and you don't have to worry about serializing arrays and ugly things like that.
As for getting it back. Well, get the appropriate row/sequence of rows with a query and, well, use a loop.. right?
You can save your array as a json.
there is documentation for json data type: https://dev.mysql.com/doc/refman/5.7/en/json.html
I think this is the best solution, and will help you maintain your code more readable by avoiding crazy functions.
I expect this is helpful for you.
Yup, serialize/unserialize is what I've seen the most in many open source projects.
I would suggest using implode/explode with a character that you know will not be contained in any of the individual array items. Then store it in SQL as a string.
you can insert serialized object ( array ) to mysql , example serialize($object) and you can unserize object example unserialize($object)
check out the implode function, since the values are in an array, you want to put the values of the array into a mysql query that inserts the values into a table.
$query = "INSERT INto hardware (specifications) VALUES (".implode(",",$specifications).")";
If the values in the array are text values, you will need to add quotes
$query = "INSERT INto hardware (specifications) VALUES ("'.implode("','",$specifications)."')";
mysql_query($conn,$query);
Also, if you don't want duplicate values, switch the "INto" to "IGNORE" and only unique values will be inserted into the table.
UPDATE
Warning
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:
mysqli_query
PDO::query()
Instead of saving it to the database, save it to a file and then call it later.
What many php apps do (like sugarcrm) is to just use var_export to echo all the data of the array to a file.
This is what I use to save my configurations data:
private function saveConfig() {
file_put_contents($this->_data['pathtocompileddata'],'<?php' . PHP_EOL . '$acs_confdata = ' . var_export($this->_data,true) . ';');
}
I think this is a better way to save your data!

Categories