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;
Related
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'];
I have _Installation and Swipt_User classes in parse, the installation has UserR, which related to Swipt_User table as in the pic :
I have this query :
$query = new ParseQuery("_Installation");
$query->includeKey("Swipt_User");
$installations = $query->find(true);
included the object related to installation which is Swipt_User, but when i try to get the object in foreach, it didn't get it as below and returned as null
foreach ($installations as $key => $installation) {
$user = $installation->get('Swipt_User');
}
Any help ? .. please
You need to specify the name of the column, not the name of the related table (group), when using include.
Your code needs to be:
$query = new ParseQuery("_Installation");
$query->includeKey("userR");
$installations = $query->find(true);
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
I am using mysqli_fetch_assoc to get the database columns of one user (username, password, firstname, lastname ... ect).
I have these same columns as attributes in my user class. I was wondering if there is an easy way of mapping the values of the associated array to the object attributes everytime I call mysqli_fetch_assoc.
Something like this could work:
$user = mysql_fetch_assoc(...);
foreach($user as $key=>$value) {
$userObject->$key = $value;
}
Note the ->$key - this means to get the property referenced by the contents of the variable key.
Thank you #hjpotter92: mysqli_fetch_object() works perfectly, I just replaced my
$user = mysqli_fetch_assoc($user_set)
with
$user = mysqli_fetch_object($user_set)
I was talking to a person today who mentioned he used arrays when calling parameters or for other reasons when pulling data from the database etc.
Basically my question is: how would you use arrays in web development?
For example:
If you had a url like this (a social dating site)
http://www.example.com/page.php?sid=1&agefrom=30&ageto=40&sex=female&loccation=los angeles
How I would query the browse page (when showing a list of users) is
$id = mysql_real_escape_string($_GET['id']);
$agefrom = mysql_real_escape_string($_GET['agefrom']);
$ageto = mysql_real_escape_string($_GET['ageto']);
$sex = mysql_real_escape_string($_GET['sex']);
$location = mysql_real_escape_string($_GET['location']);
mysql_query("select from table where id = '$id' and agefrom='$agefrom' [.....the rest of the query]")
Can this be done with arrays? What if a location wasn't selected or the age wasn't entered? If i did the query it might fail.
I hope my question is more clear now.
Arrays make it easy to hold a set of values, or key => value pairs, inside a variable. It also makes it easy to iterate over a set of values.
foreach ($myarray as $key => $value)
{
// do something with this key and value
}
If you are passing a large number of values to a function, and this set of values could be thought of as a list or a lookup table, then you would use an array.
Please consult the PHP manual on arrays for more information.
Edit:
I think I see what you mean now. It can be helpful to sort of 'abstract' your database calls by creating a function that accepts values as an array. For example:
function editrecord($recordid, $values)
{
// SQL is generated by what is in $values, and then query is run
// remember to check keys for validity and escape values properly
}
That's an extreme simplication of course.
Arrays are an important feature of any language, they have O(1) (constant time) random access and can be used as a base data structure to make more complex types.
Specifically talking about PHP, the arrays are used VERY often, the language itself uses them for example to grab the GET and POST parameters.
To get data, you can also make use of arrays in PHP.
You can use mysql_fetch_assoc, this will retch a result row from the database as an associative array, each index of the array will represent a column of data of the current row:
//...
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
// Here, the $row variable is an associative array.
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}