Using Variable in MySQL query

Discussion in 'PHP' started by nita, Jan 7, 2013.

  1. #1
    Hi everone.

    Having a problem with getting the values from a database.

    What im trying to do is:
    I use variable 'varname' from packaging_items table (values are coressponding to the names of columns in packaging table ... pack01, pack02 .. and so on).
    But in query result1 instead of getting the value of (pack01, pack02 ..) i get the names of columns (pack01, pack02 ..)
    Here is my short code: (ofcourse there is more to it, but this bit is most important)

    
    $result = mysql_query("SELECT * FROM packaging_items") or die(mysql_error());  
    while($row = mysql_fetch_array($result)) {  
        $data1 = $row['varname']; 
        $name = $row['name']; 
        $price = $row['price']; 
    
    $result1=mysql_query("SELECT `$data1` FROM packaging WHERE orderno='$orderno' LIMIT 1") or die(mysql_error()); 
    while($row1 = mysql_fetch_array( $result1 )) { 
        if ( $data1 == '' ) {} else { 
        echo" <tr><td>$name</td><td>$data1</td><td>&pound;$price</td><tr>"; } 
    } 
    }  
    PHP:
    Im stuck here, tried some other options .. and only get worst..

    What do i wrong .. if someone can help will be nice.

    Thank you in advance!
     
    nita, Jan 7, 2013 IP
  2. nita

    nita Member

    Messages:
    30
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #2
    for example when i hardcode the query, results are ok and that is what i want to achive here

    $result1=mysql_query("SELECT pack01 FROM packaging WHERE orderno='$orderno' LIMIT 1") or die(mysql_error());
    while($row1 = mysql_fetch_array( $result1 )) {
    $pack01 = $row1['pack01'];
    echo "$pack01";
    }
     
    nita, Jan 8, 2013 IP
  3. nita

    nita Member

    Messages:
    30
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #3
    got it fixed ...

    $result1=mysql_query("SELECT ".$data1." as data1 FROM packaging WHERE orderno='$orderno' LIMIT 1") or die(mysql_error());
    while($row1 = mysql_fetch_array( $result1 )) {
    $data = $row1['data1'];
    if ( $data == '' ) {} else { echo" <tr><td>$name</td><td>$data</td><td>&pound;$price</td><tr>"; }

    }
     
    nita, Jan 8, 2013 IP
  4. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #4
    Just so you know:

    $row['varname']

    can also be written

    $row[0] or $row[1]

    or whichever field you want from the select statement. (It's the ordinal of the SELECTed fields, not the ordinal of all fields - unless you're selecting all fields, then they're the same.) So you don't need to use a variable if you know which field - first, second, etc. - you want.
     
    Rukbat, Jan 9, 2013 IP