PHP创建表脚本并在表中插入数据

时间:2017-02-25 09:44:27

标签: php mysql post

  

我收到错误“未定义的变量:第15行的C:\ xampp \ htdocs \ online test \ study_question1.php中的表”如何创建表并在其中添加数据。

 <?php
    $connection = mysqli_connect('localhost','root','','userquestion') or die(mysqli_error($connection));
    define("table","table_name");
        if(isset($_POST['next'])){
            $table=$_POST['table_name'];
            $query= "CREATE TABLE `userquestion`.`$table` ( `id` INT(15) NOT NULL AUTO_INCREMENT , `question` TEXT CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL , `option1` TEXT CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL , `option2` TEXT CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL , `option3` TEXT CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL , `option4` TEXT CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL , `true_ans` TEXT CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB;";
            $data = mysqli_query($connection,$query);
            header('Location: study_question1.php');

            return $table;
        }
 ?>

<?php
    include "online.php";
    $connection = mysqli_connect('localhost','root','','userquestion') or die(mysqli_error($connection));
    if(isset($_POST['submit'])) {
       $question = $_POST["question"];
       $option1 = $_POST['option1'];
       $option2 = $_POST['option2'];
       $option3 = $_POST['option3']; 
       $option4 = $_POST['option4'];
       $true_ans = $_POST['true_ans'];
       $query = "INSERT INTO `userquestion`.`$table` (question,option1,option2,option3,option4,true_ans) VALUES ('$question','$option1','$option2','$option3','$option4','$true_ans')"; 
       $data = mysqli_query($connection,$query);
       if($data) {
         echo "ab dusra dal..."; 
       }
    } 

 ?>

2 个答案:

答案 0 :(得分:0)

您未在table中声明study_question1.php变量。你可以这样做:

Code1.php

<?php
$tableName = 'name';
header('Location: Code2.php?tableName=' . $tableName);

然后在Code2.php中

<?php
$tableName = $_GET['table'];

使用session也可以达到类似效果。

答案 1 :(得分:0)

在您的查询中,您使用$table这是常量而不是仅使用table而不使用$符号,您不能将常量用作变量。

希望这会对你有所帮助:)。