创建 php fom 从表 bd 中选择多个取值 [英] Create php fom select multiple taking values from a table bd
本文介绍了创建 php fom 从表 bd 中选择多个取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
表 deportes 有 2 列 4 行:
The table deportes has 2 columns with 4 rows:
<?php
$sql = 'SELECT * FROM deportes';
$resul = mysqli_query($conexion, $sql);
$deportes = array();
while ($fila = mysqli_fetch_array($resul))
{
$deportes[] = $fila;
}
?>
带有选择多个选项的表单:
The form with the select multiple options:
<select name="fan[]" multiple="multiple">
<?php
foreach ($deportes as $aficion)
{
echo "<option value='".$aficion['idD']."'";
echo " >{$aficion['nombreDep']} </option>\n";
}
?>
</select>
从表单中获取值
<?php
if (isset($_POST['fan']))
{
$sport = $_POST['fan'];
}
?>
现在这个
<?php $sport = mysqli_real_escape_string($conexion, $sport); ?>
这种方式将值插入另一个表中
This way insert the values in another table
$idPersona = mysqli_insert_id($conexion);
$sql = "INSERT INTO mec(id,idD) VALUES ('$idPersona','$sport') ";
结果是我从表 mec 的字段 idD 中得到值0"
And the result is i get the value "0" in the field idD from table mec
推荐答案
如果你print_r
你的$_POST['fan']
,你会看到这是<强>数组.要获取数组的每个值,您应该使用 for
或 foreach
对其进行迭代:
If you print_r
your $_POST['fan']
, you will see that this is array. To get every value of array you should iterate over it, with for
or foreach
:
$idPersona = mysqli_insert_id($conexion);
foreach ($_POST['fan'] as $sport) {
echo $sport; // you will see that now it is string
$sql = "INSERT INTO mec(id,idD) VALUES ('$idPersona','$sport') ";
// execute your query
}
当然,您必须转向准备好的语句,以保护您的代码免受 sql 注入.这个问题会给你一个开始.
And of course you must move to prepared statements to protect your code from sql-injection. This question will give you a start.
这篇关于创建 php fom 从表 bd 中选择多个取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文