How to place retrieved SQL rows into an object? (Plus Bonus php/sql Question!)

I assume the answer is simple but I don’t know how to do it with an object but I’m merging the result from this with another object. I know how to do it with an array easy enough but can’t figure this one out, keep getting the error “Attempt to assign property of non-object”. Help is appreciated.

if(!$result = mysql_query("SELECT * FROM users_meta WHERE user_id = $thisUser->user_id"))
			$userMeta = false;
		else 
			$userMeta = object;
			while($row=mysql_fetch_object($result))
				foreach($row as $field=>$data)
					$userMeta->$field = $data; 

SUPER BONUS QUESTION-N-N-N-N!

I had been using the below code to return false if nothing is returned from a database. It SEEMED to be working but I now realize it isn’t, as in the above code, it goes to the ELSE even if there are no rows returned. What is a good way to quickly check if a result has been returned or not?

if(!$result = mysql_query("QUERY"))

Thanks for reading guys and gals. Coding, the joy that keeps on giving.

Object are a tricky one, i had the same troubles at first but after a quick search i found the answer i needed. Basically what you have is trying to reference a class which doesn’t exist, to set the object property all we need to do is use the curly braces {} and it will work.

$userMeta->{$field} = $data;

Using the code you have won’t count the results, what it’s doing is checking if he MySQL query has successfully run or not. so for instance this is how you would write the above code to check for errors.

if (!$result = mysql_query("QUERY")) {
    die(mysql_error());
} else {
    // Run the loop...
}

To check the number of rows returned you can do this…

if (!$result = mysql_query("QUERY")) {
    die(mysql_error());
} else {
    $numrows = mysql_num_rows();
    $userMeta = false;
    
    if ($numrows) {
        while ($row = mysql_fetch_object($result)) {
            foreach ($row as $field => $data) {
                $userMeta->{$field} = $data;
            }
        }
    }
}

Also i recommend you start using MySQLi, you will know why i recommend to do so after reading the following PHP: Overview - Manual

er… be very careful there SL, you’re overwriting the data with each result row…

It’s how darkwarrior coded it, i thought he had a method to his code so i left it alone as i don’t like assuming how other people use their own code.

How do you mean StarLion?

And Sgt, I tried your change with the curly brackets but I am still receiving “Attempt to assign property of non-object” .

This is my current code

	if(!$result = mysql_query("SELECT * FROM users_meta WHERE user_id = $thisUser->user_id"))
			$userMeta = false;
		else 
			$userMeta = object;
			while($row=mysql_fetch_object($result))
				foreach($row as $field=>$data)
					$userMeta->{$field} = $data; 

As for context, I’m just retrieving several rows of meta information about a user. I’m TRYING to store that information in the form of:

dataname->data

It works well enough for a single row but it is the multiple row aspect I’m struggling with.

EDIT: Can you switch to MySQLi without rewriting all my database code? This is working towards a basic CMS that I’m fairly far into.

It seems I’m doing it wrong anyway. This is what I get when I print out $field and $data

Field = meta_key
Data = display_name
Field = meta_value
Data = Blake

So that wouldn’t work anwyay since every other row will overwrite every other row. Need to be accessing it like $row->meta_key. So minor problem fixed.

So current code now looks like this.

	if(!$result = mysql_query("SELECT meta_key, meta_value FROM users_meta WHERE user_id = $thisUser->user_id"))
			$userMeta = false;
		else  {
			$userMeta = object;
			while($row=mysql_fetch_object($result)) {
					$userMeta->{$row->meta_key} = $row->meta_value; 
			}
		}

Though it is still throwing up the same error.

$userMeta has to have a default value of false not object or it will error out, also please read back through my post about the IF statement you have as at the moment its not correct as per error catching goes.

Thanks, setting it to FALSE worked.

As per your other suggestion, from a user-friendliness bent, wouldn’t having the SQL just die be a bad thing?

Not necessarily, if you want a silent error for production that’s fine but for development you should always use either exit or die to ensure that your script contains no errors. Personally i do this all the time as its good practice.

Ah, OK, I see your point then. I do intend to build an error function for the full implementation to catch stuff like that without just halting the process.

I know this is not quite what you asked but here is an example of querying a games table that has a one to many relationship with the teams playing in the game as well as a one to many relationship to the referees.


       $qbGames = $em->createQueryBuilder();

        $qbGames->addSelect('game');
        $qbGames->addSelect('gameTeam');
        $qbGames->addSelect('person');

        $qbGames->from('ZaysoBundle:Game','game');

        $qbGames->leftJoin('game.gameTeams','gameTeam');
        $qbGames->leftJoin('game.persons',  'person');

        $games = $qbGames->getQuery()->getResult();

This results in a list of game objects from which you easily obtain the team objects as well as the officials. Welcome to Doctrine2. Doctrine - PHP Object Persistence Libraries and More

The point being that if you really want to start using objects that can be persisted to a database then consider reading through some of the various ORM documentation for ideas. Doctrine2 happens to be the latest and some would say greatest. Maybe start by looking at the query chapter:
13. Doctrine Query Language — Doctrine 2 ORM v2.1 documentation

Having a similar problem again.

I tried variations of the above when trying to retrieve multiple unknown rows from a database into an object but am having no success.

I tried:

if($output == OBJECT)
				while($row = mysql_fetch_object($result)) {
					$comList{} = $row;
			}

In the same manner as using an array but using the {} like that just draws an error about an unexpected “}”. I tried just doing:

if($output == OBJECT)
				$comList= mysql_fetch_object($result)
					return $comList;

But that only returns one row. Maybe I’m going about it wrong, just getting annoyed with having to assign the results into an array to return it and then having to do a foreach to access it in circumstances where I’m only expecting one result.

Am I being dumb about this?

$comList = $row;
Assuming that $comList is an array.
And add error_reporting(E_ALL); to the top of your page. It will help pick up a bunch of questionable stuff.

When your using a while loop to get all rows of a result set, set up the variable that your going to use as an array before the while loop runs then if you don’t have any matches any foreach loop that you’ve got set to act on the result set want give any errors if the result set is empty.

$comList=array();
while($row = mysql_fetch_object($result)) {
    $comList[] = $row;
}

If there are no rows returned by whatever query is being used then any foreach loop set to iterate through the result set will see what it expects, an array, albeit an empty array.

My error catching is set to Max already.

So the only way to do it with an object is by placing it in an array unless you know what results to expect?

I was able to get success when assigning it as “$object->{$columnname} = $data”

Where $columnname is the name of hte database column returned and $data is the contents of the row returned.

But if I do it as $object->{}, it throws an error.

You might want to invest some time reading the section on classes and objects in the manual. Squiggly brackets {} are not directly related to object oriented programing. In fact, $object->$columnname = $data would work just as well.