【问题标题】:Insert multiple columns into table using mysqli使用mysqli将多列插入表中
【发布时间】:2013-11-07 13:25:21
【问题描述】:

我正在尝试将表单数据插入到我的 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...', ....);

还是我需要暴力破解?

【问题讨论】:

    标签: php sql mysqli


    【解决方案1】:

    您可以尝试使用call_user_func_array 调用mysqli_stmt_bind_param 并传入一个参数数组:

    $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); 
    

    source

    【讨论】:

      【解决方案2】:

      Afaik 不,你不能缩短它。

      但是您可以更改您的数据库模型,使结果记录仅包含一个答案,该答案与问题和答案来自的用户相关联。因此,您对测验中有多少问题也有所不同。如果测验只有 2 个问题,您不会有 28 列的过大。

      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)
      

      使用该模型,结果的插入将是(仅伪代码):

      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
      }
      

      【讨论】:

      • 感谢您的回复。虽然这不是我想要的,但它绝对是将来有用的东西。对于我的需要,以这种方式更改数据库确实不值得。不过谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-17
      • 1970-01-01
      • 2013-10-31
      • 2015-01-19
      • 1970-01-01
      相关资源
      最近更新 更多