php/sql - 在多个字段上插入相同的值

标签 php mysql

我有这段代码(这是工作并将这些变量传递给另一个文件)

            var month = "<?php echo openedMonthbid();?>";
    var user = "<?php echo $_SESSION['member_id'];?>";
    var day = new Array();


    $(':checkbox:checked').each(function(i){
    day.push('`' + $(this).val() + '`');  });
    var count = day.length;

                            $.ajax({
                            type: "POST",
                            url: "sendBidding.php",
                            data : "user="+user+"&days="+day+"&month="+month+"&number=",
                            dataType: "json",

发送竞价.php

$month = $_POST['month'];
$user = $_POST['user'];
$days = $_POST['days'];
$count = $_POST['count'];//if a check 3 values I get '3'


      mysql_query("INSERT INTO $month ($days) VALUES ('1','1','1')");


    $result = true;

    echo json_encode(array("success"=>$result,
                               "datas" => $data,
                                "mon"=>$month));

我想添加与所选天数一样多的值(“1”)。如何更改 VALUES ('1','1','1')?

最佳答案

下面是生成一系列相同字符串的解决方案。使用 array_fill() .

$month = $_POST['month'];
$days = $_POST['days'];

// Be sure to whitelist $month and $days before using them in an SQL query!  
// For example, you could store an associative array keyed by month,
// containing lists of the day column names.
$month_table_whitelist = array(
  "month_jan" => array("day1", "day2", "day3", /* etc */),
  "month_feb" => array("day1", "day2", "day3", /* etc */),
  /* etc */
);
if (!array_key_exists($month, $month_table_whitelist)) {
  die("Please specify a valid month.");
}
if (!array_search($days, $month_table_whitelist[$month])) {
  die("Please specify a valid day of month.");
}

$count = $_POST['count'];//if a check 3 values I get '3'

$tuples = array_fill(1, $count, "('1')");

$status = mysql_query("INSERT INTO $month ($days) VALUES ".implode(",", $tuples));
if ($status === false) {
  die(mysql_error());
}

PS:通过将不安全的值 $month 和 $days 直接插入到您的查询中,您的查询容易受到 SQL 注入(inject)攻击。您应该使用白名单方法来确保这些输入与数据库中的真实表名和列名匹配,不要只相信用户输入。

PPS:您应该知道您正在使用 ext/mysql 函数,但这些函数已被弃用。如果这是一个新应用程序,您应该在投入更多时间使用已弃用的 API 之前开始使用 mysqli 或 PDO。

关于php/sql - 在多个字段上插入相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14676513/

相关文章:

PHP 和 API 调用性能和最佳实践的一对多关系

php - 如何统计变量值是否重复?

mysql - 我怎样才能使用MySQL得到以下结果

php - 无法使密码加密工作 PHP

php - Laravel Eloquent : Update A Model And its Relationships

php - 将特定的 'ID' 插入到我的表中。

mysql - C# Entity Framework : There is already an open DataReader associated with this Connection which must be closed first

php - 缓存来自 rss 提要的链接

mysql - 如何在模型中存储日期?

php - 在 PHP 中显示带有序数后缀的日期