SitePoint Sponsor

User Tag List

Results 1 to 16 of 16
  1. #1
    SitePoint Zealot darkwarrior's Avatar
    Join Date
    Dec 2010
    Posts
    171
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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.

    Code PHP:
    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?

    Code PHP:
    if(!$result = mysql_query("QUERY"))

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

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,189
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    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.

    PHP Code:
    $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.

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

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

    PHP Code:
    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

  3. #3
    Keeper of the SFL StarLion's Avatar
    Join Date
    Feb 2006
    Location
    Atlanta, GA, USA
    Posts
    3,748
    Mentioned
    69 Post(s)
    Tagged
    0 Thread(s)
    er.. be very careful there SL, you're overwriting the data with each result row....

  4. #4
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,189
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    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.

  5. #5
    SitePoint Zealot darkwarrior's Avatar
    Join Date
    Dec 2010
    Posts
    171
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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

    Code PHP:
    	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.

  6. #6
    SitePoint Zealot darkwarrior's Avatar
    Join Date
    Dec 2010
    Posts
    171
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.

    Code PHP:
    	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.

  7. #7
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,189
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    $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.

  8. #8
    SitePoint Zealot darkwarrior's Avatar
    Join Date
    Dec 2010
    Posts
    171
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by SgtLegend View Post
    $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?

  9. #9
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,189
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    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.

  10. #10
    SitePoint Zealot darkwarrior's Avatar
    Join Date
    Dec 2010
    Posts
    171
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.

  11. #11
    SitePoint Guru
    Join Date
    Nov 2003
    Location
    Huntsville AL
    Posts
    689
    Mentioned
    4 Post(s)
    Tagged
    0 Thread(s)
    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.
    PHP Code:
           $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

  12. #12
    SitePoint Zealot darkwarrior's Avatar
    Join Date
    Dec 2010
    Posts
    171
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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:

    Code:
    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:

    Code:
    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?

  13. #13
    SitePoint Guru
    Join Date
    Nov 2003
    Location
    Huntsville AL
    Posts
    689
    Mentioned
    4 Post(s)
    Tagged
    0 Thread(s)
    $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.

  14. #14
    From space with love silver trophy
    SpacePhoenix's Avatar
    Join Date
    May 2007
    Location
    Poole, UK
    Posts
    5,000
    Mentioned
    101 Post(s)
    Tagged
    0 Thread(s)
    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.

    PHP Code:
    $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.
    Community Team Advisor
    Forum Guidelines: Posting FAQ Signatures FAQ Self Promotion FAQ
    Help the Mods: What's Fluff? Report Fluff/Spam to a Moderator

  15. #15
    SitePoint Zealot darkwarrior's Avatar
    Join Date
    Dec 2010
    Posts
    171
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.

  16. #16
    SitePoint Guru
    Join Date
    Nov 2003
    Location
    Huntsville AL
    Posts
    689
    Mentioned
    4 Post(s)
    Tagged
    0 Thread(s)
    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.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •