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

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

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)";

Creating table with the domain name fails

I am trying to create a table whenever the user submits his/her domain name. It is definitely going to be a .com or a .net or a .something
The problem is that my code does not create a table when it contains a .anything
it works fine for names and characters without a .something
$domain=$_POST['domain_name'];//it is dramatainment.com
$table = mysqli_query($connection, "CREATE TABLE $domain (
user_id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user_name VARCHAR(100) NOT NULL,
user_domain VARCHAR(50) NOT NULL,
user_email VARCHAR(50),
user_password VARCHAR(50),
user_date date
) ");
if(!$table)
{
die('Could not create table: ' . mysqli_error($connection));
}
Does the creat table command have this limitation? Can this be solved?
You could try to replace the dot by an underscore.
Here you can find which character is allowed in a table name.
Additionally, it is possible to query using this syntax, which would conflict with your table name :
SELECT * FROM dbname.table_name;
UPDATE : it is possible using backticks to enclose table name :
$sql = 'CREATE TABLE `$tableName` (
user_id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user_name VARCHAR(100) NOT NULL,
user_domain VARCHAR(50) NOT NULL,
user_email VARCHAR(50),
user_password VARCHAR(50),
user_date date
)';
Some special characters are invalid for identifiers such as table names.
See http://dev.mysql.com/doc/refman/5.7/en/identifiers.html

SQL database table creation with variable

I am working on a project, and I have to use sql. The variable $file_name needs to be the table name, but when i try this:
$sqlTableCreate = "CREATE TABLE ". $file_name . "(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
The table does not create. I checked by using this:
if ($sqlConnection->query($sqlTableCreate) === TRUE) {
echo 'Created Sucessfully';
} else {
echo 'Table does not create.';
}
I get 'Table does not create' when trying to use this. Help would be greatly appreciated. Thanks in advance!
Your filename contains a extension, but I suspect you just want to use the name without the extension as the name of the table. You can use the basename function to remove the extension.
$sqlTableCreate = "CREATE TABLE ". basename($file_name, ".csv") . "(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
If there can be different extensions, and you want to remove them more generally, see
How to remove extension from string (only real extension!)
I don't see any issue with your posted query but couple things may be wrong
Make sure that there is no table exists with that same name. You can use IF NOT EXISTS marker to be sure like
CREATE TABLE IF NOT EXISTS". $file_name . "(
make sure that the variable $file_name is not empty. Else, you are passing a null identifier in CREATE TABLE statement; which will not succeed.
Per your comment: you have $file_name = 'currentScan.csv';
That's the problem here. You are trying to create a table named currentScan.csv which your DB engine thinking that currentscan is the DB name and .csv is the table name which obviously doesn't exits and so the error.
first check your database connection and change your query with given below :
$sqlTableCreate = "CREATE TABLE ". $file_name . " (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";

Add a unique key to database

I've got a form on my website for users to input their fname, sname, company,phone,email which then gets updated to a database on submit. I also have a field in my database for a unique userID to incase users have same name and company ect. When submitting my form how is it possible to add in this field, a unique number so that it is +1 from the fields taken already. At the minute there are only 3 userIDs so i need the next inputted one to be 4 and so on.
At the moment I have this.
require_once('dbConnect.php');
//taken from a smarty template form.
$addForename = $_POST['forename'];
$addSurname = $_POST['surname'];
$addCompany = $_POST['company'];
$addContact = $_POST['contact'];
$addEmail = $_POST['email'];
public function addUser($addForename,$addSurname,$addCompany,$addContact,$addEmail)
{
$sql = "INSERT INTO `Users` (`Forename`, `Surname`, `ComanyName`, `Phone`, `Email`) VALUES ('".$addForename."','".$addSurname."','".$addCompany."','".$addContact."','".$addEmail."')";
$databaseAccess = new DatabaseConnect();
try
{
$result = $databaseAccess->connect($sql, "add");
}
catch (Exception $e)
{
throw new Exception("Adding User Failed !!!");
}
if ($result)
{
return 1;
}
else{return 0;}
}
thanks
If you are using phpmyadmin there should be a checkbox when youre creating a new column with "A_I" or Auto_Increment.. you have to check that and then it will count your entrys.
Create the row as an auto_increment in the database:
create table someName (ID int primary key auto_increment, col1 int ...);
Then when you are inserting data, either pass it a null, or don't insert that field like this:
insert into someName (col1) values (3);
or
insert into someName (ID, col1) values (null, 3);
You can modify your current table with the following:
ALTER TABLE someName MODIFY COLUMN ID INT NOT NULL AUTO_INCREMENT , ADD PRIMARY KEY (ID);
create the ID:
ALTER TABLE users ADD ID INT UNSIGNED
NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (ID);
and start the auto-increment where you want
ALTER TABLE tbl AUTO_INCREMENT = 4;
Create a column set it as a primary key and auto increment. You can even write a stored procedure for inserting in the table. That way you don't have to write query every time and not have to worry about escape characters. If you want the particular no to be returned from stored procedure use SCOPE_IDENTITY() in the stored procedure.

PHP: How to get data from 2 tables

If I log in with my email and password in table 'students', how can I get the data from the table 'data' where the emailadresses match?
CREATE TABLE `students` (
`email` varchar(150) NOT NULL,
`password` varchar(150) NOT NULL
)
CREATE TABLE `data` (
`student_id` varchar(50) NOT NULL,
`studygroup_id` varchar(50) NOT NULL,
`applied_courses` varchar(50) NOT NULL,
`study_results` varchar(50) NOT NULL,
`email` varchar(150) NOT NULL
)
Well, the easy answer would just be to execute a query like
SELECT * FROM data WHERE email = '$emailAddress'
Where $emailAddress is the email address that has been used to log in.
But you should really think about your schema design. Perhaps go and read some books/tutorials on the basics and there are a number of possible issues with what you have. You should probably have a numeric primary key on your "students" table and reference this as a foreign key in your other table. You should also think about renaming the second table. "Data" doesn't really describe what it does; everything (or very nearly) in a database is data! Plus all your id columns are varchars. Unless you have alphanumeric ids you should make these columns the correct type for the data they hold.
Please clarify question. Where's the password coming from? A script in PHP?
SELECT * FROM data WHERE student.email = "$my_email" AND student.password = "$my_password"
Students table should also contain the student_id
alter table student add column student_id int auto_increment primary key
then the query
select a.email, a.password,b.studentgroup_id, b.applied_course,b.student_result
from student a inner join
data b
on a.student_id=b.student_id
If you want to confirm login and get data in one query, use a LEFT JOIN, which in the following example will give you a result from the students table, even if there is nothing in the data table for that email address.
$query = "SELECT * FROM `students`
LEFT JOIN `data` ON `students`.`email` = `data`.`email`
WHERE `students`.`password` = '" . $password . "'
AND `students`.`email` = '" . $email. "'";
Note: if there are multiple rows in the data table for the email address, each row will be returned and will contain identical student.password and student.email values.

Categories