I have this raw query that extracts data from the database table in Laravel
$username = DB::table('hotspot_users')
->select('userName')
->where('assignedTo', '786')->get();
I get these values: [{"userName":"kim"}]
but I want to extract just the username "kim" itself, not an array. I have tried to do this without success:
$convert1=json_decode($username);
$newusername=$convert1->userName;
but i get an error: Trying to get property 'userName' of non-object
Any idea how I can solve this
Instead of what you're doing, you can just do this:
HotspotUser::where('assignedTo', 786)->pluck('userName');
Now you will have a collection of names; or if you only want the first one:
HotspotUser::where('assignedTo', 786)->first()->user_name;
(I'm not certain if the property will be user_name or userName; you should have simple column names to make things easier.)
You are getting the result of DB as php stdClass object, so you can iterate over it and get every variable that is queried. Something like below code may help you.
In case of using get()
$data = DB::table('hotspot_users')
->where('assignedTo', '786')->select('userName')->get();
foreach ($data as $datum) {
$result[] = $datum->userName;
}
In case of using first()
$data = DB::table('hotspot_users')
->where('assignedTo', '786')->select('userName')->first()->userName;
Hi As you mentioned that is an array [{"userName":"kim"}]
So you have two choices
First , you first insted of get
$username = DB::table('hotspot_users')
->select('userName')
->where('assignedTo', '786')->first();
$newusername=$convert1->userName;
Second , get the first element of array
$username = DB::table('hotspot_users')
->select('userName')
->where('assignedTo', '786')->get();
$username = reset($username);
$convert1=json_decode($username);
$newusername=$convert1['userName'];
Related
I generate chart using jpgraph. I succesfully get data for the plot from database and i want the title also take from database. i already use this script
$sql = $this->db->select("title from table")->get()->first_row();
$title = $sql->title;
$graph->title->Set($title);
But that not work. can anyone solve this issue? thank you
This will help to get first_row along with field:
$this->db->select('title'); // your column
$this->db->from('table'); // your table
$result = $this->db->get()->result(); // get result
$title = $result->first_row()->title; // get ist row using first_row with your field name
$graph->title->Set($title); // as you are using for graph
Also note that, in CI function row() also return the ist row of your query in object form.
From the manual:
You can walk forward/backwards/first/last through your results using
these variations:
$row = $query->first_row()
$row = $query->last_row()
$row = $query->next_row()
$row = $query->previous_row()
Or if you want to print result in array instead of object than you can use a word 'array' as param, like:
$query->first_row(‘array’)
You can also follow the CI manual for better understanding: http://www.codeigniter.com/userguide3/database/results.html
I use create command of Yii as
$sql = "select name from users where id = 2";
$EmployeeName=Yii::app()->db->createCommand($sql)->queryAll();
now i have to use foreachloop to get specific value like
foreach($EmployeeName as $value)
$name = $value['name'];
Can i bypass foreach loop like
$EmployeeName -> name; //To get value of specific field
Question is why i use foreach loop when i know i have single index array?
when i am using print_r($EmployeeName) its showing me sql command in object instead of data so i am confused how to debug object array
Assuming id is your primary key, you should use queryScalar instead. This will return a single value and not an array.
$name=Yii::app()->db->createCommand($sql)->queryScalar();
You can use this syntax in Yii:
$user = Users::model()->findByAttributes(array('id' => 2));
$name = $user->name;
echo $name;
Single line solution
The simplest approach is find by primary key (PK).
Suppose id is PK in the Users model (Users model should be set thru gii model generator):
$name = Users::model()->findByPk(2)->name;
I have a problem here in NotORM code.
This code are working well:
$select = $db->pspaym->select("COUNT(*)")->where("F4","$textdate")->fetch();
$count = count($select);
But this code here does not working:
$select = $db->pssale->select("COUNT(*)")->where("F8","$textdate")->fetch();
$count = count($select);
This code have an error message said:
"Trying to get property of non-object"
cannot resolve this problem.
all variables are not null.
thanks.
if you want to count lines in a table, simply use:
$select = $db->pspaym->where("F4","$textdate");
$count = count($select);
The problem comes from your combination of fetch() and count() methods. Because of the ending fetch call, $select doesn't contain a Table object, but a Record object.
So count($select) will count the number of columns in your record. Normally, it should always returns 1 (because one field in the returned record).
For your information, if you want to be uselessly explicit, you may do something like this.
$record = $db->pspaym("F4","$textdate")->select("COUNT(*) AS c")->fetch();
$count = $record['c'];
But, that's the long way.
I'm trying to enter 100 email addresses separated by ';' and store them in MySql table. What I've tried so far is:
$recipient_raw = $this->input->post('recipient'); //get the 100 emails in $recipient_raw
$recipient_array=explode(';', $recipient_raw); //explode them into an array
$title = $this->input->post('title');
$body = $this->input->post('body');
foreach($recipient_array->result() as $row):
$recipient=array(
'email'=>$row->email //looping through each email; seems I should not use $row->email since there's no title for them
);
$this->db->insert('eamil_send',$this->db->escape($recipient));
endforeach;
I'm running this on CodeIgniter PHP. Error msg is on line foreach($recipient_array->result() as $row):, where it says: Call to a member function result() on a non-object
Any advice is appreciated! Thanks!
result(), is an active record function for converting a database result object. You are creating a standard array.
$batch = array();
foreach($recipient as $row){
$batch[] = array(
'email' => $row
);
}
$this->db->insert_batch('email_send', $batch);
That should do what you're trying to accomplish.
The error message is pretty much self explanatory..
In the 2nd line of your code you declared $recipient_array as an Array(), not an object. So, there's no "result" method available.
Your loop should be
foreach($recipient_array as $row)
On a side note, you probably shouldn't be executing db operations inside a loop (especially, for 100 operations!). Instead, you should save all the queries in one big query string and execute at the end.
If you want your 100 email address be separate by ',' you should use implode(glue, pieces) instead of explode() function. Like on email address that you want to insert.
$recipient_raw = array();
$recipient_raw[] = $this->input->post('recipient');
foreach ($recipient_raw as $value) {
$tem_arr = implode(',', $value);
}
$this->db->insert('eamil_send',$this->db->escape($tem_arr));
I have written this code which in theory i want to loop round an array and for every value use in a select statement to retrieve the applicable information. Then map a particular value id as a key and the value from the sql statement as its associated value. Though i cant seem to figure out how to add it as a value into my array im sure im a word out.
heres my code
/*
* Loop through the hasNewModelIdInYear and retrieve the exterior media paths
* with a mapped id as a key.
*/
$mediapatharray = array();
foreach ($hasNewModelIdInYear as $key => $value) {
$selectMediaPathFromValue = "SELECT `name` FROM `media` WHERE `id`='".$value['img1_media_id']."'";
$res = $mysqli->query($selectMediaPathFromValue);
$mediapatharray[$value['model_id']] = $res;
}
All that array returns is an array full of keys but no values.. With the variable $res do i then have to ->fetch_value? as im not sure on the syntax needed in order to access the data from the query?
regards mike
it is not good writing whan you have query inside loop. you should search based on array of img1_media_id
you can do follwing
$selectMediaPathFromValue = "SELECT `name` FROM `media`
WHERE `id` IN = '$hasNewModelIdInYear'";
array should be following format
$hasNewModelIdInYear = "12,21,22,65";
The result will return false on failure or the results on success. Mysqli result will be returned the first set of array that consist of the array index. You will need to fetch the values and store it in array. Try adding this code.
while($row = $res->fetch_assoc()){
$mediapatharray[$value['model_id']] = $row['name'];
}
Thanks for your responses i was trying to make it more complicated than it needed to be. I done it by putting the whole media table in a multidimension array then looping through them both and comparing values and if mathcing id map the name.
simple connection and sql query to populate the array, then map the id to a key and name as its value. heres my code.
mediaarray is an array with the media table contents populated in it
$mediaIdPAthFromOld = array();
foreach ($hasNewModelIdInYear as $hnkey => $hsvalue) {
foreach ($mediaarray as $mpavalue) {
if ($hsvalue['img1_media_id'] == $mpavalue['id']) {
$mediaIdPAthFromOld[$hsvalue['model_id']] = $mpavalue['name'];
}
}
}
though this has done what i wanted i assume there is a more effient way to do this.
regards mike