如何使用php在mysql中设置变量字段名称?

时间:2019-03-29 04:20:20

标签: php mysql

我想创建一个名为“ serial_no”的字段[每次管理员添加一个新问题时都会更改],每次管理员在表“ Questions”中添加一个问题时,都应该从表“ Question”中获取serial_no。 我正在使用下面给出的方法,但出现错误-“无法将mysqli_result类的对象转换为字符串”

$ question已设置为管理员已添加的当前问题。

$query = "INSERT INTO `questions` (Question, option1, option2, option3, option4, answer)
                 VALUES ('$question','$option_a','$option_b','$option_c','$option_d','$answer');";
    $q=mysqli_query($db,$query);
    if (!$q)
      {
        die('Error: ' . mysqli_error($db));
      }
    $_SESSION['question']=$question;
    $_SESSION['option1']=$option_a;
    $_SESSION['option2']=$option_b;
    $_SESSION['option3']=$option_c;
    $_SESSION['option4']=$option_d;
    $_SESSION['answer']=$answer;


    $result = mysqli_query($db,"SELECT serial_no FROM questions WHERE `Question` = '$question';");

    // $update_ques_query = "INSERT INTO leaderboard table........(updating leaderboard table.)
    while($row=$result->mysqli_fetch_array();)
    {
        $query1 = "ALTER TABLE `leaderboard` ADD COLUMN $row INT(5) DEFAULT 0 after score;";
        $q1=mysqli_query($db,$query1);
        if(!$q1)
        {
            die('Error: ' . mysqli_error($db));
        }
    }

1 个答案:

答案 0 :(得分:0)

$query = "INSERT INTO `questions` (Question, option1, option2, option3, option4, answer)
                     VALUES ('$question','$option_a','$option_b','$option_c','$option_d','$answer');";
        $q=mysqli_query($db,$query);
        if (!$q)
          {
            die('Error: ' . mysqli_error($db));
          }
        $_SESSION['question']=$question;
        $_SESSION['option1']=$option_a;
        $_SESSION['option2']=$option_b;
        $_SESSION['option3']=$option_c;
        $_SESSION['option4']=$option_d;
        $_SESSION['answer']=$answer;


        $result = mysqli_query($db,"SELECT serial_no FROM questions WHERE `Question` = '$question'");


               $numRows           = mysqli_num_rows($result);

                if($numRows > 0)
                {

                       while($results   = mysqli_fetch_assoc($result))
                       {
                               $query1 = "ALTER TABLE `leaderboard` ADD COLUMN  ".$results['serial_no']."  INT(5) DEFAULT 0 after score";
                                       $q1=mysqli_query($db,$query1);
                                        if(!$q1)
                                        {
                                            die('Error: ' . mysqli_error($db));
                                        }
                       }


               }

您犯的错误是获取serial_no,希望这会有所帮助。发生“重复的列名错误”是因为您多次添加了列名“ Array”