如何使用php将一行中的多个值添加到mysql

时间:2017-02-01 05:37:45

标签: php html mysql twitter-bootstrap

我是人力资源和开发新手。我开始使用PHP和Mysql进行HR管理程序。我想在一列的一行中添加至少5名员工的姓名。我使用bootstrap在单个字段中获取多个值。但是当我尝试插入值时,只插入最后一个值。

<td>Distribute</td><td><input type="text" class="form-control"  name="distribute[]"></td>

HTML代码:

<tr><td>Distribute</td><td><input type="text" class="form-control"  name="distribute[]"></td></tr>

PHP插入mysql

$civil_id= $_POST['civil_id'];

    $name= $_POST['name']; 
    $card_type = $_POST['card_type']; 
    $count = $_POST['count']; 
    $amt=$card_type * $count;
    $avail_bal=$_POST['balance']- $amt; 
    $issue_year= $_POST['issue_year']; 
    $issue_month= $_POST['issue_month']; 
    $issue_date= $_POST['issue_date']; 
    $distribute= $_POST['distribute'];

$sql ="insert into group_phone
(civil_id,
name,
card_type,
count,
amt,
avail_bal,issue_year,issue_month,issue_date,distribute)values('$civil_id',
'$name',
'$card_type',
'$count',
'$amt',
'$avail_bal','$issue_year','$issue_month','$issue_date','$distribute')";

HTML

&#13;
&#13;
<script>
      $(document).ready(function() {
        $(".select2_single").select2({
          placeholder: "Select Vehicle Plate Number",
          allowClear: true
        });
        $(".select2_group").select2({});
        $(".select2_multiple").select2({
          maximumSelectionLength: 10,
          placeholder: "With Max Selection limit 10",
          allowClear: true
        });
      });
    </script>
&#13;
<form class="form-horizontal form-label-left" action="new_rechargecard.php" method="POST" ">
                    <table id="datatable" class="table table-striped table-bordered">
                      


                      <tbody>
					  
					   <tr>
	          <td width='100'>Employee Name: </td><td><input type="text" class="form-control" placeholder="0" name="name" value="<?php echo "$name";?>" ></td> 
    
</tr>
                       
                      
					   
					   
                          
    <tr>
	
	<td>Available Balance</td><td><input type="text" class="form-control" placeholder="0" name="balance" value=<?php echo $balance;?> > </td></tr> 
     <tr><td>Civil id</td><td><input type="text" class="form-control" placeholder="Civil ID Required" name="civil_id" value=<?php echo $pass_name;?> > </td></tr>
	 <!--<tr><td>Name</td><td><input type="text" class="form-control" name="name" value="<?php echo $name;?>" > </td></tr>-->
	 
	  
	 <tr><td width='250'>Card Type (1 KD or 2.5 KD or 5 KD)</td><td><input type="text" class="form-control"   name="card_type"></td></tr>
	 <tr><td width='200'>Card Count</td><td><input type="text" class="form-control"  name="count"></td></tr>
	 <tr><td>Issue Year</td><td><input type="text" class="form-control"  name="issue_year" value="<?php echo date('Y'); ?>"></td></tr>
	  <tr><td>For the Month of</td><td><input type="text" class="form-control"  name="issue_month" value="<?php echo date('M'); ?>"></td></tr>
	 <tr><td>Issue date</td><td><input type="text" class="form-control"  name="issue_date"></td></tr>
	 <tr><td>Distribute</td><td><select name="distribute" class="select2_multiple form-control" tabindex="-1"  multiple="multiple">
	 <option></option>
     <option>Richard Marcus</option>     
     <option>Rowlant S Peter</option> 
     <option>David.K.Rumpell</option> 
     <option>John Mathew</option>  
   	 </select>
	 </td></tr>
	 
	
	 	
     <tr><td></td><td><input type="submit" class="btn btn-round btn-danger" value="Update" name="submit"></td></tr>
	 </tbody>
     </table>
	 </form>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

像这样更改你的代码

<?php

/* First create mysql connection */

$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "userlist";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

/* End */

    $civil_id= $_POST['civil_id'];

    $name= $_POST['name']; 
    $card_type = $_POST['card_type']; 
    $count = $_POST['count']; 
    $amt=$card_type * $count;
    $avail_bal=$_POST['balance']- $amt; 
    $issue_year= $_POST['issue_year']; 
    $issue_month= $_POST['issue_month']; 
    $issue_date= $_POST['issue_date']; 
    $distribute= $_POST['distribute'];

