laravel how to handle empty json results set from a query - json

I am very new to the laravel framework and i have what it seems to be a simple question. I have a query like so
$query['query2']= DB::connection('test')->select(
"select * from cities");
...
...
echo json_encode($q);
Sometimes this particular query returns an empty result set.
How do I handle this? Lets say I want to add my own json response when its empty.
Thanks

Try the following
$dataToSend = $q->get(); // $q being your query
if($dataToSend->isEmpty())
{
echo json_encode(['something'=>'else']);
}
else
{
echo json_encode($dataToSend);
}
Or in a shorter fashion
$dataToSend = $q->get(); // $q being your query
echo json_encode($dataToSend->isEmpty()? ['something'=>'else'] : $dataToSend);

Related

codeigniter 3 $query = $this->db->query($queri_str); return 0 result

Good morning,
I have a problem with mysql and coeigniter 3.
if I request data with
$ query = $ this-> db-> query ($ queri_str);
it does not give me results.
if I enter the query on phpmyadmin it shows me two results.
$ queri_str = 'SELECT * FROM `my_table` WHERE` id_mytable2` = "'. $ id_name. '"';
The database tables were created with mysql workbench and automatically the reference to the main table with a 1: n ratio was added
Try this query
$this->db->select('*');
$this->db->where('id', '58e5j0m5bqrs7hk8suokko28hj7ni0v6');
$result = $this->db->get('ci_sessions')->result_array();
print_r($result);
Try this solution, you want to do a normal select,I don't know the query your wrote but
public fucntion get_data($id){
$this->db->select('*');
$this->db->from('your_table');
$this->db->where('id','=' ,'$id');
$query = $this->db->get();
$data = $query->result_array();
return $data;
}
the problem is back.
I'll explain.
function myfunction($id_myname) {
$this->db->select('*');
$this->db->where('id_myname', $id_myname);
//$query = $this->db->get('my_table');
$query = $this->db->get('my_table');
//print_r($query);
//var_dump($query);
if ( !$query ){
$error = $this->db->error(); // Has keys 'code' and 'message'
}
return $query->result();
}
when I call this function an empty value comes back to me.
While if I enter the value of the query in phpmyadmin I find two values

DB Query on returning one value Laravel

Im using a simple query to pull the users in a table called users.
$users = DB::table('users')->get();
Then using a foreach loop to get the values , for example :
foreach ($users as $user)
{
return $user->email;
}
There is definitely 2 records in the DB Table, but it only returns one line. If i try to query a different table it does the same thing.
If i use the Query Log between the query
DB::enableQueryLog();
$users = DB::table('users')->get();
$result = DB::getQueryLog();
It returns the query and it looks fine
[{"query":"select * from `users`","bindings":[],"time":0.85}]
This table was created within PhpMyAdmin and not using the Artisan Migrate
Of course it so, cause you return from loop, use echo
foreach ($users as $user)
{
echo $user->email;
}
return statement inside the loop will behave like break for your case, this means breaking the loop.
You can use either:
DB::table('users')->select(['email'])->get();
or
DB::table('users')->get(['email']);
But its basics, you can easily find this stuff in docs https://laravel.com/docs/master/

mySQL query for building dynamically populated model

