如何访问包含逗号分隔值的输入框值并将其插入数据库 [英] how to access input box values that contains comma separated values and insert into database

查看:80
本文介绍了如何访问包含逗号分隔值的输入框值并将其插入数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我到目前为止尝试过的我的PHP代码

This is My PHP code till now I tried

<?php
include_once("../include/connClass.php");
$db = new Database();
$conn = $db->getConnection();

if(isset($_POST["save"]))
{
 $date = $_POST["txtDate1"];
}

$date = $_POST["txtDate1"];
$service = $_POST["txtService1"];
$charge = $_POST["txtCharge1"];
$amount = $_POST["txtAmount1"];
$unit = $_POST["txtUnit1"];
$total = $_POST["txtTotal1"];

for ($i = 0; $i <= count($date); $i++) {

 try {
    $sql = $conn->prepare("INSERT INTO backup_master (backup_date, 
backup_service, backup_charge, backup_amount, backup_unit, backup_total)
        VALUES (:backup_date, :backup_service, :backup_charge, 
 :backup_amount, :backup_unit, :backup_total)");

    $sql->bindParam(':backup_date', $date);
    $sql->bindParam(':backup_service', $service);
    $sql->bindParam(':backup_charge', $charge);
    $sql->bindParam(':backup_amount', $amount);
    $sql->bindParam(':backup_unit', $unit);
    $sql->bindParam(':backup_total', $total);

    $query = $sql->execute();
    // echo $query;
}
catch (PDOException $e) {
    echo $sql . "<br />Error" . $e->getMessage();
}
}
?>

这是我的表单代码

<form method="POST" action="backend/save.php">

<input type="text" id="txtDate1" name="txtDate1">
<input type="text" id="txtService1" name="txtService1">
<input type="text" id="txtCharge1" name="txtCharge1">
<input type="text" id="txtAmount1" name="txtAmount1">
<input type="text" id="txtUnit1" name="txtUnit1">
<input type="text" id="txtTotal1" name="txtTotal1">

<button type="submit" name="save" class="btn btn-primary">Save</button>
</form>

这是我的问题,我在每个输入框中都有一个用逗号分隔值的输入框值(例如abc,xyz,pqr),我想一一插入值到数据库的不同行中,但是现在所有逗号分隔的值会将任何想法如何插入到单行中.预先感谢.

Here is my question is I have an input boxes values with comma separated values in each input box(like abc,xyz,pqr) and I want to insert values one by one to the different rows to the database but now all comma separated values are inserting into the single row any idea how to do. Thanks in advance.

推荐答案

您可以展开,上的所有POST变量,然后循环查找最小的值.

You can explode all the POST variables on , and then loop for the smallest amount of values.

示例:

$date = explode(",", $_POST['txtDate1']);
$unit = explode(",", $_POST['txtUnit1']);

$lowest = 1000; //Bad practice, this assumes there will never be more than 1000 comma seperated values
if (count($date) < $lowest)
    $lowest = count($date); //Loop for all values.

for ($i=0;$i<$lowest;$i++){
    //Insert records into database 1-by-1
}

这篇关于如何访问包含逗号分隔值的输入框值并将其插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