Using urldecode on a mysql_fetch_array Array - php

I have been trying to convert the fields from a mysql_fetch_array (that are urlencoded) to urldecode before converting to JSON (json_encode)
Here's what I'm working with that doesn't work:The output is still urlencoded
$query = "SELECT * FROM table WHERE tableId=$tableId";
$result = mysql_fetch_array(mysql_query($query));
foreach($result as $value) {
$value = urldecode($value);
}
$jsonOut = array();
$jsonOut[] = $result;
echo (json_encode($jsonOut));
Any ideas?

yeah....! you're not updating $result with the value returned by the function. $value needs to be passed by reference.
foreach($result as &$value) {
$value = urldecode($value);
}
or
foreach($result as $i => $value) {
$result[$i] = urldecode($value);
}
when you do this...
foreach($result as $value) {
$value = urldecode($value);
}
The result of the function is lost at at iteration of the foreach. You're trying to update each value stored in $result but that's not happening.
Also take note that the code only fetches one row from your query. I'm not sure if that's by design or not.

Try:
$query = "SELECT * FROM table WHERE tableId=$tableId";
$result = mysql_query($query);
$value = array();
while($row = mysql_fetch_array($result))
$value[] = urldecode($row);
}
$jsonOut = array();
$jsonOut[] = $result;
echo (json_encode($jsonOut));

Related

PHP sql statement where clause to multiple array values

How do i use where clause for array if value[3] has multiple data stored
$fsql="select * from Error where RptDatime = 201706091000 and partnumber like ('$value[3]')";
$getResults = $conn->prepare($fsql);
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);
foreach($results as $row)
{
$mac = $row['Machine'];
$id = $row['Id'];
echo 'ID:'.$id.'Machine Number :'.$mac;
}
You can use regex function instead of like. Below is the sample code for you.
$partnumner = [];
foreach($value[3] as $v)
{
$partnumber[] = "*.".$v.".*";
}
$fsql="select * from Error where RptDatime = 201706091000 and partnumber REGEXP '".implode("|",$partnumber)."'";
If you still wish to use like, you can follow the answer here
I assume that you have array of numbers so, first you should validate for expected data and then to implode it into comma separated string.
if(!isset($value[3])){
return false;
}
if(!is_array($value[3])){
return false;
}
foreach($value[3] as $number){
if(!is_numeric($number)){
return false;
}
}
$numbers = implode(",",$value[3]);
$fsql=sprintf("select * from Error where RptDatime = 201706091000 and partnumber in (%s)",$numbers);
$getResults = $conn->prepare($fsql);
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);
foreach($results as $row)
{
$mac = $row['Machine'];
$id = $row['Id'];
echo 'ID:'.$id.'Machine Number :'.$mac;
}

Add Object to Array while looping

One of my PDO statements returns an array. For JSON encoding I want to cast this array to an Object and append it to another array.
while($row = $sth->fetch()){
foreach($row as $key=>$value){
$r = (object) $row;
$recordArray[] = $r;
}
}
$json->record = $recordArray;
echo json_encode($json);
$recordArray seems to stay empty but it doesn't if I write $recordArray[] = "test" in the loop. So there must be something wrong with my Object $r but I can't spot the mistake. Any help is appreciated.
Here is an easier way
echo json_encode(array('record'=>$sth->fetchAll(PDO::FETCH_OBJ)));
Your foreach is wrong: in body you use object on which you iterate.
May be you mean this?
$records = [];
while($row = $sth->fetch()) {
$current = [];
foreach($row as $key => $value) {
$current[$key] = $value;
}
$records[] = $current;
}
If I understood, you want to loop over $row and add every object within $row to $recordArray.
Then you should do this:
while($row = $sth->fetch()){
foreach($row as $value){
$recordArray[] = $value;
}
}

json encode and decode array in codeigniter

