如何使用php在mysqli select查询中选择单选按钮
我有一个带有许多不同复选框的html表单。我想使用php,因此当运行查询时,这意味着选择部分将是用户选中的任何单选按钮。可能是这样的:如何使用php在mysqli select查询中选择单选按钮,php,html,mysqli,Php,Html,Mysqli,我有一个带有许多不同复选框的html表单。我想使用php,因此当运行查询时,这意味着选择部分将是用户选中的任何单选按钮。可能是这样的: <?php error_reporting(E_ALL); ini_set('display_errors', 1); $choice = $_POST["choice"]; if(!empty($choice)){ $select = implode(',',$choice); // this will split all choices wi
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$choice = $_POST["choice"];
if(!empty($choice)){
$select = implode(',',$choice); // this will split all choices with a comma
$query = "SELECT $select from purchase";
}else{
// IF NOTHING IS SELECTED
}
include "connect.php";
?>
要从html表单中正确选择,可以根据允许的选择字段检查输入值。以下是一个示例:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$choice = $_POST["choice"];
include "connect.php";
switch($choice){
case("HouseID"): $selection = "HouseID";
break;
case("DatePurchased"): $selection = "DatePurchased";
break;
case("AskingFor"): $selection = "AskingFor";
break;
case("SoldFor"): $selection = "SoldFor";
break;
Default: $selection = "*";
}
$query = "SELECT $selection from purchase";
?>
这样,就不会将用户输入直接放入查询中,并且可以使输入值与表字段不同,从而为您增加一层保护 我建议不要修改查询,而是修改输出
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
include "connect.php";
// Just select all the columns.
$query = "SELECT HouseID, DatePurchased, AskingFor, SoldFor from purchase";
// Execute the query
$result = mysqli_query($con, $query);
// Then output only the columns you want.
echo "<table><thead><tr>";
foreach ($_POST["choice"] as $column) {
echo "<th>$column</th>";
}
echo "</tr></thead><tbody>";
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { //
echo "<tr>";
foreach ($_POST['choice'] as $column) {
echo "<td>{$row[$column]}</td>";
}
echo "</tr>";
}
echo "</tbody></table>";
?>
您的问题到底是什么?我希望从查询中选择用户选择的任何单选按钮。您没有单选按钮,但有复选框,其次,它们在一个数组中。打开sql注入,您需要获取查询。为什么在$query
之前有一个斜杠?哦,是的,对不起,意思是复选框根据您的编辑echo“Please pick a sel”
我如何在表中打印它?遗憾的是,这不起作用包括“connect.php”代码>应该在查询之前进行。似乎不喜欢fetch Array。例如,我使用了fetchArray()
,因为您的问题不清楚您将使用哪个数据库扩展。如果您向问题中添加代码以显示当前如何执行查询和获取结果,我可以相应地修改此答案。在编辑的问题中的代码中,您没有执行查询。如果使用此方法生成表,则不需要修改SQL字符串。执行什么操作?执行查询?也就是这一行$result=mysqli\u query($con,$query)代码>。为了你的努力,我把这个答案投了赞成票,尽管这个问题毫无意义。在发布之前,OP应该先阅读教程。