I have some code below which demonstrates a hard-coded example of what I would like to accomplish dynamically.
At a high level, I wish to do something like select * from view_data_$app_state and then get all of the data from that views table into my mustache templates dynamically.
The code I currently must use to group multiple rows of data for a specific column along with the views data is:
<?php
error_reporting(E_ALL);
class Example {
function __construct(){
try {
$this->db = new PDO('mysql:host=localhost;dbname=Example', 'root','drowssap');
}
catch (PDOException $e) {
print($e->getMessage());
die();
}
}
function __destruct(){
$this->db = null;
}
function string_to_array($links_string){
return explode(",", $links_string);
}
function get_view_data(){
$q = $this->db->prepare('select *, GROUP_CONCAT(`links`) as "links" from `view_data_global` ');
$q->execute();
$result = $q->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
}
$Example = new Example();
$result = $Example->get_view_data();
$result[0]["links"] = $Example->string_to_array($result[0]["links"]);
echo json_encode($result);
This gives me the perfect object while
GROUP_CONCAT seems to be doing the trick this way, however I MUST know the column name that will contain multiple rows before writing the query. I am trying to figure out an approach for this and wish to make a custom query + code example that will transform cols with multiple rows of null null and not empty data into an array like above - but return the data.. again like the code above.
Below is an output of the actual data:
[{"id":"1","title":"This is the title test","links":["main","about","store"]}];
How can I replicate this process dynamically on each view table?
Thank you so much SO!
You can use PDOStatement::fetch to retrieve your results, with fetch_style set to PDO::FETCH_ASSOC (some other values will also provide the same information). In this case, the result set will be array indexed by column name. You can access this information with foreach (array_expression as $key => $value)
See the documentation for additional information.

How to get array format data from json data in laravel4 query builder?

I am using laravel4 query builder . I have following query which returns json data .
$query=DB::connection('mysqlMagento')->
table('magento_catalog_category_flat_store_1')->
join('sohyper_region_activity', 'magento_catalog_category_flat_store_1.entity_id', '=', 'sohyper_region_activity.activity_id')->
select("magento_catalog_category_flat_store_1.entity_id" , "magento_catalog_category_flat_store_1.parent_id" , "magento_catalog_category_flat_store_1.name as label" ,"magento_catalog_category_flat_store_1.url_key as name")->
get();
The above query returns json format data , I want to convert this to arrat format . I know Toarray() is used in eloquent to convert this but here it is in query builder , please help me on this .
Thanks.
$query=DB::connection('mysqlMagento')->
table('magento_catalog_category_flat_store_1')->
join('sohyper_region_activity', 'magento_catalog_category_flat_store_1.entity_id', '=', 'sohyper_region_activity.activity_id')->
select("magento_catalog_category_flat_store_1.entity_id" , "magento_catalog_category_flat_store_1.parent_id" , "magento_catalog_category_flat_store_1.name as label" ,"magento_catalog_category_flat_store_1.url_key as name")->
get();
$array = json_decode($query);
Though i'm fairly sure that the query builder is not returning JSON.
The query builder returns an array of objects. For example the query:
$users = DB::table('users')->select('name')->get();
will return an array which you can handle like this
foreach($users as $user) {
echo $user->name;
}
EDIT
If you want to convert it to array you have to do it on your own.
Here is a quick way
$users = json_decode(json_encode($users), true);
Now you can handle it like this
foreach($users as $user) {
echo $user['name'];
}

PHP PDO succinct mySQL SELECT object

Using PDO I have built a succinct object for retrieving rows from a database as a PHP object with the first column value being the name and the second column value being the desired value.
$sql = "SELECT * FROM `site`"; $site = array();
foreach($sodb->query($sql) as $sitefield){
$site[$sitefield['name']] = $sitefield['value'];
}
I now want to apply it to a function with 2 parameters, the first containing the table and the second containing any where clauses to then produce the same result.
function select($table,$condition){
$sql = "SELECT * FROM `$table`";
if($condition){
$sql .= " WHERE $condition";
}
foreach($sodb->query($sql) as $field){
return $table[$field['name']] = $field['value'];
}
}
The idea that this could be called something like this:
<?php select("options","class = 'apples'");?>
and then be used on page in the same format as the first method.
<?php echo $option['green'];?>
Giving me the value of the column named value that is in the same row as the value called 'green' in the column named field.
The problem of course is that the function will not return the foreach data like that. That is that this bit:
foreach($sodb->query($sql) as $field){
return $table[$field['name']] = $field['value'];
}
cannot return data like that.
Is there a way to make it?
Well, this:
$sql = "SELECT * FROM `site`"; $site = array();
foreach($sodb->query($sql) as $sitefield){
$site[$sitefield['name']] = $sitefield['value'];
}
Can easily become this:
$sql = "SELECT * FROM `site`";
$site = array();
foreach( $sodb->query($sql) as $row )
{
$site[] = $row;
}
print_r($site);
// or, where 0 is the index you want, etc.
echo $site[0]['name'];
So, you should be able to get a map of all of your columns into the multidimensional array $site.
Also, don't forget to sanitize your inputs before you dump them right into that query. One of the benefits of PDO is using placeholders to protect yourself from malicious users.