[英]Creating a MySql table with a php variable as a name
我正在嘗試編寫一個基本的 function 創建一個以名稱作為參數的表。
When I execute the function I get this error: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '( id int(10) unsigned NOT NULL AUTO_INCREMENT, nom VARCHAR (255),第 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;
}
非常感謝。
您的 varchar 的默認值必須是 char,因此請使用單引號和 niot 反引號
$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; ";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.