Cannot create SQL table with query variable as table name in PHP - php

I am passing a query variable in PHP. I would like to make it the table name, but I know there is probably a SQL syntax error. When I print the statement, the variable is passed meaning it works, but the database simply isn't created.
Here is my code for the creation of the database:
$DBName = "database_name";
$sql = "CREATE TABLE '$DBName'.'$login' (
ClientID int NOT NULL AUTO_INCREMENT,
AgentClients varchar(15),
ClientTotal int
)";
mysql_query($sql,$link);
where `$login = $_POST['login'];
Also, I'm not worried about security breaches at the moment, so don't worry about that.
Any insight would be greatly appreciated.

You must use backticks for your tablename, and not quotes:
$sql = "CREATE TABLE `$DBName`.`$login` (
ClientID int NOT NULL AUTO_INCREMENT,
AgentClients varchar(15),
ClientTotal int,
PRIMARY KEY (`ClientID`)
)";

Related

Create TABLE using PHP, according to input [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 3 years ago.
I am about to create a table, but I want to declare it based on the user's input. thankyou for any response, all answers are appreciated, more power!
I am receiving this error (Error creating table: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''2020-2021' ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR' at line 1)
here's the sample code I am doing.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mias";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$table = $_POST['usersinput'];
// sql to create table
$sql = "CREATE TABLE $table (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
if ($conn->query($sql) === TRUE) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
Try this code by replacing your code. It will work. i have tried. Problem in your last line of your code.
CREATE TABLE $table(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30),
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP)
As Nigel has said in the comment, it's definitely a bad idea to allow user input to create a table.
How I would think about doing this would be to use relationships between the Table Guests and the Table or Booking you want them to be added to.
You would just need to create two tables, one for the Booking and one for the Guests then in the Guests table, have a Booking_ID field which would contain the ID of the bookings the user should be added to.
This way, when you want to look for Guests for a specific table, you would be able to do SELECT * FROM MyGuests WHERE booking_id=[the booking id] and this would return the guests for that table.
Like other users stated there are several reasons (most importantly security) not to do that, but if you really want it you have to use concatenation for your string:
Option
$sql = "CREATE TABLE {$table}(id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30), email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP)";
Option
$sql = "CREATE TABLE" . $table . "(id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30), email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP)";

Use a variable as table name when creating a table in mysql

I have variable whos value is a random number between 0 and 1000, I would like to use this as the name when creating a new table. I have tried to do this by concatenating my sql with the variable that stores the random number, this hasn't worked, is there a way of doing this? Thanks
include 'includes/db_connect_ssg.php';
if (isset($_POST['new_user_name'])&&isset($_POST['new_user_password'])) {
$username = $_POST['new_user_name'];
$password = $_POST['new_user_password'];
$randID = rand(0,1000);
$sql = "INSERT INTO `Users`(`id`, `username`, `password`, `admin`, `href`) VALUES ('$randID','$username','$password','0','ssgprofile.php?id=$randID')";
$query = mysqli_query($dbc, $sql);
$id = (string)$randID;
$q = "CREATE TABLE CONCAT('userTable_',$id) (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
$qquery = mysqli_query($dbc, $q);
if ($query&&$qquery) {
include 'admin_loadUsers.php';
}else{
echo "Could not connect sorry please try again later, for more info please contact BB Smithy at 0838100085";
}
}
You could just use:
$q = "CREATE TABLE `userTable_".$id."` (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
But beware, creating a table with name containing a number is nearly always a sign of bad database design.
Instead of creating many tables with just one row, simply add columns firstname, lastname, email and reg_date to your table Users. Also your way of generating user ID by calling rand(0,1000) will result in collisions (rand will return a value which is already used as an ID in Users table). Use AUTO_INCREMENT for generating user IDs.
You do not have a valid table name
From the Mysql docs:
Identifiers may begin with a digit but unless quoted may not consist solely of digits

Foreign Key Failure in MySQL

I have created a database composed of three tables. This is my query in creating my tables with Foreign Key.
CREATE TABLE reporter
(
reporterid INT NOT NULL AUTO_INCREMENT,
firstname VARCHAR(1000) NOT NULL,
lastname VARCHAR(100) NOT NULL,
PRIMARY KEY (reporterid)
);
CREATE TABLE flood
(
floodid INT NOT NULL AUTO_INCREMENT,
address VARCHAR(500) NOT NULL,
description VARCHAR(1000) NOT NULL,
dateofflood DATE NOT NULL,
timeofflood INT NOT NULL,
PRIMARY KEY (floodid)
);
CREATE TABLE reports
(
reportid INT NOT NULL AUTO_INCREMENT,
timereport NODATATYPE NOT NULL,
datereport DATE NOT NULL,
rid INT NOT NULL,
fid INT NOT NULL,
PRIMARY KEY (reportid),
FOREIGN KEY (rid) REFERENCES reporter(reporterid),
FOREIGN KEY (fid) REFERENCES flood(floodid)
);
I created a system in order for me to add records/row on my database through PHP. This is my code:
<?php
mysql_connect("localhost", "root", "") or die("Connection Failed");
mysql_select_db("flooddatabase")or die("Connection Failed");
$description = $_POST['description'];
$address = $_POST['address']; // Make sure to clean the
$dateofflood=$_POST['dateofflood'];
$timeofflood=$_POST['timeofflood'];
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$dateofreport=$_POST['dateofreport'];
$timeofreport=$_POST['timeofreport'];
$query = "INSERT into flood(address,description,dateofflood,timeofflood) values ('$address','$description','$dateofflood','$timeofflood')";
$query2 = "INSERT into reporter(firstname,lastname) values ('$firstname','$lastname')";
$query3 = "INSERT into reports(dateofreport,timeofreport) values ('$dateofreport','$timeofreport')";
if(mysql_query($query))
if(mysql_query($query2))
if(mysql_query($query3))
{
echo "";
} else
{
echo "fail";
}
?>
The result that I am getting is fine. It's just that, in my REPORTS table, there is no foreign key that is being generated. For example I input something on my reporter table and flood table, the foreign key 'rid' and 'fid' has no values that references to both tables. Need help thank you.
Get the just inserted Primary key value from flood table insert
query. And store it to a variable say $f_id;
Get the just inserted primary key value from reporter table insert
query and store it to a variable say $r_id;
Now Make your last insert statement like below:
"INSERT into reports(dateofreport,timeofreport,rid,fid) values ('$dateofreport','$timeofreport',$r_id,$f_id)";
I am not giving you a direct copy paste solution.
If you need to know how to get the last inserted id by executing an insert query then look at this link
there is no foreign key that is being generated
I'm not entirely sure what you even mean by that. Foreign keys aren't "generated". Primary keys can be, which you do:
reporterid INT NOT NULL AUTO_INCREMENT
(as well as for your other two tables)
the foreign key 'rid' and 'fid' has no values
Well, look at your query:
INSERT into reports(dateofreport,timeofreport) values ...
Where do you insert values for rid and fid? I'm actually pretty surprised this query works at all, since those columns don't allow NULL values:
rid INT NOT NULL,
fid INT NOT NULL,
(Though your column names also don't line up, so I find it likely that the code you're showing isn't actually the code you're using...) That point aside however, the fact still remains that if you want a value in those fields then you have to put a value in those fields:
INSERT into reports(dateofreport,timeofreport,rid,fid) values ...
After each query, you can get the last generated identifier from mysql_insert_id():
$last_id = mysql_insert_id();
Use that to then populate the values being inserted as foreign keys in subsequent queries.
Also worth noting, the mysql_* libraries are long since deprecated and have been replaced with mysqli_ and other libraries such as PDO. I highly recommend you upgrade to a current technology, since what you're using isn't supported by any vendor.
Additionally, and this is very important, your code is wide open to SQL injection attacks. This basically means that you execute any code your users send you. You should treat user input as values, not as executable code. This is a good place to start reading on the subject, as is this.

wordpress plugin sql setup

I have set up four additional tables for my plugin to use what I am trying to do is take a name and assign it a ID then use this data to populate drop down menus with a name and the same for class and position I am unsure as to how to do this correctly this is what i have so far.
$sql = "CREATE TABLE $tableName (
recordID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(recordID),
driverID int,
driverName varchar(30),
classID int,
driverClass varchar(20),
posID,
driverPosition varchar(6),
trackName varchar(30),
raceDate date
);";
$sql = "CREATE TABLE $driverTableName (
driverID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(driverID),
driverName varchar(30)
);";
$sql = "CREATE TABLE $classTableName (
classID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(classID),
className varchar (20)
);";
$sql = "CREATE TABLE $posTableName (
posID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(posID),
posName varchar(6)
);";
The bottom three tables will store the data I want to populate the drop down boxes to create a record with I am unsure as to how to link them to the top table where this record will be stored.
This is pretty much a indexing issue. If you are going to access the database separately to the standard calls that Wordpress provides, you should at the very least use http://codex.wordpress.org/Class_Reference/wpdb as it will save you some coding time.
The rest of it is a MySQL question. (Assuming you are using MySQL) In how to properly index the data together and then parsing the data as it comes in.

Create MySQL table with PHP variable

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))");
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.
Any help would be great!
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).
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))");
Put it in another variable and it will work, there's a conflict with the "'" character in the POST variable and in the mysql_query.
<?php
mysql_connect("localhost", "peltdyou_admin", "123456") or die(mysql_error());
mysql_select_db("peltdyou_orders") or die(mysql_error());
$name = mysql_real_escape_string($_POST['name']);
mysql_query("CREATE TABLE '$name' ( name VARCHAR(30), age INT, car VARCHAR(30))");
?>
I posted this code to help you in your code but you should not use the mysql_* functions you should use the mysqli_* functions.
You can read more about them here:
http://php.net/manual/en/book.mysqli.php
You should really be using PDO or MySQLi instead of mysql_* functions. mysql_* functions are in the process of being deprecated and they are full of security holes.
With that said you don't need to quote your table name and instead should use nothing or backticks.
Using the newest Mysqli connector, you can do something like this:
1. Create a variable from the user's input like so $variable=$_POST['name']
2. Use the variable in your query as shown in the complete code below here
$variable=$_POST['name'];
mysqli_connect("localhost", "peltdyou_admin", "123456") or die(mysql_error());
mysqli_select_db("peltdyou_orders") or die(mysqli_connect_error());
mysqli_query("CREATE TABLE $variable ( name VARCHAR(30), age INT, car VARCHAR(30))");
$query = "CREATE TABLE $name" . '(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
age INT,
name varchar(30),
car VARCHAR(30)
)';
CREATE TABLE IF NOT EXISTS `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL,
`description` text NOT NULL,
`price` double NOT NULL,
`created` datetime NOT NULL,
`modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;

Categories