使用php变量创建mysql表不起作用 [英] Create mysql table with php variable not working
问题描述
我是php的新手,这可能是一个愚蠢的错误...但是我不知道发生了什么.我正在尝试使用php在数据库中创建一个表.我想用用户名命名该表.我正在使用变量$tableusername
.这是我的代码
I'm pretty new to php.. and this is probably a stupid mistake... but I have no idea what is going on. I'm trying to create a table in my database using php. I want to name the table after the username. I'm using the variable $tableusername
. Here's my code
$sql="SELECT * FROM userdata WHERE username='$username'";
$result=mysql_query($sql);
while ($row = mysql_fetch_assoc($result))
{
$tableusername = $row["username"];
}
$create = "CREATE TABLE `".$tableusername."` ('
. ' `ID` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, '
. ' `please` VARCHAR(50) NOT NULL, '
. ' `make` VARCHAR(50) NOT NULL, '
. ' `this` VARCHAR(50) NOT NULL, '
. ' `work` VARCHAR(50) NOT NULL'
. ' )'
. ' ENGINE = myisam;";
mysql_query($create)
?>
<html>
<head>
</head>
<body>
You have successfully signed up. <?php echo $tableusername ?>
</body>
</html>
如此-这将创建一个名为$tableusername
的表.变量不会保留.但是-当我echo $tableusername
-变量结转.我对此很陌生-因此,我们将不胜感激.
So- This creates a table named $tableusername
. The variable doesn't carry over. BUT- when I echo $tableusername
- the variable carries over. I'm pretty new to this - so any help is appreciated.
推荐答案
在您的SQL查询之后添加它-(它确实可以帮助并加快错误纠正时间)
Add this after your SQL querys - (It really helps and speeds up error correcting time)
or die("A MySQL error has occurred.<br />Error: (" . mysql_errno() . ") " . mysql_error());
在您的实例中
echos :
发生MySQL错误.
错误:(1064)您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册,以在''附近使用正确的语法. 'ID
INT非空AUTO_INCREMENT主键,'.第1行的please
VARCH'
A MySQL error has occurred.
Error: (1064) 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 NOT NULL AUTO_INCREMENT PRIMARY KEY, ' . ' please
VARCH' at line 1
这然后向我表明该错误与"和'有关.
This then indicates to me that the error regards " & '.
将代码更改为包含单引号并执行后,现在没有回显.
After changing the code to contain single quotes and executing it, there is now no echo.
<?php
$tableusername = "philip";
$create = "CREATE TABLE `".$tableusername."` ("
. " `ID` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, "
. " `please` VARCHAR(50) NOT NULL, "
. " `make` VARCHAR(50) NOT NULL, "
. " `this` VARCHAR(50) NOT NULL, "
. " `work` VARCHAR(50) NOT NULL"
. " )"
. " ENGINE = myisam;";
mysql_query($create)or die("A MySQL error has occurred.<br />Error: (" . mysql_errno() . ") " . mysql_error());
?>
注意:当使用PHP中嵌入的SQL时,请参考 MySQLi 扩展. mysql_ *正在弃用过程中.
Note: Please refer to the MySQLi extension when using SQL embedded in PHP. mysql_* is in a deprecation process.
希望这会有所帮助.
这篇关于使用php变量创建mysql表不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!