使用可变表名创建mysql表 [英] creating mysql tables with variable table names

查看:49
本文介绍了使用可变表名创建mysql表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个平台,在该平台中可以从 php 创建表并命名为提交者类型的变量.我这里的代码导致了 mysql 语法错误.我相信这是括号放置的问题,但我尝试过的每种组合都不成功,有人能弄清楚吗?我去掉了不正确的括号以减少混淆

I am trying to create a platform where tables can be created from a php from and named as the variable that the submitter types. The code I have here has causes a mysql syntax error. I believe it is a matter of parenthesis placement but every combination I have tryed ha been unsuccessful can anyone figure it out? I have taken out the incorrect parenthesis to make it less confusing

    <?php

if (isset($_POST['submit']))
{ 
$name=$_POST['name'];

mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());


mysql_query("CREATE TABLE '$name'(
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
name VARCHAR(30),
age INT)")
or die(mysql_error());  

echo "Table Created!";

?>   <html><form method='POST'>..........</html>

推荐答案

在 SQL 文本中的表名周围使用反引号:

Use backticks around the table name in your SQL text:

mysql_query("CREATE TABLE `$name`(

反引号是 MySQL 中标识符的默认分隔符.(注意:可以启用其他分隔符,但您并不真的想去那里.)

The backticks are the default delimiter for identifiers in MySQL. (Note: it is possible to enable other delimiters, but you don't really want to go there.)

如果标识符是保留字,包含空格等,则反引号是必需的(反引号在很多情况下可以省略,但在不需要时使用它们并没有错.基本上,认为规则为总是在标识符周围使用反引号",并在方便时省略它们并且您确定它们不是必需的.)

The backticks are required if the identifier is a reserved word, contains white space, etc. (The backticks can be omitted in a lot of cases, but it's not wrong to use them when they aren't required. Basically, think of the rule as "always use backticks around identifiers", and omit them when its convenient and you are sure they aren't required.)

这篇关于使用可变表名创建mysql表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