0

我正在尝试使用复选框来概括 Select 查询,您将看到的可变选择是从前端文件发布的,该文件使用复选框在后端创建数组。然后,此数组用于选择语句的 SELECT 子句。目前,表头输出正确的表头,但数据也输出相同的数据。谁能帮我找出我的错误。

<?php
session_start(); //Begins a session
?>

<html> <head> <title> Genre selection back end </title>
</head>
<body>
<?php
$genre_value =  $_POST['genrelist'];

$choice = $_POST['choice'];

$numvalues = count($choice);
echo '<h2> Table shows some data </h2>';
echo "<table border = '1'>";
echo '<tr>';

for($i= 0; $i < $numvalues; $i ++)
{
echo "<th>" .$choice[$i]. "</th>";
$choicearray = $choicearray . ", " .  $choice[$i];
}
echo '</tr>';

$select = substr($choicearray, 1);
include '../functions/connect.php';
$query = "SELECT '$select' FROM film WHERE Genre = '".$genre_value."'";
$result = mysql_query($query) or die ("Invalid query");

while($row = mysql_fetch_array($result))
    {
    echo "<tr>";
        for($i = 0; $i < $numvalues; $i ++)
        {
        echo "<td>" .$row[$i]. "</td>";
        }
    echo "</tr>";
    }
echo "</table>";
mysql_close($con);
?>
</body>
</html>
4

1 回答 1

1

您在选择语句中使用单引号。这使得 MySQL 选择那些确切的字符串值。

删除单引号。将您的查询更改为

$query = "SELECT $select FROM film WHERE Genre = '".$genre_value."'";

此外,请不要将此代码用于概念证明以外的任何用途。您绝对不能直接在查询中信任POST或数据。GET确保首先转义每个值。

我建议您将 for 循环更改为以下内容:

$choicearray = array();
for($i= 0; $i < $numvalues; $i ++)
{
    echo "<th>" .$choice[$i]. "</th>";
    $choicearray[] = mysql_escape_string(trim($choice[$i]));
}
echo '</tr>';
$choicearray = implode(',', $choicearray);

这将为您提供相同的结果,但沿途避开所有项目。

于 2013-04-28T23:40:15.130 回答