I am doing my project in codeigniter. My issues is i will store value for 'game_aspect_details' in json format like
"{"game_aspect_details":[{"aspect_id":"1"},{"aspect_id":"4"}]}"
for this select query i will decode the json format and check that value in foreach.
$this->db->select('game_aspect_details');
$this->db->from('share_reviews');
$this->db->where('review_id',6);
$query = $this->db->get();
$result = $query->result();
$test = $result[0]->game_aspect_details;
$res = json_decode($test);
$result_array = array();
foreach ($res as $row)
{
$this->db->select('comments');
$this->db->from('review_ratings');
$this->db->where('game_aspect_id',$row->game_aspect_details); //here i need
$query1 = $this->db->get(); to check 1 and 4
$resultReviews['comments'] = $query1->result();
$result_array[] = $resultReviews;
}
print_r($res);
exit;
First this do see what you are getting in the $row within the foreach by using the print_r().
And I hope that you need to replace the below line
$this->db->where('game_aspect_id',$row->game_aspect_details);
With following line:
$this->db->where('game_aspect_id',$row['aspect_id']);
as $row is an array not an object.
EDITED:
foreach ($res as $rows)
{
foreach ($rows as $row)
{
........
$this->db->where('game_aspect_id',$row['aspect_id']); //here make change
.....
}
}
You are doing some things wrong, see the comments in this code:
...
//$test = $result[0]->game_aspect_details; // This does not work since $result is not decoded yet
$res = json_decode($result); // Changed to `$result` instead of `$test`
$res = $res->game_aspect_details; // Instead pick the `game_aspect_details` here, after the decode
$result_array = array();
foreach ($res as $row)
{
$this->db->select('comments');
$this->db->from('review_ratings');
$this->db->where('game_aspect_id',$row['aspect_id']); // Changed to `aspect_id`
$query1 = $this->db->get();
$resultReviews['comments'] = $query1->result();
$result_array[] = $resultReviews;
}
...

array to string php

Hy every one I have this problem with an array I start like this...
$name = array($_POST['names']);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
$nameId[] = array('ids' => $row['id'] );
}
which gives me arrays like this..
$name:
array('0'=>'name1,name2,name3')
$names:
array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
how can I bring this in an string/form like this..
array('0'=>'61,6,1')
The idea is to save the ids to the Database.
Or is the a better more efficent way to get names from a form compare them with a database and get the ids back to save them to the Database?
many thanks in advance.
Change your assignment to this:
$nameId[] = $row['id'];
$name = array(name1,name2,name3);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
//below line changed
$nameId[] = $row['id'] ;
}
$string = implode(',',$nameId);
Try this :
$array = array(0=>array(0=>'61'),1=>array(0=>'6'),2=>array(0=>'1'));
$result = implode(",",call_user_func_array('array_merge', $array));
Please note : Here all are numeric keys, so change your code to :
$nameId[] = array($row['id'] ); , remove key 'ids' from here
Output :
61,6,1
Thats what I think
$nameId[] = $row['id'];
$stringId = implode(',',$name);
Use following function that will loop through array and find ids key and merge it into other array and after that when you calling this function it will impload it.
function CustomFindJoinArray( $needly, $array )
{
$results = array();
foreach ( $array as $key => $value )
{
if ( is_array( $value ) )
{
$results = array_merge($results, foo( $needly, $value ));
}
else if ( $key == $needly )
{
$results[] = $value;
}
}
return $results;
}
echo implode( ",", CustomFindJoinArray( "ids", $your_array ) );
where $your_array will be array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
OR More simple
foreach ($your_array as $key => $ids) {
$newArray[] = $array[$key]["ids"];
}
$string = implode(',', $newArray);
$ids = array();
foreach($nameId as $curr) {
$ids[] = $curr['ids'];
}
$str = "(".implode(",",$ids).")";

How to index the result of a mySql query as an array of array?

If I need to select and use information of every element of a table in a database the procedure would be this:
$query = "...mySql query...";
$query_result = mysql_query($query) or die (mysql_error());
Then if I wished to access the fields of the result I would use the function mysql_fetch_array() and access them like this:
$query_result_array = mysql_fetch_array($query_result);
echo $query_result_array['field_1'];
....
echo $query_result_array['field_i'];
....
But since more elements could be returned by the query I would like to access every single of them with an array indexed from 0 to mysql_num_rows($query_result).
As an example:
echo $query_result_array['field_i'][0];
....
echo $query_result_array['field_i'][mysql_num_rows($query_result)];
should print for every selected element of the table the value of field i.
Is there a function that will do the job for me?
If not, any suggestions on how to do it?
Thanks in advance for help.
This may be an alternative
$res = mysql_query("..SQL...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
$arr[] = $row;
}
var_dump($arr);
Or
$res = mysql_query("..SQL...");
for
(
$arr = array();
$row = mysql_fetch_assoc($res);
$arr[] = $row
);
var_dump($arr);
I don't think there is such a method; you have to do it yourself.
try with something like:
$res = mysql_query("..mySql query...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
$query_result_array[] = $row;
}
then you access your data like:
echo $query_result_array[0]['field_i'];
based on 2 previous answers, those authors assuming that usual SO author is familiar with such a thing as creating a function
function sqlArr($sql) { return an array consists of
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
if ($res) {
while ($row = mysql_fetch_assoc($res)) {
$ret[] = $row;
}
}
return $ret;
}
$array = sqlArr("SELECT * FROM table");
foreach ($array as $row) {
echo $row['name'],$row['sex'];
}
this resulting array have different structure from what you asked, but it is way more convenient too.
if you still need yours unusual one, you have to tell how you gonna use it

Categories