如何使用php的强大功能和魔力将一个名称与多个产品一起输入或插入数据库


How to input or insert one name with more products into the database using the power and magic of php?

我正在尝试用多个产品输入一个名称。这里的场景是当我

输入名称:_______________产品:______________产品:_______________。

它将被插入数据库,并显示如下:

Johnny | IphoneJohnny | Windows Phone

这是我的代码:

<form action="" method="POST">
    <table>
        <tr>
            <td>Name</td>
            <td><input type="text" name="name_txt[]" /></td>
        </tr>
        <tr>
            <td>Product</td>
            <td><input type="text" name="product_name_txt[]" /></td>
        </tr>
        <tr>
            <td>Product</td>
            <td><input type="text" name="product_name_txt[]" /></td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td><input type="submit" name="submit" value="add" />
            <input type="reset" name="submit" value="clear" /></td>
        </tr>
    </table>
</form>
<?php   
if(isset($_POST['submit']))
    {      
    include 'db.php';
    foreach($_POST['product_name_txt'] as $row => $value){
        $name=$_POST['name_txt'][$row];
        $product=$_POST['product_name_txt'][$row];
        $sql = "INSERT INTO request(p_name, product_name) VALUES ('$name','$product')";
        if (mysqli_query($conn, $sql)) {
            echo "New record created successfully";
        } else {
            echo "Error: " . $sql . "<br>" . mysqli_error($conn);
        }
     }
   }    
?>

首先,因为只有一个名称,所以应该使用name_txt而不是name_txt[]。其次,对于您的产品,使用implode()函数将数组元素与字符串连接,然后执行INSERT操作。

更改此

<td><input type="text" name="name_txt[]" /></td>

<td><input type="text" name="name_txt" /></td>

你的表格处理是这样的:

if(isset($_POST['submit'])){      
    include 'db.php';
    $name=$_POST['name_txt'];
    $products = implode(" ", $_POST['product_name_txt']);
    $sql = "INSERT INTO request(p_name, product_name) VALUES ('$name','$products')";
    if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
    } else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
    }
}  

以下是参考资料:

  • 内爆()

上面的答案是正确的,但您只需要修改它。

<td><input type="text" name="name_txt" /></td>

$name = $_POST['name_txt'];
$products = $_POST['product_name_txt']; 
foreach($products as $value){
$sql = "INSERT INTO request(p_name, product_name) VALUES ('$name','$value')";
if (mysqli_query($conn, $sql)) 
{
 echo "New record created successfully"; }
 else { 
echo "Error: " . $sql . "<br>" . mysqli_error($conn); 
}
}