创建一个以php变量为名称的MySql表

时间:2020-05-05 21:23:23

标签: php mysql database mysqli

我正在尝试编写一个基本函数,以名称作为参数来创建表。

当我执行函数时,出现此错误: “您的SQL语法有错误;请在与MySQL服务器版本相对应的手册中找到在'(id int(10)unsigned NOT NULL AUTO_INCREMENT,nom VARCHAR(255),questio'附近第1行附近使用正确语法的正确语法“

我看了很多论坛帖子,似乎这种语法对某些人有效,但对meeee无效! 这是我的代码:

function connexion_bd() {
    $serv ="localhost";
    $username = "root";
    $pwd = "blah_blah";
    $bd ="project";
    $connex = mysqli_connect($serv, $username, $pwd, $bd);  
    if (! $connex) {
        page_erreur(ERR_CONNEX, mysqli_connect_error($connex)); exit; 
    }
    return $connex;
}

function creer_jeu_bdd($nom) {
    $connex = connexion_bd();

    $nom = mysqli_real_escape_string($connex,$nom);

    $req = "CREATE TABLE IF NOT EXISTS ".$nom." ( 
        id int(10) unsigned NOT NULL AUTO_INCREMENT,
        nom VARCHAR (255),
        question text NOT NULL,
        reponse1 VARCHAR(256) NOT NULL DEFAULT ``,
        reponse2 VARCHAR(256) NOT NULL DEFAULT ``,
        reponse3 VARCHAR(256) NOT NULL DEFAULT ``,
        bonne_reponse TINYINT(2) UNSIGNED NOT NULL,
        foreign key (nom) references jeux(nom),
        primary key(`id`)
    )ENGINE=InnoDB DEFAULT CHARSET=utf8; ";
    $resultat = mysqli_query($connex, $req);

    if (!$resultat) {
        page_erreur(ERR_REQUETE, mysqli_error($connex)); 
    } elseif (mysqli_num_rows($resultat) > 0) {
        page_erreur(ERR_LOGIN, ''); 
    }
    mysqli_close($connex);
    exit;
}

非常感谢。

1 个答案:

答案 0 :(得分:0)

您的varchar默认值必须为char,因此请使用单引号和反引号

请检查When to use single quotes, double quotes, and backticks in MySQL

const getCurrentDate=()=>{

      var date = new Date().getDate();
      var month = new Date().getMonth() + 1;
      var year = new Date().getFullYear();

      //Alert.alert(date + '-' + month + '-' + year);
      // You can turn it in to your desired format
      return date + '-' + month + '-' + year;//format: dd-mm-yyyy;
}