用PHP变量创建MySQL表 [英] Create MySQL table with PHP variable

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

问题描述

我正在尝试创建一个表,该表的名称是存储在变量$name中的值.我尝试了许多不同的方法,但似乎没有一种对我有用.这是我当前正在使用的代码:

I'm trying to create a table whose name is the value of what is stored inside the variable $name. I have tried numerous different methods but none seem to work for me. Here is the code I am using currently:

 mysql_connect("localhost", "peltdyou_admin", "123456") or die(mysql_error()); 
 mysql_select_db("peltdyou_orders") or die(mysql_error()); 
 mysql_query("CREATE TABLE '" .$_POST['name']. "' ( name VARCHAR(30), age INT, car VARCHAR(30))");

我知道这与'" .$_POST['name']. "'有关,但我无法解决. 我已经尝试在其位置上使用'$name',以便在代码中进一步获得它的价值.

I know it is something to do with '" .$_POST['name']. "' but I can't work out what. I have tried '$name' in its place which gets it's value from further up in the code.

任何帮助都会很棒!

推荐答案

在表名(而不是引号)周围使用反引号.并逃避输入!另外,虽然这在localhost上有效,但是请确保在生产服务器上运行的用户具有创建表的特权(当然,在共享主机上通常不是AFAIK).

Use backticks around table name, not quotes. And escape the input! Also, while this works on localhost, make sure that the user running on your production server has the privilege to CREATE tables (usually it's not, AFAIK, on shared hostings of course).

警告语:您确定要在用户输入上创建表吗?您将以这种方式创建多少个表?您不能只是重新设计整个内容,而是插入 values 吗?

A word of warning: are you really sure you want to create a table on a user input?? how many tables are you going to create in this way? Can't you just redesign the whole thing so that you insert values instead?

$name = mysql_real_escape_string($_POST['name']);
mysql_query("CREATE TABLE `".$name."` ( name VARCHAR(30), age INT, car VARCHAR(30))");

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

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