From a recent query I am getting this as the result.
[{"BeneficiaryID":"2"},{"BeneficiaryID":"3"},{"BeneficiaryID":"4"},{"BeneficiaryID":"6"}]
I want to use these ID values for another mysql query using Laravel. How can I just get only those numbers. Final result should be like [2,3,4,6]
$data = json_decode('[{"BeneficiaryID":"2"},{"BeneficiaryID":"3"},{"BeneficiaryID":"4"},{"BeneficiaryID":"6"}]');
$id_array = [];
foreach($data as $data) {
$id_array[] = $data->BeneficiaryID;
}
$query = Model::whereIn('column', $id_array)->get();
Related
I'm still new to this laravel, for now I'm facing a trouble for fetching data from the database. What i want to get is when there are only one data available, the second parameters won't be executed, but if there are some data available on the second parameters, then all the data from first parameter and the second parameter will be called.
$detail = Barang_Keluar_Detail::findOrFail($id); //15
$cariid = $detail->pluck('barang_keluar_id');
$instansiquery = Barang_Keluar::where('id',$cariid)->first(); //21
$instansiid = $instansiquery->pluck('instansi_id');
$tanggal = $instansiquery->pluck('tanggal')->first();//2019-12-31
and the parameter are here
$cariinstasama = Barang_Keluar::where('id', $cariid)
->orWhere(function ($query) use($instansiid, $tanggal) {
$query->where('tanggal', "'$tanggal'")
->where('instansi_id', $instansiid);
});
Please any help will be appreciated, thank you.
Laravel query builder provides elegant way to put conditional clause using when() . You can put conditional clause on your query like this:
$cariinstasama = Barang_Keluar::where('id', $cariid)
->when($instansiid, function ($query, $instansiid) {
return $query->where('instansi_id', $instansiid);
})
->when($tanggal, function ($query, $tanggal) {
return $query->where('tanggal', $tanggal);
})->get();
For more info see https://laravel.com/docs/5.8/queries#conditional-clauses
You can try this as well.
$cariinstasama = Barang_Keluar::where('id', $cariid);
if($instansiid !== null)
{
$cariinstasama->where('instansi_id', $instansiid);
}
if($tanggal !== null)
{
$cariinstasama->where('instansi_id', $instansiid);
}
$result = $cariinstasama->get();
Its not clear what exactly you want.
Are you applying more than one parameter on the query if the first parameter result gives you more than one row in the database? If yes check out my approach :
$query = new Model(); // the model you want to query
if($query->where('col1', $param1)->count() > 1) // checks if the query from the 1st parameter produces more than one row in the database
$query = $query->where( // if yes apply more parameters to the query
[
['col1', $param1],
['col2', $param2]
]
);
else
$query = $query->where('col1', $param1);
$results = $query->get();
Hope it helps....
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
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.
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.
I'm looking to sort the results of a query in the controller, "after" it is returned from the model, here is what im trying:
$query = $this->user->get_all_users();
foreach($query as $user){
// dynamically according to my projects' logic
// assigns a grade to each user
$user->grade = assign_a_grade_to_user()
}
what im looking to do is , the results in $query should be sorted according to the grade a student has , and then pass that sorted $query to my view to print
any suggestions or idea to get this ?
NOTE : no issues if we use another temporary variables or data structures like we can store the sorted results in some other variable too
This should do:
function cmp( $a, $b )
{
if( $a->grade== $b->grade){ return 0 ; }
return ($a->grade< $b->grade) ? -1 : 1;
}
$sortedArray=usort($query ,'cmp');
So your code should look like:
$query = $this->user->get_all_users();
foreach($query as $user){
// assigns a grade to each user
$user->grade = assign_a_grade_to_user()
}
$sortedArray=usort($query ,'cmp');
$data['users']=$query;
$this->load->view('home',$data);