Maher Mahmoud
Maher Mahmoud

Reputation: 113

MYSQL assign column name to variable?

I have a database table which has two columns, business and tourist.

I ask a user to select one of them from dropdown list, then use the result in a SELECT statement in MySQL. I assign this column to $cclass, then I make this statement SELECT $cclass FROM flights ....

But it always returns NULL. Why does it return NULL and how do I fix this?

My code:

$check = mysql_query("SELECT $cclass FROM flights WHERE flight_no = '$flightno'");

while ($result = mysql_fetch_assoc($check))
{
    $db_seats = $result['$cclass']; 
}

Upvotes: 2

Views: 144

Answers (3)

Will
Will

Reputation: 24699

First of all, this code has a serious security issue, as it is vulnerable to SQL Injection. You should be using the MySQLi extension instead, and properly filtering your input.

Try something like this:

<?php

/* Create the connection. */
$mysql = new mysqli("localhost", "username", "password", "myDB");
if ($mysql->connect_error)
{
    error_log("Connection failed: " . $mysql->connect_error);
    die("Connection failed: " . $mysql->connect_error);
}

/* Sanitize user input. */
if (!in_array($cclass, array('business', 'tourist')))
{

    error_log("Invalid input: Must be 'business' or 'tourist'");
    die("Invalid input: Must be 'business' or 'tourist'");
}

$statement = $mysql->stmt_init();
$statement->prepare("SELECT $cclass FROM flights WHERE flight_no = ?");
$statement->bind_param("s", $flightno);
if (!$statement->execute())
{
    error_log("Query failed: " . $statement->error);
    die("Query failed: " . $statement->error);
}

if ($statement->num_rows < 1)
{
    echo "No results found.";
}
else
{
    $statement->bind_result($seats);
    while ($statement->fetch())
    {
        echo "Result: $seats";

        // Continue to process the data... You can just use $seats.
    }
}

$mysql->close();

However, the reason your original example is failing, is that you're quoting $cclass:

$db_seats = $result[$cclass]; 

However, please do not ignore the serious security risks noted above.

Upvotes: 1

Gouda Elalfy
Gouda Elalfy

Reputation: 7023

you should replace this line:

$db_seats = $result['$cclass']; 

with this:

$db_seats = $result[$cclass]; 

string between 2 single quotes doesn't parsed: Strings

Upvotes: 3

Chico Jos&#233;
Chico Jos&#233;

Reputation: 121

Have you tried doing the following:

$check = mysql_query("SELECT".$cclass." FROM flights WHERE flight_no = '$flightno'");

Upvotes: 1

Related Questions