using $this-> in mysql query

Discussion in 'PHP' started by makemoneyfromgoogle, Sep 17, 2011.

  1. #1
    How can I retrieve a field in mysql table from a variable from a previous query?
    I have been trying a structure that looks like this:

    Query A)
    OOP php to get 1st result set:
    $q = "SELECT id, label, parent FROM mytable";
    process associative array in while loop, and
    display this to page (call it parent) with:
    instantiating the object: $obj = new myclass();
    and then: echo $obj->display_myfunction();

    B) So where I get lost is adding a second query to get other fields in the same table related to the id from query $q.
    Can I write a second query that goes something like:
    $y = "SELECT id, parent FROM mytable where this->id = id";
    provided that both queries A & B are in the same class?

    I imagine a situation where A) is a menu bar down the left side of a page, and what is active in the menu is displayed in B) on the body of the page.
     
    makemoneyfromgoogle, Sep 17, 2011 IP
  2. sarahk

    sarahk iTamer Staff

    Messages:
    28,899
    Likes Received:
    4,555
    Best Answers:
    123
    Trophy Points:
    665
    #2
    You're on the right track but I'm not quite sure where the problem is.

    When putting the variable into the new query (which is just a string until it hits the database) code it like this

    $y = "SELECT `id`, `parent` FROM `mytable` where `id` = '{$this->id}'";
    // or
    $y = "SELECT `id`, `parent` FROM `mytable` where `id` = '".$this->id."'";
    
    PHP:
    The {} tell PHP to look for a variable - forced rather than implied and necessary for objects and arrays otherwise it stops at -> and doesn't read the rest.

    The `` around the table name and column name are to ensure mysql knows the name relates to a column or table and doesn't get confused with reserved words. Best practice and not essential.
     
    sarahk, Sep 17, 2011 IP