![](/img/trans.png)
[英]PHP + SQL - insert value of primary key to another field in the same row
[英]php/sql - insert same value on multiple field
我有此代碼(正在工作,並將這些變量傳遞到另一個文件)
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",
sendBidding.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:您的查詢很容易受到SQL注入的攻擊,方法是將不安全的值$ month和$ days直接插值到查詢中。 您應該使用白名單方法來確保這些輸入與數據庫中的實際表名和列名匹配,而不僅僅是信任用戶輸入。
PPS:您應該知道您正在使用ext / mysql函數,但是這些函數已被棄用。 如果這是一個新應用程序,則應先使用mysqli或PDO,然后再投入更多時間使用不推薦使用的API。
$count = $_POST['count'];//if a check 3 values I get '3'
$daystatic="('1')";
mysql_query("INSERT INTO $month ($days) VALUES ". $daystatic . str_repeat ( ",$daystatic" , $count-1));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.