【问题标题】:How to add multiple values in a single row of a column using php into mysql如何使用php在一列的单行中添加多个值到mysql
【发布时间】:2017-02-03 01:18:46
【问题描述】:

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

<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

<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>
<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>

【问题讨论】:

  • 请参考此链接tutorialspoint.com/mysql
  • 显示完整代码
  • 警告:使用mysqli 时,您应该使用parameterized queriesbind_param 将用户数据添加到您的查询中。 请勿使用字符串插值或连接来完成此操作,因为您创建了严重的SQL injection bug切勿$_POST$_GET 数据直接放入查询中,如果有人试图利用您的错误,这可能会非常有害。
  • '单个字段中的多个值' :-(

标签: php html mysql twitter-bootstrap


【解决方案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');

【讨论】:

  • 尽可能尝试链接到官方文档。 w3schools 通过推荐不良做法在这里制造了很多问题。
  • 你可以试试我的代码..我认为这可以帮助你解决你的问题......
  • ,'$x', 形式的插值代码切换到,'" . $x . "', 之类的串联代码不会改变任何实质性内容,两者的评估方式相同。要正确,此代码应使用 parameterized queriesbind_param
  • 是的,阿曼库马尔。没有变化。我同意塔德曼。我想在特定员工的分布列中添加 4 或 5 个名称。前雇员 X,Distribute=a,b,c,d,e
  • 或者您可以尝试将所有逗号分隔值以 json 格式插入数据库,但“分发”数据类型必须为 varchar
【解决方案2】:

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

另外,对于我的示例,我使用了 PDO 而不是 mysqli_,但原理是相同的。查看bind_param。最后,我会考虑创建一些有助于清理脚本的有用类。下面是一些基本示例。

/classes/User.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);
            }
    }

/classes/Database.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;
            }
    }

/new_rechargecard.php

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);
}
?>

表单 HTML:

<form class="form-horizontal form-label-left" action="new_rechargecard.php" method="POST">
    <input type="hidden" name="action" value="update_user" />
    <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 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"></td>
            </tr>
        </tbody>
    </table>
</form>

【讨论】:

    猜你喜欢
    • 2016-05-25
    • 1970-01-01
    • 2015-07-14
    • 2016-08-25
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    相关资源
    最近更新 更多