我有一个数据库表,其中有两列business
和tourist
。
我要求用户从下拉列表中选择其中一个,然后在MySQL的SELECT
语句中使用结果。我将此列分配给$cclass
,然后我将此语句SELECT $cclass FROM flights ...
。
但它总是返回NULL
。为什么返回NULL
以及如何解决此问题?
我的代码:
$check = mysql_query("SELECT $cclass FROM flights WHERE flight_no = '$flightno'");
while ($result = mysql_fetch_assoc($check))
{
$db_seats = $result['$cclass'];
}
答案 0 :(得分:3)
你应该替换这一行:
$db_seats = $result['$cclass'];
用这个:
$db_seats = $result[$cclass];
两个单引号之间的字符串没有被解析: Strings
答案 1 :(得分:1)
您是否尝试过以下操作:
$check = mysql_query("SELECT".$cclass." FROM flights WHERE flight_no = '$flightno'");
答案 2 :(得分:1)
首先,此代码存在严重的安全问题,因为它易受SQL Injection攻击。您应该使用MySQLi扩展名,并正确过滤您的输入。
尝试这样的事情:
<?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();
但是,原始示例失败的原因是您引用$cclass
:
$db_seats = $result[$cclass];
但是,请不要忽视上述严重的安全风险。