syntax: create table 'variable' [duplicate] - php

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 5 years ago.
there are a lot of ways to work with variable in this area, but this place of the variable seems to work with the syntax I wrote beneath. Except, it doesn't.
$name = (string)$_GET['name'];
mysqli_select_db($con,"dbtest");
// sql to create table
$sql = "CREATE TABLE '".$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
)";

Try this:
(get rid of quotes and double quotes around your variable -> name)
$sql = "CREATE TABLE $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
)";

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

get the foreign key [duplicate]

This question already has answers here:
MYSQL - Impossible to create an external key
(1 answer)
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Reference - What does this error mean in PHP?
(38 answers)
Closed 3 years ago.
I am a self taught programmer in college and I am super confused since few days. I am working on the backend of a job listing website. The user will be able to post a job and I have three tables: jobs, keywords and requirements. The job_id is the primary key of jobs and also a foreign key in the keywords table. Right now, I am only able to insert data in the jobs table and I am not able to key anything from the keywords table. Each job_id can have multiple keyword.
SQL - jobs table
CREATE TABLE `jobs` (
`title` text NOT NULL,
`type` text NOT NULL,
`location` text NOT NULL,
`salary` int(11) NOT NULL,
`description` text NOT NULL,
`date` date NOT NULL,
`job_id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`job_id`)
) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=latin1;
SQL - keywords table
CREATE TABLE `keywords` (
`keyword_id` int(11) NOT NULL AUTO_INCREMENT,
`keyword` text NOT NULL,
`job_id` int(11) NOT NULL,
PRIMARY KEY (`keyword_id`),
KEY `job_id` (`job_id`),
CONSTRAINT `keywords_ibfk_1` FOREIGN KEY (`job_id`) REFERENCES `jobs` (`job_id`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=latin1;
PHP (I know the code is not secured yet but I just want to understand first)
<?php
require("../config/db.php");
require("add-jobs.php");
$link = mysqli_connect("localhost","root","","benoit");
$title = $_POST["position"];
$type = $_POST["job-type"];
$location = $_POST["location"];
$salary = $_POST["salary"];
$description = $_POST["description"];
$date = $publisheddate;
$keywords = $_POST["keywords"];
mysqli_query($link,"INSERT INTO jobs (`title`, `type`, `location`, `salary`, `description`, `date`)
VALUES ('$title', '$type', '$location', '$salary', '$description', CURDATE())")
or die(mysqli_error($link));
foreach ($keywords as $keyword){
mysqli_query($link, "INSERT INTO keywords (`keyword`) VALUES ('$keyword')");
}
?>
Get insert id with $mysqli->insert_id and use it:
mysqli_query($link, ".....");
$insert_id = mysqli_insert_id($link);
foreach ($keywords as $keyword){
mysqli_query($link, "INSERT INTO keywords (`job_id`, `keyword`) VALUES ($insert_id, '$keyword')");
}

why table is not creating in phpmyadmin [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 6 years ago.
I have written these codes (if table doesn't exist) condition. The Database is fine however my table is not creating and there was not error. Can anyone help me?!
$connect=mysqli_connect($host,$username,$password)or die("cannot connect");
$create=mysqli_query($connect,"CREATE DATABASE IF NOT EXISTS projectdb") or die (mysql_error());
mysqli_select_db($connect,"projectdb");
$info="CREATE TABLE IF NOT EXISTS info (
id int NOT NULL auto_increment,
contactEmail text NOT NULL,
firstName varchar(50) NOT NULL,
lastName varchar(50) NOT NULL,
phone varchar(50) NOT NULL,
phone text NOT NULL,
dob date NOT NULL,
address varchar(50) NOT NULL,
country varchar(70) NOT NULL,
PRIMARY KEY(id),
UNIQUE KEY ( id )
)";
mysqli_query($connect,$info);
your phone column is duplicate. so use any one
phone varchar(50) NOT NULL,
phone text NOT NULL,
Please use bellow :
phone varchar(50) NOT NULL,
or
phone text NOT NULL,

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

Categories