php - 向数据库插入未知数量的输入
问题描述
我在数据库中有 2 个表,问题表和机会表。问题是我希望用户能够通过单击显示“插入更多机会输入 []”的按钮来添加更多机会,我不知道如何告诉 PHP 将这个未知数量的输入插入到数据库。
// Check connection
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$title= $_POST['question'];
$timer= $_POST['timer'];
$points= $_POST['points'];
$sql1 = "INSERT INTO questions (title, timer, points)
VALUES ('$title','$timer','$points')";
if (mysqli_query($conn, $sql1)) {
echo "QUESTION ADDED TO DB SUCCESSFULLY!";
echo "ADDING CHANCES TO THEIR TABLE...";
$questionid = mysqli_insert_id($conn);
$titles= $_POST['chance']; //the problem starts from here
$status= 0; //initially
$sql = "INSERT INTO chances (questionid, titles, status)
VALUES ('$questionid','$titles','$status')";
} else {
echo "Error QUESTION DIDN'T ADDED: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Static Template</title>
</head>
<body>
<form method="post">
<h1>new question</h1>
<input type="text" name="question" placeholder="question">
<input type="num" name="timer" placeholder="timer">
<input type="num" name="points" placeholder="points">
<br><br>
<h1>question chances</h1>
<input type="text" name="chance[]" placeholder="chance-1">
<input type="text" name="chance[]" placeholder="chance-2">
<input type="text" name="chance[]" placeholder="chance-3">
<input type="text" name="chance[]" placeholder="chance-4">
<br>
<button>INSERT MORE INPUTS OF CHANCES[]</button>
<input type="submit">
</form>
</body>
</html>
解决方案
您的原始代码容易受到 SQL 注入的攻击,因此以下说明了如何使用prepared statements
来减轻威胁。当您使用chance[]
名称时,您可以有效地发布一个数组,以便您可以遍历发布的值并为该数组中的每个机会执行一个插入语句。该按钮在原始问题中似乎没有做任何事情,所以我即兴创作了chance
在提交表单之前添加新输入元素的方法。希望能帮助到你
<?php
$dbhost = 'localhost';
$dbuser = 'I-am-Gr00t';
$dbpwd = 'xxx';
$dbname = 'xxx';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$results=array();
if( $_SERVER['REQUEST_METHOD'] == 'POST' ){
$chances=isset( $_POST['chance'] ) ? $_POST['chance'] : false;
if( !empty( $chances ) ){
$args=array(
'question' => FILTER_SANITIZE_STRING,
'timer' => FILTER_SANITIZE_NUMBER_INT,
'points' => FILTER_SANITIZE_NUMBER_INT
);
$_POST=filter_input_array( INPUT_POST, $args );
extract( $_POST );
# add the question using a prepared statement
$sql='insert into `questions` (`title`, `timer`, `points`) values (?,?,?)';
$stmt=$db->prepare( $sql );
$stmt->bind_param('sii',$question,$timer,$points);
$stmt->execute();
# id for last record added
$id=$db->insert_id;
$results[]=$id ? sprintf( 'Question "%s" added', $question ) : sprintf( 'Error: failed to add question "%s"',$question );
if( $id ){
#prepare & bind new insert statement
$sql='insert into `chances` (`questionid`,`titles`,`status`) values (?,?,?)';
$stmt=$db->prepare( $sql );
$stmt->bind_param( 'isi', $id, $title, $status );
$status=0;# this could simply be the default value in the chances table and thus be omitted here
#add each chance
foreach( $chances as $index => $title ){
$res=$stmt->execute();
$results[]=$res ? sprintf( 'Chance "%s" added', $title ) : sprintf( 'Error: failed to add "%s"', $title );
}
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Static Template</title>
<style>
body, body *{box-sizing:border-box;font-family:monospace}
fieldset{border:none;margin:2rem 0;padding:0.5rem;box-shadow:2px 2px 15px rgba(0,0,150,0.1);border-radius:0.5rem;}
.chances{margin:0.5rem;}
.chances > input,
button,
[type='submit']{margin:0.25rem!important;padding:0.25rem}
[name='chance[]']{width:120px}
</style>
</head>
<body>
<form method="post">
<fieldset>
<h1>new question</h1>
<input type="text" name="question" placeholder="question" />
<input type="num" name="timer" placeholder="timer" />
<input type="num" name="points" placeholder="points" />
</fieldset>
<fieldset>
<h1>question chances</h1>
<div class='chances'>
<input type="text" name="chance[]" value='chance-1' placeholder="chance-1" />
<input type="text" name="chance[]" value='chance-2' placeholder="chance-2" />
<input type="text" name="chance[]" value='chance-3' placeholder="chance-3" />
<input type="text" name="chance[]" value='chance-4' placeholder="chance-4" />
</div>
</fieldset>
<fieldset>
<button type='button' name='add'>INSERT MORE INPUTS OF CHANCES[]</button>
<input type="submit" />
</fieldset>
<?php
if( !empty( $results ) )printf('<pre>%s</pre>',implode(PHP_EOL,$results));
?>
</form>
<script>
document.querySelector( 'button[name="add"]' ).addEventListener('click', e=> {
let col=document.querySelectorAll('input[name="chance[]"]');
let l=col.length;
let i=l+1;
let input=col[ l - 1 ];
let clone=input.cloneNode( true );
clone.removeAttribute('placeholder');
clone.setAttribute( 'placeholder', 'chance-' + i );
clone.value=clone.getAttribute('placeholder');
input.parentNode.insertBefore( clone, input.nextSibling );
});
</script>
</body>
</html>
推荐阅读
- c++ - 是否可以覆盖在 C++ 中获取结构成员的默认行为?
- python - 如何重载numpy ufuncs
- ruby-on-rails - 来自 AR 对象的 PORO
- tensorflow - 如何为 CPU 安装最新版本的 Tensorflow
- excel - Excel 的 FOR XML PATH 回车
- sql - 语法问题的情况
- javascript - 在多个工作表中添加或删除第一保护中的编辑器
- swift - 如何在 Mac Catalyst 13.0+ 中快速打开 Finder
- python - 为列赋值时矛盾的 pandas.DataFrame 行为
- jenkins - 如何从 jenkins 脚本控制台列出并终止多分支管道的所有正在运行的作业