如何将数组插入数据库?

时间:2018-08-14 04:07:58

标签: php mysql mysqli

我在这里是新手,应该明确说明我不是计算机程序员,只是出于业余爱好。结果,我知道我的代码不是完美的,只是想知道如何将以下数组添加到数据库中。

目前,仅插入一个阵列。我正在尝试遵循有关如何进行php测验的php教程,但是此人没有使用implode()serialize()。如何插入单独的行?我希望我已经正确格式化了。

<?php

include_once 'includes/dbh.php';
include_once 'header.php';

$sql = "SELECT * FROM users WHERE user_uid = ?;";

$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
  echo 'SQL statement failed';
} else {
//Bind parameters to the placeholder
  mysqli_stmt_bind_param($stmt, "s", $_SESSION['u_uid']);
//Run parameters inside database
  mysqli_stmt_execute($stmt);
  $result = mysqli_stmt_get_result($stmt);
  $row = mysqli_fetch_assoc($result);


  if ($row['admin'] == 0) {
    header("Location: header.php?add=notadmin");
    exit;
  } else {

    if (isset($_POST['submit'])) {


      include_once 'includes/dbh.php';
      $question_number = $_POST['question_number'];
      $question_text = $_POST['question_text'];
      $correct_choice = $_POST['correct_choice'];
      //Choices array
      $choices = array();
      $choices[1] = $_POST['choice1'];
      $choices[2] = $_POST['choice2'];
      $choices[3] = $_POST['choice3'];
      $choices[4] = $_POST['choice4'];



      $correct_choice = $_POST['correct_choice'];

      $sql2 = "INSERT INTO questions (question_number, text) VALUES (?,?);";

      $stmt = mysqli_stmt_init($conn);
      if (!mysqli_stmt_prepare($stmt, $sql2)) {
        echo 'SQL statement failed';
      } else {
        //Bind parameters to the placeholder
        mysqli_stmt_bind_param($stmt, "is", $question_number, $question_text);
        //Run parameters inside database
        mysqli_stmt_execute($stmt);



        foreach($choices as $choice => $value) {

          if ($value != '') {
            if ($correct_choice == $choice) {
              $is_correct = 1;
            } else {
              $is_correct = 0;
            }




            // Choice query

            $sql3 = "INSERT INTO choices (question_number, is_correct, text) VALUES (?,?,?);";



            $stmt = mysqli_stmt_init($conn);
            if (!mysqli_stmt_prepare($stmt, $sql3)) {
              echo 'SQL statement failed';
            } else {
              //Bind parameters to the placeholder
              mysqli_stmt_bind_param($stmt, "iis", $question_number, $is_correct, $value);
              mysqli_stmt_execute($stmt);
            }

            header("Location: quiz.php?add=success");
            exit();
          }
        }

      }
    }
  }
}  

这是print_r($choices)的输出:

Array (
    [question_number] => 2 
    [question_text] => how many beat is a crotchet? 
    [choice1] => one 
    [choice2] => two 
    [choice3] => three 
    [choice4] => four 
    [correct_choice] => 1 
    [submit] => submit 
) 

我想知道为什么我$value时显示所有echo $value;;只有第一个变量输出任何东西。

我还想知道...用程序mysqli编写$result = mysqli->query();相当于什么?这和写$result = mysqli_stmt_execute($stmt);一样吗?

2 个答案:

答案 0 :(得分:2)

首先,这里是您的代码,需要进行重大清理:

include_once 'includes/dbh.php';
include_once 'header.php';

$stmt = $conn->prepare('SELECT * FROM users WHERE user_uid = ?');
$stmt->bind_param('i', $_SESSION['u_uid']);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();

if (!$row['admin'])
{
    header("Location: header.php?add=notadmin");
    exit;
}

if ($_POST && !array_diff_key(array_flip(['question_number', 'question_text', 'correct_choice', 'choice1', 'choice2', 'choice3', 'choice4']), array_filter($_POST, 'strlen')))
{
    for ($i = 1; $i <= 4; ++$i)
        if ($_POST['correct_choice'] == $_POST["choice$i"])
            break;

    if ($i > 4)
        die('There is no correct choice.');

    $stmt = $conn->prepare('INSERT INTO questions (question_number, text, correct_choice) VALUES (?,?,?)');
    $stmt->bind_param('is', $_POST['question_number'], $_POST['question_text'], $i);
    $stmt->execute();

    $stmt = $conn->prepare('INSERT INTO choices (question_number, choice_number, text) VALUES (?,?,?)');
    for ($i = 1; $i <= 4; ++$i)
    {
        $stmt->bind_param('iis', $_POST['question_number'], $i, $_POST["choice$i"]);
        $stmt->execute();
    }

}
header("Location: quiz.php?add=success");

更改之处:

  1. 确保所有必需的数据都在$_POST中发送;
  2. questions现在包含正确答案的ID;
  3. choices现在具有从1到4标识的选项;
  4. 以面向对象的编程方式使用MySQLi的意图;
  5. 请注意,我刚刚在循环外创建了$stmt。准备好的语句可以重复使用,您不必每次都声明它。

这样,事情的结构会更好。

是的,回到问题所在。存储阵列。

通常,将数组存储在称为one-to-many relationship的数据库中,在这种情况下,每个问题都有4个选择的答案,每个选择在choices表中都有自己的记录,但是本质上是组的一部分(如果需要,则是数组的一部分)。

您可以序列化,但这意味着MySQL服务器不再负责索引和搜索该数据,只有您的应用程序(知道如何序列化)才能做到这一点。在大多数情况下,这并不重要。

我想你想知道如何找回这个“数组”。您是这样做的:

$stmt = $conn->prepare('SELECT choice_number, text FROM choices WHERE question_number = ? ORDER BY choice_number ASC');
$stmt->bind_param('i', $question_number);
$stmt->execute();
$res = $stmt->get_result();
$choices = [];
while ($row = $res->fetch_assoc())
    $choices[$row['choice_number']] = $row['text'];

$choices是数组,返回给您。

我希望这可以消除一些疑问,因为您的问题还不清楚,我不确定这是否有帮助。

答案 1 :(得分:0)

我个人更喜欢json_encode()方法将数组存储到数据库表中。这是描述这种情况的示例:

// An example PHP array
$yourArray = array(
                'Hello', 
                'World', 
                array(
                    1,
                    2,
                    3,
                    "What's up?"
                ) 
            );

// Encode $yourArray array into a JSON string
$yourArrayEncoded = json_encode($yourArray);

// Let's escape single / double quotes before saving it into database
$escapedStr = mysqli_real_escape_string($GLOBALS['connection'], $yourArrayEncoded);

// Insert the string into a table column
$sql = "INSERT INTO foo (bar) VALUES ('$escapedStr')";

// Stripping slashes and converting json string into the original array
print_r( json_decode ( stripslashes ($escapedStr) ) );

我希望这会对您有所帮助。仅此而已!