$sql ="insert into group_phone
(civil_id,
name,
card_type,
count,
amt,
avail_bal,issue_year,issue_month,issue_date,distribute)values('".$civil_id."',
'".$name."',
'".$card_type."',
'".$count."',
'".$amt."',
'".$avail_bal."','".$issue_year."','".$issue_month."','".$issue_date."','".$distribute."')";

if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);

?>
  

MySQL表结构

- 表userlist

的表结构
CREATE TABLE IF NOT EXISTS `userlist` (
  `civil_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(200) NOT NULL,
  `card_type` varchar(100) NOT NULL,
  `count` int(11) NOT NULL,
  `amt` int(11) NOT NULL,
  `avail_bal` int(11) NOT NULL,
  `issue_year` int(11) NOT NULL,
  `issue_month` varchar(50) NOT NULL,
  `issue_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `distribute` varchar(200) NOT NULL,
  PRIMARY KEY (`civil_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
  

工作查询(MySQL)

INSERT INTO `userlist` (`civil_id`, `name`, `card_type`, `count`, `amt`, `avail_bal`, `issue_year`, `issue_month`, `issue_date`, `distribute`) VALUES
(1, 'aman,suresh,mohan', 'POST', 10, 500, 50, 2016, 'March', '2017-02-01 06:46:16', 'Airtel,Idea,Vodafone');

答案 1 :(得分:0)

不确定你是否解决了这个问题,但是你只需要在表单中做一个排列的distribute名称,然后使用内置函数将数组转换为字符串,一些常用函数是{{1} }或serialize()。我更喜欢后者,因为JavaScript可以使用它,但就最佳实践而言,通常不赞成将数组存储到这样的数据库中。我发现它对于现在或将来不需要有针对性的搜索的一次性实例很有用。我会非常谨慎地使用它。在这种情况下,您可能希望创建一个单独的表来单独存储名称,并在以后再选择它们时加入它们。

另外,对于我的例子,我使用的是PDO而不是json_encode(),但原则是相同的。看看bind_param。最后,我将介绍如何创建一些有用的类来帮助清理脚本。我下面的是一些基本的例子。

<强> /classes/User.php

mysqli_

<强> /classes/Database.php

# I would think about containing your script in a class, this is just
# a bare-bones example
class   User
    {
        public  function __construct(PDO $db)
            {
                $this->db   =   $db;
            }

        protected   function getAmount($a, $b)
            {
                return $a*$b;
            }

        protected   function getBalance($a,$b)
            {
                return $a-$b;
            }

        public  function addUser($array)
            {
                $bind   =   array(
                    $_POST['civil_id'],
                    $_POST['name'],
                    $_POST['card_type'],
                    $_POST['count'],
                    $amt = $this->getAmount($_POST['card_type'],$_POST['count']),
                    $this->getBalance($_POST['balance'],$amt),
                    $_POST['issue_year'],
                    $_POST['issue_month'],
                    $_POST['issue_date'],
                    json_encode($_POST['distribute'])
                );

                $sql ="INSERT INTO group_phone 
                    (civil_id,name,card_type,count,amt,avail_bal,issue_year,issue_month,issue_date,distribute)
                values
                    (?,?,?,?,?,?,?,?,?,?)";

                $query  =   $this->db->prepare($sql);
                $query->execute($bind);
            }
    }

<强> /new_rechargecard.php

# This would need to be filled out and made to work with yours
# This is demonstration purposes only
class Database
    {
        private static  $con;

        public  function connect()
            {
                if(self::$con instanceof PDO)
                    return self::$con;

                self::$con  =   new PDO("mysql:host=localhost;dbname=databasename;","username","password");

                return self::$con;
            }
    }

表单HTML:

define('DS', DIRECTORY_SEPARATOR);
define('ROOT_DIR', __DIR__);
define('CLASSES', ROOT_DIR.DS.'classes');
# Create a class autoloader
spl_autoload_register(function($class){
    $inc = CLASSES.DS.trim(str_replace('\\',DS,$class),DS).'.php';
    if(file_exists($inc))
        include_once($inc);
});
# Create db
$con    =   (new Database())->connect();
# Check for update
if(isset($_POST['action']) && $_POST['action'] == 'update_user') {
    # Create user instance
    $User   =   new User($con);
    # Add into database
    $User->addUser($_POST);
}
?>