Board index   FAQ   Search  
Register  Login
Board index php forum :: Database mySQL & php coding

Using Variable in MySQL query

Codes here !

Moderators: macek, egami, gesf

Using Variable in MySQL query

Postby nitapita » Mon Jan 07, 2013 10:18 pm

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)

Code: Select all
$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>"; }
}



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!
nitapita
New php-forum User
New php-forum User
 
Posts: 8
Joined: Sun Jan 06, 2013 12:41 am

Re: Using Variable in MySQL query

Postby nitapita » Tue Jan 08, 2013 12:03 am

for example when i hardcode the query, results are ok and that is what i want to achive here
Code: Select all
$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";
}
nitapita
New php-forum User
New php-forum User
 
Posts: 8
Joined: Sun Jan 06, 2013 12:41 am

Re: Using Variable in MySQL query

Postby nitapita » Tue Jan 08, 2013 12:44 am

got it fixed ..

Code: Select all
$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>"; }

}
nitapita
New php-forum User
New php-forum User
 
Posts: 8
Joined: Sun Jan 06, 2013 12:41 am


Return to mySQL & php coding

Who is online

Users browsing this forum: docharley01 and 1 guest

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.

cron