Map mysqli_fetch_assoc to object attributes? - php

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)

Related

Getting specific column from sql database using raw query in laravel

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'];

how to read yii create command object without foreachloop

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;

Accessing object's properties via array index

I have a situation where i have to programmatically do database inserts. I have multiple tables but the order of information of those tables are similar , i.e, in each table, the first coulmn in id, and second is a foregin key, and third is a name, and fourth is a blob and fifth is a text.
I searched php doc and found that I can use $objectName[index] to access the database property. I am getting error
Cannot use object of type stdClass as array in C:\....php on line .. .
The erroneous line is indicated on the code
private function uploadTemp($databaseObject, $table_name){
$this->load->database();
//get file_contents too;
$file_id = $databaseObject[3]; // < Here's where the error appeared
$this->db->from('tbl_file')->where('file_id',$file_id);
$q = $this->db->get();
$data = $q->row();
$query = "INSERT INTO $table_name VALUES(NULL, '".$databaseObject[2]."','".$data->filecontent."');";
$this->db->query($query);
}
I am using CodeIgniter as a framework.
Try casting to array:
$file_id = (array) $databaseObject[3];
As STDClass is just a dummy container with public dynamic variables and no methods, there should be no problems in casting it to array and backwards as well.
However in some situations numbers are used to represent a variable name.
Example:
$array ; //Is some array created by engines / database handlers.
$obj = (object) $array ;
echo $obj->0 ; //Hell it will not work.
echo $obj[0] ; //The same problem.
echo $obj->{'0'} ; //PERFECT
try this function get_object_vars()
or create function to convert to array
function array_to_object($array)//from CodeIgniter forum
{
return (is_array($array)) ? (object) array_map(__FUNCTION__, $array) : $array;
}

Quicker way of doing this

I'm using PDO to get an array of relations from my DB.
$dbRelaties = $dbh->query("SELECT pkRelatieId,naam,email FROM relaties");
in another function i need to acces one specific row in this array. I've managed to do it like this:
$klant = array();
foreach($dbRelaties as $dbRelatie)
{
if($dbRelatie["pkRelatieId"] == $relatie){ $klant = $dbRelatie; break; }
}
sendMail("Subject",$klant);
The above code works. But i'me looking for a neater solution and a quicker one, the above code is called in a function and that function is called inside a loop. So everytime it executes is has to loop through $dbRelaties to get the correct relation.
Can anyone set me in the right direction?
assuming the pk means primary key, then
while($row = mysql_fetch_assoc($result)) {
$dbRelatie[$row['pkRelatieID']] = $row;
}
would produce an array keyed with your primary key field, so
$dbRelatie[$pk]['naam']
will give you that particular pk's naam value.
To show a PDO specific version of Marc B's answer.
Assuming a query was executed through PDO like so:
$sql = "SELECT pkRelatieId,naam,email FROM relaties";
$resultSet = $pdo->query($sql);
The results can be read into a PHP array using PDO's fetch method.
$dbRelaties = array();
while ($row = $resultSet->fetch(PDO::FETCH_ASSOC)) {
$dbRelaties[$row['pkRelatieID']] = $row;
}
This can then be used to access values based on the PK of the row.
sendMail("Subject", $dbRelaties[$relatie]['naam']);
Furthermore. PDO lets you assign a default fetch mode to each PDO instance, and the PDOStatement class is Traversable, so that you don't actually have to call the fetch() method in a while loop to go through a result set.
If you were to do this to a PDO object before a query: (Ideally only once right after creating the object.)
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
Then you can use a foreach loop on the result set to get row arrays with field names, instead of using a while loop.
$dbRelaties = array();
foreach ($stmt as $row) {
$dbRelaties[$row['pkRelatieID']] = $row;
}

can i insert a php array into a single mysql record field?

suppose we have a mysql table "table" with fields "user" "siblings" and we want to store this family info for every user.
is it possible to do this:
$user=35;
$sibs=array("george","christina");
mysql_query("insert into table (user,siblings) values ('$user','$sibs')");
so that field "siblings" contains an array?
You want to use PHP's serialize() function for this. To reverse the process, use unserialize()
Snippit from PHP.net:
<?php
// $session_data contains a multi-dimensional array with session
// information for the current user. We use serialize() to store
// it in a database at the end of the request.
$conn = odbc_connect("webdb", "php", "chicken");
$stmt = odbc_prepare($conn,
"UPDATE sessions SET data = ? WHERE id = ?");
$sqldata = array (serialize($session_data), $_SERVER['PHP_AUTH_USER']);
if (!odbc_execute($stmt, $sqldata)) {
$stmt = odbc_prepare($conn,
"INSERT INTO sessions (id, data) VALUES(?, ?)");
if (!odbc_execute($stmt, $sqldata)) {
/* Something went wrong.. */
}
}
?>
To build on #David Houde's answer from the post he refered to also use compression to save space (if useful to you):
<?php
mySerialize( $obj ) {
return base64_encode(gzcompress(serialize($obj)));
}
myUnserialize( $txt ) {
return unserialize(gzuncompress(base64_decode($txt)));
}
?>
You can use serialize http://ru2.php.net/manual/en/function.serialize.php
But it's really bad practice.
You can use implode() to add a divider between values. For example, you can use the pipe "|"
e.g.
$user=35;
$sibs=array("george","christina");
$sibs1 = ''.implode('|',$sibs).'|';
mysql_query("insert into table (user,siblings) values ('$user','$sibs1')");
When extracting information from the database use LIKE '%|$var|%' in your query to extaract the exact value. e.g. |Christina|
Yes, you can serialize() the array prior to inserting it, or implode() it with some kind of a separator of your choice for this, but I would recommend you just insert separate rows for each user->sibling relationship.

Categories