I have this function in Code igniter PHP where I am trying to get all rows from the database that match a input value.
How should I change the code to get all rows that match my search criteria?
Thank you
Model search function:
function findquestion($searchvalue){
$this->db->where('answer1', $searchvalue);
$res = $this->db->get('questions');
$count = $res->num_rows();
if($res->num_rows()==0){
return "...";
}
$moviearray = $res->row_array();
return $moviearray;
}
Controller Function:
public function getdatabasedata()
{
if($this->input->server('REQUEST_METHOD') == 'GET')
{
$year = $this->input->get('searchvalue');
if($year != ''){
$movie = $this->adminmodel->findquestion($year);
echo json_encode($movie);
}
}
}
When I look at Postman to check what the JSON object holds, this is what I get. But in fact I have three more rows in my database that match my search criteria.
{
"id": "10",
"question": "test questions",
"image": "test image",
"answer1": "answer1",
"answer2": "answer2",
"answer3": "answer3",
"answer4": "answer4"
}
function findquestion($searchvalue){
1) define array.
$data = array();
$this->db->where('answer1', $searchvalue);
$res = $this->db->get('questions');
if($res->num_rows()==0){
return "...";
}
2) loop trough results and store in array.
foreach ($res->result() as $row)
{
$data[] = array(
'id' => $row->id,
'question' => $row->question,
'image' => $row->image,
'answer1' => $row->answer1,
'answer2' => $row->answer2,
'answer3' => $row->answer3,
'answer4' => $row->answer4
);
}
//$moviearray = $res->row_array();
return $data;
}
Related
Is it possible to repeat a function when it has finished. For Example: I have a function for export mysql to json file with a limit of 100 data. if it is successful create a json file with 100 data. Then it will repeat the same function to create json file 100 more data (no duplicate data) until the data runs out.
my code for generate json file :
$results = $db->SELECT()
->FROM( array( 'MM'=>'M_MEMBER'),
array( 'MEMBER_ID' => 'MM.MEMBER_ID',
'FIRST_NAME' => 'MM.FIRST_NAME',
'LAST_NAME' => 'MM.LAST_NAME',
'MEMBER_GROUP' => 'MM.MEMBER_GROUP',
'MEMBER_GROUP1' => 'MM.MEMBER_GROUP1',
'PHONE_NUMBER' => 'MM.PHONE_NUMBER',
'MEMBERSHIP' => 'MM.MEMBERSHIP',
'UPLOAD_DATE' => 'MM.UPLOAD_DATE',
'STATUS' => 'MM.STATUS'
)
)
->WHERE('DATE(MM.UPLOAD_DATE) = CURDATE()')
->WHERE('SYNC_FLAG = ?','N')
->LIMIT(100)
->QUERY()->FETCHALL();
if (!empty($results) && $results['SYNC_FLAG'] != 'Y')
{
$counter = formatNbr($counterFile);
$data = array();
foreach ($results as $key=>$row) {
$data[$key] = $row;
$data[$key]['_id'] = (string) Application_Helper_General::generateIdJsonFile();
$queryUdateMemberFlag = 'UPDATE M_MEMBER SET SYNC_FLAG = "Y" WHERE MEMBER_ID = '.$row['MEMBER_ID'].'';
$db->query($queryUdateMemberFlag);
}
$out = array_values($data);
$jsonAr = json_encode($out);
$json = substr($jsonAr, 1, -1);
$jsonData = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json);
$file = $store_path_pos.'dataMember_'.date('Y-m-d').'_'.$counter.'.json';
$createJson = file_put_contents($file, $jsonData);
if($createJson){
echo "Create Json File Success In :".$file;
}else{
echo "Create Json Failed";
}
}
the code can only generate a json file once, how can it be repeated after generating a successful json file
note: I added a flag for each successful data generated json file
You can extract your codes to a function and use the function in the loop.
Example:
function exporter($limit = 100)
{
$results = $db->SELECT()
->FROM( array( 'MM'=>'M_MEMBER'),
array( 'MEMBER_ID' => 'MM.MEMBER_ID',
'FIRST_NAME' => 'MM.FIRST_NAME',
'LAST_NAME' => 'MM.LAST_NAME',
'MEMBER_GROUP' => 'MM.MEMBER_GROUP',
'MEMBER_GROUP1' => 'MM.MEMBER_GROUP1',
'PHONE_NUMBER' => 'MM.PHONE_NUMBER',
'MEMBERSHIP' => 'MM.MEMBERSHIP',
'UPLOAD_DATE' => 'MM.UPLOAD_DATE',
'STATUS' => 'MM.STATUS'
)
)
->WHERE('DATE(MM.UPLOAD_DATE) = CURDATE()')
->WHERE('SYNC_FLAG = ?','N')
->LIMIT($limit)
->QUERY()->FETCHALL();
if (!empty($results) && $results['SYNC_FLAG'] != 'Y')
{
$counter = formatNbr($counterFile);
$data = array();
foreach ($results as $key=>$row) {
$data[$key] = $row;
$data[$key]['_id'] = (string) Application_Helper_General::generateIdJsonFile();
$queryUdateMemberFlag = 'UPDATE M_MEMBER SET SYNC_FLAG = "Y" WHERE MEMBER_ID = '.$row['MEMBER_ID'].'';
$db->query($queryUdateMemberFlag);
}
$out = array_values($data);
$jsonAr = json_encode($out);
$json = substr($jsonAr, 1, -1);
$jsonData = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json);
$file = $store_path_pos.'dataMember_'.date('Y-m-d').'_'.$counter.'.json';
$createJson = file_put_contents($file, $jsonData);
if($createJson) {
echo "Create Json File Success In :".$file;
} else {
echo "Create Json Failed";
}
}
$numberOfRows = 10000; # use the count query here
$limit = 100;
while($numberOfRows > 0) {
exporter($limit);
$numberOfRows -= $limit;
}
Also, you can call your function in your function recursively (https://www.w3schools.blog/php-recursive-functions)
Putting the existing code in a loop seems like the obvious answer here.
do {
$results = $db
->SELECT()
->FROM(
['MM'=>'M_MEMBER'],
[
'MEMBER_ID' => 'MM.MEMBER_ID',
'FIRST_NAME' => 'MM.FIRST_NAME',
'LAST_NAME' => 'MM.LAST_NAME',
'MEMBER_GROUP' => 'MM.MEMBER_GROUP',
'MEMBER_GROUP1' => 'MM.MEMBER_GROUP1',
'PHONE_NUMBER' => 'MM.PHONE_NUMBER',
'MEMBERSHIP' => 'MM.MEMBERSHIP',
'UPLOAD_DATE' => 'MM.UPLOAD_DATE',
'STATUS' => 'MM.STATUS',
]
)
->WHERE('DATE(MM.UPLOAD_DATE) = CURDATE()')
->WHERE('SYNC_FLAG = ?','N')
->LIMIT(100)
->QUERY()
->FETCHALL();
if (count($results) === 0) {
break;
}
$data = [];
foreach ($results as $row) {
$row['_id'] = (string) Application_Helper_General::generateIdJsonFile();
$data[] = $row;
//
// this is UNSAFE and inefficient, use a prepared statement if possible
//
$queryUdateMemberFlag = 'UPDATE M_MEMBER SET SYNC_FLAG = "Y" WHERE MEMBER_ID = '.$row['MEMBER_ID'].'';
$db->query($queryUdateMemberFlag);
}
$json = json_encode($out);
$filename = sprintf(
"%sdataMember_%s_%s.json",
$store_path_pos,
date("Y-m-d"),
formatNbr($counterFile)
);
if ($json && file_put_contents($filename, $json)) {
echo "Create Json File Success In $file";
} else {
echo "Create Json Failed";
}
} while (true);
I fixed a few inefficiencies in your code; I have no idea what DB library you're using but as a rule you should never inject variables into an SQL query. It's likely safe in this context, but if your library allows you should prepare the statement outside the loop and execute it inside the loop for better performance.
Before I begin, I have looked through other examples and Q&A's on multiple platforms but none of them seem to solve my problem. I am trying to return multiple rows from MySQL via a json. However, I have been unable to. The code below shows my attempt.
I get my responses via Postman. The first while returns only the last entry in the database, and the do-while returns all entries but doesn't encode the json properly, as the json outputs syntax error but the html part shows all entries.
<?php
$dashboard_content_token = $_REQUEST["dashboard_content_token"];
$token = "g4";
require(cc_scripts/connect.php);
$sql = "SELECT * FROM `dashboard_content`";
$check = strcmp("$token", "$dashboard_content_token");
$statement = mysqli_query($con, $sql);
if (check) {
$rows = mysqli_fetch_assoc($statement);
if (!$rows) {
echo "No results!";
} else {
while ($rows = mysqli_fetch_assoc($statement)) {
$news_id = $rows['news_id'];
$image_url = $rows['image_url'];
$news_title = $rows['news_title'];
$news_description = $rows['news_description'];
$news_article = $rows['news_article'];
$result['dashboard content: '][] = array('news_id' => $news_id, 'image_url' => $image_url, 'news_title' => $news_title, 'news_description' => $news_description, 'news_article' => $news_article);
echo json_encode($result);
}
// do {
// $news_id = $rows['news_id'];
// $image_url = $rows['image_url'];
// $news_title = $rows['news_title'];
// $news_description = $rows['news_description'];
// $news_article = $rows['news_article'];
// $result['dashboard content: '][] = array('news_id' => $news_id, 'image_url' => $image_url, 'news_title' => $news_title, 'news_description' => $news_description, 'news_article' => $news_article);
// echo json_encode($result);
// } while ($rows = mysqli_fetch_assoc($statement));
mysqli_free_result($statement);
}
}
?>
This should work. You'll want to use the do...while statement otherwise the first result is skipped.
<?php
$dashboard_content_token = $_REQUEST["dashboard_content_token"];
$token = "g4";
require(cc_scripts/connect.php);
$sql = "SELECT * FROM `dashboard_content`";
$check = strcmp("$token", "$dashboard_content_token");
$statement = mysqli_query($con, $sql);
if (check) {
$rows = mysqli_fetch_assoc($statement);
if (!$rows) {
echo "No results!";
} else {
do {
$news_id = $rows['news_id'];
$image_url = $rows['image_url'];
$news_title = $rows['news_title'];
$news_description = $rows['news_description'];
$news_article = $rows['news_article'];
$result['dashboard content: '][] = array('news_id' => $news_id, 'image_url' => $image_url, 'news_title' => $news_title, 'news_description' => $news_description, 'news_article' => $news_article);
} while ($rows = mysqli_fetch_assoc($statement));
mysqli_free_result($statement);
echo json_encode($result);
}
}
?>
The key is to put all of you results into an array and then just do one json_encode(). When you call json_encode() multiple times, your API will return invalid json.
In your while loop,
$result['dashboard content: '] = array('news_id' => $news_id, 'image_url' => $image_url, 'news_title' => $news_title, 'news_description' => $news_description, 'news_article' => $news_article);
just over-writes the same "dashboard content" entry in the $result array every time you run the loop. This is why you only see the last entry.
Doing json_encode() within the loop makes no sense as well, because you'll just output multiple, disconnected individual JSON objects, which are not part of an array or coherent structure. This doesn't make for a valid JSON response.
It's not abundantly clear exactly what output structure you're hoping for, but this might give you either a solution, or at least a shove in the right direction:
$statement = mysqli_query($con, $sql);
$result = array("dashboard_content" => array()); //create an associative array with a property called "dashboard_content", which is an array. (json_encode will convert an associative array to a JSON object)
if (check) {
$rows = mysqli_fetch_assoc($statement);
if (!$rows) {
echo "No results!";
} else {
while ($rows = mysqli_fetch_assoc($statement)) {
$news_id = $rows['news_id'];
$image_url = $rows['image_url'];
$news_title = $rows['news_title'];
$news_description = $rows['news_description'];
$news_article = $rows['news_article'];
//append the current data to a new entry in the "dashboard_content" array
$result["dashboard_content"][] = array('news_id' => $news_id, 'image_url' => $image_url, 'news_title' => $news_title, 'news_description' => $news_description, 'news_article' => $news_article);
}
}
//now, output the whole completed result to one single, coherent, valid JSON array.
echo json_encode($result);
You should end up with some JSON like this:
{
"dashboard_content": [
{
"news_id": 1,
"image_url": "abc",
"news_title": "xyz",
//...etc
},
{
"news_id": 2,
"image_url": "def",
"news_title": "pqr",
//...etc
},
//...etc
]
}
As you can see in the JSON file, this looks not so necessary.
I get values from input-s and add it to the array and send it via AJAX. A simple array I know how to convert, but a multidimensional one is not. Can eat what that function? I tried to create an array with "keys", but there is a lot of trouble, I never reached the end , and I'm sure it's not right. Tell me what you can do.
i want this
{
"user1" : {
first_name":"Michael",
"last_name":"Podlevskykh",
"phones" : {
"phone_1":"5345",
"phone_2":"345345",
"phone_3":"123"
}
}
}
//this is what i see
JSON
[
{"first_name":"Michael"},
{"last_name":"Podlevskykh"},
[{"phone_1":"5345"},
{"phone_2":"345345"},
{"phone_3":"0991215078"}
]
]
PHP
//[["5345", "345345", "123"], "Michael", "Podlevskykh"]
$userInfo = (json_decode($_POST["phones"], true));
$namePhones = ["phone_1", "phone_2", "phone_3"];
$nameUser = ["first_name", "last_name"];
$jsonPhones = $userInfo;
$nameLName = $userInfo;
$jsonPhones = array_splice($jsonPhones, 0, 1);
$nameLName = array_splice($nameLName, -2);
foreach ($jsonPhones[0] as $key => $value) {
$phones[] = array($namePhones[$key] => $jsonPhones[0][$key]);
}
foreach ($nameLName as $key => $value) {
$usersName[] = array($nameUser[$key] => $nameLName[$key]);
}
array_push($usersName, $phones);
echo "<pre>";
echo json_encode($usersName);
//[
// {"first_name":"Michael"},{"last_name":"Podlevskykh"},
// [{"phone_1":"5345"},{"phone_2":"345345"},{"phone_3":"123"}]
//]
I don't get all the complications, I would do something like this if I'm sure the $input format is the same:
<?php
$input = '[["5345", "345345", "123"], "Michael", "Podlevskykh"]';
$input = json_decode($input, true);
$output = [
'user1' => [
'first_name' => $input[1],
'last_name' => $input[2],
'phones' => [
'phone_1' => $input[0][0],
'phone_2' => $input[0][1],
'phone_3' => $input[0][2]
]
]
];
echo '<pre>';
echo json_encode($output);
If you want an object as output, you need to create an object:
$userInfo = (json_decode($_POST["phones"], true));
$namePhones = ["phone_1", "phone_2", "phone_3"];
$nameUser = ["first_name", "last_name"];
$jsonPhones = $userInfo;
$nameLName = $userInfo;
$jsonPhones = array_splice($jsonPhones, 0, 1);
$nameLName = array_splice($nameLName, -2);
$user = new stdClass();
foreach ($nameLName as $key => $value) {
$user->{$nameUser[$key]} = $nameLName[$key];
}
$phones = new stdClass();
foreach ($jsonPhones[0] as $key => $value) {
$phones->{$namePhones[$key]} = $jsonPhones[0][$key];
}
$user->phones = $phones;
$users = new stdClass();
$users->user1 = $user;
echo json_encode($users);
Output:
{"user1": {
"first_name":"Michael",
"last_name":"Podlevskykh",
"phones":{
"phone_1":"5345",
"phone_2":"345345",
"phone_3":"123"
}
}
}
I'm fairly new to Json and arrays and I'm just wondering whether someone can correct the code I've tried that is still outputting an invalid string.
$json = array(
'posts' => array(),
);
while($row = mysqli_fetch_array($result)) {
$posts = array();
$posts['count'] = $rowcount;
$posts['streamitem_id'] = $row['streamitem_id'];
$json['posts'] = $posts;
echo json_encode($json);
}
I have used http://jsonlint.com/ and posted my returned data from firebug errors on lines 6,11 and 16
} {
{
"posts": {
"count": 4,
"streamitem_id": "1976"
}
} {
"posts": {
"count": 4,
"streamitem_id": "1980"
}
} {
"posts": {
"count": 4,
"streamitem_id": "1099"
}
} {
"posts": {
"count": 4,
"streamitem_id": "1178"
}
}
Some have already commented with a valid answer however, I believe array_push is the most efficient method rather than redefining the $posts variable over and over.
$json = array(
'posts' => array()
);
while($row = mysqli_fetch_array($result)) {
array_push($json['posts'], $array(
'count' => $rowcount,
'streamitem_id' => $row['streamitem_id']
)
);
}
echo json_encode($json);
PS: I noticed that you're putting $rowcount in each post array. If this is not intended, I recommend the following change:
$json = array(
'posts' => array(),
'count' => $rowcount
);
And then in the while loop:
array_push($json['posts'], $array(
'streamitem_id' => $row['streamitem_id']
)
);
This way, you can reference the post count and it won't be a waste of memory.
console.log(json['count']);
I think you want this:
$posts = array();
$rowcount = 0;
while ($row = mysqli_fetch_array($result)) {
$posts[] = array(
'count' => $rowcount,
'streamitem_id' = $row['streamitem_id'],
);
$rowcount++;
}
$json['posts'] = $posts;
echo json_encode($json);
Put this outside of loop, you are overwriting and echoing each value instead whole at once
Inside loop
$posts[] = ["count"=> $rowcount,"streamitem_id"=>$row['streamitem_id']);
After loop
$json['posts'] = $posts;
echo json_encode($json);
I want to send nested JSON array.Which contain following format.
${"posts":[{
"abc":"123",
"xyz":"123",
"pro":[{
"name":"Brinjal",
"qty":"500 gms"
},
{
"name":"Brinjal",
"qty":"500 gms"
}]
}]
}
Here is my php code:
$rows = $stmt->fetchAll();
if ($rows) {
$order["posts"] = array();
foreach ($rows as $row) {
$post = array();
$post["order_id"] = $row["order_id"];
$post["order_totalamount"] = $row["order_totalamount"];
$post["address"] = $row["address"];
$post["pincode"] = $row["pincode"];
$post["delivery_timeslot"] = $row["delivery_timeslot"];
$post["order_date"] = $row["order_date"];
$query1= "query";
$rows1 = $stmt->fetchAll();
if ($rows1) {
foreach ($rows1 as $row1) {
$query2= "query";
$rows2 = $stmt->fetchAll();
$post["product"] = array();
if ($rows2) {
$products = array();
foreach ($rows2 as $row2) {
$products["product_name"]=$row2["product_name"];
$products["prod_qty"] = $row2["product_minquantity"];
}
array_push($post["product"],$products);
echo json_encode($products);
}
}
}
array_push($order["posts"], $post);
}
echo json_encode($order);
}
From above code I got result:
$ {"posts":
[{
"order_id":"18",
"order_totalamount":"40",
"address":"2, Chetan Society, Vadodara",
"pincode":"390023",
"delivery_timeslot":"Zone wise delivery",
"order_date":"2016-03-18 17:50:53",
"product":[{"product_name":"Brinjal","prod_qty":"500 gms"}]
}]
}
But my actual product array is:
${"product_name":"Banana","prod_qty":"1 Kg"}{"product_name":"Brinjal","prod_qty":"500 gms"}
Kindly help out. I am stuck on it. tried a lot but did not get success.
In
foreach ($rows2 as $row2) {
$products["product_name"]=$row2["product_name"];
$products["prod_qty"] = $row2["product_minquantity"];
}
You overwrite $products["product_name"]and $products["prod_qty"] with the values of the last $row2.
The line {"product_name":"Banana","prod_qty":"1 Kg"}{"product_name":"Brinjal","prod_qty":"500 gms"} actually consists of two echo's:
{"product_name":"Banana","prod_qty":"1 Kg"}
{"product_name":"Brinjal","prod_qty":"500 gms"}
But you don't see the difference. I suggest echoing a string in-between them or use something like var_dump() to see how many values you're echoing.
You should do something like:
for ($i = 0; $i < count($rows2); $i++) {
$products[$i]["product_name"]=$rows2[$i]["product_name"];
$products[$i]["prod_qty"] = $rows2[$i]["product_minquantity"];
}
This will result in: [{"product_name":"Banana","prod_qty":"1 Kg"},{"product_name":"Brinjal","prod_qty":"500 gms"}]
FYI $array[] = has the same rsults as array_push(), but had less overhead of calling array_push().
EDIT:
Below a complete example since it doesn't seem to workout for you:
//Demo $order
$order = array (
'posts' =>
array (
0 =>
array (
'order_id' => '18',
'order_totalamount' => '40',
'address' => '2, Chetan Society, Vadodara',
'pincode' => '390023',
'delivery_timeslot' => 'Zone wise delivery',
'order_date' => '2016-03-18 17:50:53',
),
),
);
//Demo $rows2
$rows2 = array(
array(
'product_name' => 'banana',
'product_minquantity' => '1 Kg'
),
array(
'product_name' => 'Brinjal',
'product_minquantity' => '500 gms'
)
);
$post['product'] = array();
if ($rows2) {
$products = array();
for ($i = 0; $i < count($rows2); $i++) {
$products[$i]['product_name'] = $rows2[$i]['product_name'];
$products[$i]['prod_qty'] = $rows2[$i]['product_minquantity'];
}
$post['product'] = $products;
echo json_encode($products); //[{"product_name":"banana","prod_qty":"1 Kg"},{"product_name":"Brinjal","prod_qty":"500 gms"}]
}
//$order['posts'][] = $post;
$order['posts'][0] = $order['posts'][0] + $post;
//In this example I only have 1 item in $order['posts'] so I know to add to key 0.
//In your case you need to know which key of $rows1 you need to do the adding.
//Change the foreach loop of $rows to a for loop as well so you can define your own keynames ($i).
echo '<br>==================================================================<br>';
echo json_encode($order);
/*
{
"posts":[
{
"order_id":"18",
"order_totalamount":"40",
"address":"2, Chetan Society, Vadodara",
"pincode":"390023",
"delivery_timeslot":"Zone wise delivery",
"order_date":"2016-03-18 17:50:53",
"product":[
{
"product_name":"banana",
"prod_qty":"1 Kg"
},
{
"product_name":"Brinjal",
"prod_qty":"500 gms"
}
]
}
]
}
*/