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;
}
...
Related
I have the following function which fetches some data from a MySQL table:
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
foreach ($query as $row) {
var_dump($row);
};
echo $data
}
How can I push all the returned data into an array, where each member is indexed by a number?
Do I need to use echo or return at the end? They seem to have the same effect.
EDIT: Is this the correct way of returning results of the query? I am passing it to the front-end.
$questionData = $controller->readQuestion($quizType, $questionId);
return $questionData;
In general your function must looks like:
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
return $query;
}
But, you have to look what is inside $query variable. If it is array - just return this array, if not - maybe it is some iterator, hence you have to check it and try to find method like toArray or something like that... Otherwise, you have to do something like:
$data = [];
foreach ($query as $row) {
$data[] = $row;
};
return $data;
Now you can use this function like:
var_dump(readQuestion($quizType, $questionId));
Take a look up here on how to secure your data.
Anyway, as I said in the comment you cannot use echo on an Array. And you can't do anything with the output of var_dump.
Change var_dump($row); for $data[] = $row;
and change echo $data; for return $data;
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
foreach ($query as $row) {
$data=$row;
};
return $result;
}
I have tried to get all the rows from mysql table for that am using mysqli_fetch_assoc. While using this am getting only one row. I need to convert the resulting array into JSON.
$query = "SELECT * FROM db_category WHERE publish='1'";
$result = mysqli_query($c, $query) or die(mysqli_error($c));
$length = mysqli_num_rows($result);
if($length > 0)
{
$var['status'] = 'success';
while($obj = mysqli_fetch_assoc($result))
{
$var = array_merge($var, $obj);
$var1 = json_encode($var);
}
echo '{"slider":['.$var1.']}';
}
else
{
$arr = array('status'=>"notfound");
echo '{"slider":['.json_encode($arr).']}';
}
Now the output for above code is,
{"slider":[{"status":"success","category_id":"12","category_name":"Books","publish":"1"}]}
Required output is,
{"slider":[{"status":"success","category_id":"1","category_name":"Apparel","publish":"1"},{"status":"success","category_id":"2","category_name":"Footwear","publish":"1"},{"status":"success","category_id":"3","category_name":"Furniture","publish":"1"},{"status":"success","category_id":"4","category_name":"Jewellery","publish":"1"}]}
How to solve this issue.
You can do it simply by json_encode() function. And you can also get all data into array, with mysqli_fetch_all() function :
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
$jsonData = json_encode(array('slider'=>$data, 'status' => 'success'));
If you want to put 'status'=>'success' for each row, do it like this (before json_encode)
foreach($data as $key => $dataRow) {
$data[$key]['status'] = 'success';
}
I have a method of creating JSON into an array that looks like this:
[{"date":"","name":"","image":"","genre":"","info":"","videocode":""},{...},{...}]
I first tried getting the data from a html page (not the database) like this:
$arr = array();
$info = linkExtractor($html);
$dates = linkExtractor2($html);
$names = linkExtractor3($html);
$images = linkExtractor4($html);
$genres = linkExtractor5($html);
$videocode = linkExtractor6($html);
for ($i=0; $i<count($images); $i++) {
$arr[] = array("date" => $dates[$i], "name" => $names[$i], "image" => $images[$i], "genre" => $genres[$i], "info" => $info[$i], "videocode" => $videocode[$i]);
}
echo json_encode($arr);
Where each linkExtractor looks a bit like this - where it grabs all the text within a class videocode.
function linkExtractor6($html){
$doc = new DOMDocument();
$last = libxml_use_internal_errors(TRUE);
$doc->loadHTML($html);
libxml_use_internal_errors($last);
$xp = new DOMXPath($doc);
$result = array();
foreach ($xp->query("//*[contains(concat(' ', normalize-space(#class), ' '), ' videocode ')]") as $node)
$result[] = trim($node->textContent); // Just push the result here, don't assign it to a key (as that's why you're overwriting)
// Now return the array, rather than extracting keys from it
return $result;
}
I now want to do this instead with a database.
So I have tried to replace each linkExtractor with this - and obviously the connection:
function linkExtractor6($html){
$genre = mysqli_query($con,"SELECT genre
FROM entries
ORDER BY date DESC");
foreach ($genre as $node)
$result[] = $node;
return $result;
}
But I am getting the error:
Invalid argument supplied for foreach()
Avoid redundancy and run a single SELECT
function create_json_db($con){
$result = mysqli_query($con,"SELECT date, name, image, genre, info, videocode
FROM entries
ORDER BY date DESC");
$items= array();
while ($row = mysqli_fetch_assoc($result)) {
$items[] = $row;
}
return $items ;
}
Try to use this. More info in the official PHP documentation:
function linkExtractor6($html){
$result = mysqli_query($con,"SELECT genre
FROM entries
ORDER BY date DESC");
$items = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$items[] = $row;
}
return $items;
}
First, you are not iterating through your results via something like mysqli_fetch_array. So here is the function with mysqli_fetch_array in place. But there is a much larger issue. Read on.
function linkExtractor6($html){
$result = mysqli_query($con,"SELECT genre
FROM entries
ORDER BY date DESC");
$ret = array();
while ($row = mysqli_fetch_array($result)) {
$items[] = $row;
}
return $ret ;
}
Okay, with that done, it still won’t work. Why? Look at your function. Specifically this line:
$result = mysqli_query($con,"SELECT genre
But where is $con coming from? Without a database connection mysqli_query will not work at all. So if you somehow have $con set outside your function, you need to pass it into your function like this:
function linkExtractor6($con, $html){
So your full function would be:
function linkExtractor6($con, $html){
$result = mysqli_query($con,"SELECT genre
FROM entries
ORDER BY date DESC");
$ret = array();
while ($row = mysqli_fetch_array($result)) {
$items[] = $row;
}
return $ret ;
}
Remember, functions are self-contained & isolated from whatever happens outside of them unless you explicitly pass data into them.
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));
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