复选框,SQL选择语句& PHP

时间:2010-04-28 04:34:33

标签: php mysql checkbox

我试图根据用户提交的选项显示数据库表中的一些行。这是我的表单代码

    <form action="choice.php" method="POST" >
  <input type="checkbox" name="variable[]" value="Apple">Apple
  <input type="checkbox" name="variable[]" value="Banana">Banana
  <input type="checkbox" name="variable[]" value="Orange">Orange
  <input type="checkbox" name="variable[]" value="Melon">Melon
  <input type="checkbox" name="variable[]" value="Blackberry">Blackberry

据我所知,我将这些值放入一个名为变量的数组中。 我的两个专栏名为receipe名称和成分(成分下的每个领域可以存储许多水果)。我想要做的是,如果选择了多个复选框,则会显示收据名称。

这是我的PHP代码。

<?php
// Make a MySQL Connection
mysql_connect("localhost", "*****", "*****") or die(mysql_error());
mysql_select_db("****") or die(mysql_error());

$variable=$_POST['variable'];
foreach ($variable as $variablename)
{
echo "$variablename is checked";
}

$query = "SELECT receipename FROM fruit WHERE $variable like ingredients";

$row = mysql_fetch_assoc($result);
foreach ($_POST['variabble'] as $ingredients)
echo $row[$ingredients] . '<br/>';
?>

我是php的新手,只是希望显示数据,我不需要对它执行任何操作。我尝试了很多选择语句,但我无法显示任何结果。我的数据库连接很好,它会打印出检查的变量。

非常感谢提前。

修改

感谢百万回复。但是,我尝试更正我自己的代码=空白页面以及上面==空白页面的两个解决方案。 GRRRR!这是我尝试过的一种解决方案。

<?php
// Make a MySQL Connection
mysql_connect("localhost", "", "") or die(mysql_error());
mysql_select_db("") or die(mysql_error());

$query = "SELECT receipename FROM fruit ";
$cond = "";

foreach($variable as $varname)$cond .= " $varname like 'ingredients' OR";
$cond = substr_replace($cond, '', -2);
$query .= " WHERE $cond";

$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
echo $row['receipename'],'<br />';
}

我也试过

<?php
// Make a MySQL Connection
mysql_connect("localhost", "24056", "project99") or die(mysql_error());
mysql_select_db("24056db2") or die(mysql_error());

$variable=$_POST['variable'];
foreach ($variable as $variablename)
{

$query = "SELECT receipename FROM horse WHERE ingredients = '".$variablename."'";
while($row = mysql_fetch_assoc($query))
{
echo $row['receipename']."<br/>";
}
}
?>

我想另一种说法,如果checkbox变量等于成分列下的记录,我希望打印出该记录的receipename。 我几乎在这里迷茫mysellf,哈哈。

我可以尝试其他任何想法???

2 个答案:

答案 0 :(得分:0)

  

您的密码更正

$query = "SELECT receipename FROM fruit WHERE $variable like ingredients";

$row = mysql_fetch_assoc($result);

你看到上面的区别吗?

放置“$ query”代替“$ result”mysql_fetch_assoc($ result)

  

我的解决方案

$variable=$_POST['variable'];
foreach ($variable as $variablename)
{

$query = "SELECT receipename FROM fruit WHERE ingredients = '".$variablename."'";
while($row = mysql_fetch_assoc($query))
{
echo $row['receipename']."<br/>";
}
}

答案 1 :(得分:0)

我的问题不明确,您可以尝试以下方法 -

$query = "SELECT receipename FROM fruit ";
$cond = "";

foreach($variable as $varname)$cond .= " $varname like 'ingredients' OR";
$cond = substr_replace($cond, '', -2);
$query .= " WHERE $cond";

$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
   echo $row['receipename'],'<br />';
}

注意:此代码未经过测试