0

我正在尝试将表单数据插入到我的 sql 表中。表单数据是一个包含多个问题的长问卷。这意味着我要插入的表有多个列,准确地说是 30 列。

有没有办法让我用最少或高效的代码快速插入一行 30 列?也许我可以让表单中的“名称”值等于表中的变量名称?我的表单是普通文本字段和一些复选框组的混合体。

我正在使用 php 并希望使用 mysqli 准备好的语句。

TLDR:我可以缩短这个吗?:

$query = "INSERT INTO table (a, b, c, d, e , f , g , h ,i j, ........) 
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,....)";

mysqli_stmt_bind_param($stmt,'sssiiisiiiiiiiiiisss...', ....);

还是我需要暴力破解它?

4

2 回答 2

1

Afaik no you can't shorten it.

But you could change your DB model that a result record only contains one answer which is linked to the question and to the user the answer is from. So you are also variable on how many questions there are in a quiz. And you don't have an oversize of 28 columns if the quiz only have 2 questions.

table: user
-----------
id (PK)
username

table: quiz
-----------
id (PK)
title (FK)

table: question
---------------
id (PK)
question
quiz_idfk (FK)


table: answer
-------------
id (PK)
answer
question_id (FK)
user_id (FK)

With that model the insert of a result would be (only pseudo code):

foreach($_POST['answer'] as $qid => $ans) {
    // sql: INSERT INTO answer SET answer = :ans, question_id = :qid, user_id = :uid

    // :ans the answer text ($ans)
    // :qid the question id ($qid)
    // :uid the currently logged in user
}
于 2013-11-07T14:02:20.720 回答
1

您可以尝试调用mysqli_stmt_bind_paramusingcall_user_func_array并传入参数数组:

$sql_link = mysqli_connect('localhost', 'my_user', 'my_password', 'world'); 
$type = "isssi"; 
$param = array("5", "File Description", "File Title", "Original Name", time()); 
$sql = "INSERT INTO file_detail (file_id, file_description, file_title, file_original_name, file_upload_date) VALUES (?, ?, ?, ?, ?)"; 
$sql_stmt = mysqli_prepare ($sql_link, $sql); 

call_user_func_array('mysqli_stmt_bind_param', array_merge (array($sql_stmt, $type), $param); 
mysqli_stmt_execute($sql_stmt); 

资源

于 2013-11-07T14:32:24.383 回答