Can't create table (errno: 150) on FOREIGN KEY - php

I saw a lot of same question but I couldn't solve my case.
If I run this code:
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/config.php');
$servername = HOST;
$username = USERNAME;
$password = PASSWORD;
$dbname = DB;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "CREATE TABLE IF NOT EXISTS Articls (
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(254) COLLATE utf8_persian_ci NOT NULL
) DEFAULT COLLATE utf8_persian_ci";
if ($conn->query($sql) === TRUE) {
echo "Table Articls created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
/////////////////////////////////////////////////////////////////////////
$sql = "CREATE TABLE IF NOT EXISTS Tags (
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
id_articls INT(10) UNSIGNED NOT NULL,
name VARCHAR(256) COLLATE utf8_persian_ci NOT NULL,
FOREIGN KEY(Tags.id_articls) REFERENCES Articls(Articls.id)
) DEFAULT COLLATE utf8_persian_ci";
if ($conn->query($sql) === TRUE) {
echo "Table Tags created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
I get this error: ( If I remove FOREIGN KEY it works)
Table Articls created successfully Error creating table: Can't create
table 'admin_wepar.Tags' (errno: 150)
Edit
If a change into Articls.id and Tags.id_articls I got this error:
Table Articls created successfullyError creating table: You have an
error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near 'FOREIGN KEY
(Tags.id_articls) REFERENCES Articls(Articls.id) ) DEFAULT COLLA' at
line 5

You need to declare both Articls.id and Tags.id_articls signed or unsigned

Tags.id_articls is a signed integer while Articl.id is an unsigned integer. MySQL requires referencing field to be exactly the same type. Make Tags.id_articls unsigned to have it work.
Additionally, the table names in the column lists are not allowed in MySQL. It is always clear which table is meant: first the referencing table and then the referenced table. So change
FOREIGN KEY(Tags.id_articls) REFERENCES Articls(Articls.id)
into
FOREIGN KEY(id_articls) REFERENCES Articls(id)
and it will work.

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

Cannot create table with PHP

I want to create a table with variables passed into my php file. However, the SQL does not work when I pass in '12345' and works when I pass in 'a12345' instead.
This is my error that is given.
Error creating the table
query was
CREATE TABLE 123456 ( humidity VARCHAR(50) NOT NULL, temperature VARCHAR(50)
NOT NULL, gasquality VARCHAR(50) NOT NULL, timestamp DATETIME NOT NULL
DEFAULT CURRENT_TIMESTAMP)
mysqlerror:You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near
'123456 ( humidity VARCHAR(50) NOT NULL, temperature VARCHAR(50) NOT NULL,
gasq' at line 1
Creating database failed!
and my function that creates the table
function CreateTableNode(&$formvars)
{
$serialno = $formvars['serialno'];
$qry = "CREATE TABLE ".$serialno." (".
" humidity VARCHAR(50) NOT NULL, ".
" temperature VARCHAR(50) NOT NULL, ".
" gasquality VARCHAR(50) NOT NULL, ".
" timestamp DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)";
if(!mysqli_query($this->connection,$qry))
{
$this->HandleDBError("Error creating the table \nquery was\n $qry");
return false;
}
return true;
}
I want to be able to create tables with numeric names like '12345' or '154124' for other purposes. Thanks alot!
My suggestion:
Provide a prefix to the table you created.
Moreover, I couldn't
see the primary key in your table. However, it is not necessary to
have it but if your table design doesn't have a primary key, you need
to rethink your design. It plays a vital role to join tables.
Your code can be rewritten as:
function CreateTableNode (&$formvars) {
$host = 'localhost';
$database = 'test';
$dbuser = 'root';
$dbpass = '';
try {
$pdo = new PDO('mysql:host=localhost; dbname=test', $dbuser, $dbpass);
} catch (PDOException $e) {
print "ERROR! : " . $e->getMessage() . "<br/>";
die();
}
$serialno = $formvars['serialno'];
$qry = "CREATE TABLE ".$serialno." ("."
`id` INT NOT NULL AUTO_INCREMENT ,
`humidity` VARCHAR(50) NOT NULL ,
`temperature` VARCHAR(50) NOT NULL ,
`gasquality` VARCHAR(50) NOT NULL ,
`timestamp` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ,
PRIMARY KEY (`id`)
)";
$stmt = $pdo->prepare($qry);
$stmt->execute();
$pdo = null;
return true;
}
You just need to wrap some elements in the query with quotes as the duplicated thread mentioned by underscore_d says:
$qry = "CREATE TABLE '$serialno' (
'humidity' VARCHAR(50) NOT NULL,
'temperature' VARCHAR(50) NOT NULL,
'gasquality' VARCHAR(50) NOT NULL,
'timestamp' DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)";
This will fix your syntax errror in the query.
Marking to close the question as duplicated
The name of the entity was expected. (near "123456" at position 13)
Try adding a prefix to the table name as such
"t_12345"
CREATE TABLE t_12345
MySql does not allow numeric values as table name.
MySQL doesn't allow the creation of tables with names made solely of digits unless the name is quotes. See here
Identifiers may begin with a digit but unless quoted may not consist solely of digits.
Try quoting the name with backticks (`) or prefix the table name.
The error says "Creating database failed!".
So I assume you haven't selected the database in the connection query. You should do that or select it with "use mydatabase;" first. Of course, you may need to create the database first.
With PDO it would look like:
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
Please see dbname=myDB which preselects the right db for you.
Reference: https://www.w3schools.com/php/php_mysql_connect.asp
Using mysql functions, you can use:
mysql_select_db($dbname)
Reference: http://php.net/manual/en/function.mysql-select-db.php

Error performing sql query in PHP

I am trying to learn using mysql in php. I started off trying to create a table in mysql, and using the mysqli extension.
My code:
<?php
$truemsg = "Table created successfully";
$falsemsg = "Error creating table: ";
$servername = "localhost";
$username = "myuser";
$password = "mypass";
$db = "mytable";
// Create database
$sql = "USE ".$db.";".
'CREATE TABLE IF NOT EXISTS Authentication (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
userid VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL,
role VARCHAR(20) NOT NULL,
email VARCHAR(50)
);';
print "Sql command is ".$sql;
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
print "<p></p>";
if ($conn->query($sql) === TRUE) {
echo $truemsg;
} else {
echo $falsemsg . $conn->error;
}
$conn->close();
?>
The error is:
Sql command is USE mytable;CREATE TABLE IF NOT EXISTS Authentication ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, userid VARCHAR(30) NOT NULL, password VARCHAR(30) NOT NULL, role VARCHAR(20) NOT NULL, email VARCHAR(50) );
Error creating table: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CREATE TABLE IF NOT EXISTS Authentication ( id INT(6) UNSIGNED AUTO_INCREMENT PR' at line 1
I tried pasting the same command on the mysql command line, and it works fine. What's the problem using this in php?
You are supposed to run queries one by one
$sql = "query one";
$conn->query($sql);
$sql = 'query two';
$conn->query($sql);
instead of coupling them all in one statement.
DO NOT use mysqi_multi_query() either, this asynchronous function is not intended for the everyday use.
Also, in this particular case USE query is superfluous. Database should go into constructor:
$conn = new mysqli($servername, $username, $password, $db);
^^^ here
Also, tell mysqli to throw errors by itself, automatically, instead of checking result of every database command manually:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
This way you will get neat and clean code:
<?php
$servername = "localhost";
$username = "myuser";
$password = "mypass";
$db = "mytable";
// Create data table
$sql = 'CREATE TABLE IF NOT EXISTS Authentication (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
userid VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL,
role VARCHAR(20) NOT NULL,
email VARCHAR(50)
)';
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $db);
// Run a query
$conn->query($sql);
echo "Table created successfully";
This code will either report that table has been created successfully, or emit an error, with a detailed explanation on what went wrong.
This seems to be like a mysql multiple query problem
$conn->select_db($db);
you can use this function before the query to use the database and remove the use database statement from your query string , then you query string becomes
$sql = 'CREATE TABLE IF NOT EXISTS Authentication (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
userid VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL,
role VARCHAR(20) NOT NULL,
email VARCHAR(50)
)';
that may work for you ..

Error in Table creation through PDO

<?php
require_once 'dbconfig.php';
try{
$dsn = "mysql:host=$host;dbname=$dbname"; // $dbname is empdb as in dbconfig.php
$dbh = new PDO($dsn, $username, $password);
$sql_create_dept_tbl = <<<EOSQL
CREATE TABLE departments(
department_no int(11) NOT NULL AUTO_INCREMENT,
name varchar(255) DEFAULT NULL,
PRIMARY KEY (department_no)
) ENGINE=InnoDB
EOSQL;
$sql_create_emp_tbl = <<<EOSQL
CREATE TABLE employees (
employee_no int(11) NOT NULL AUTO_INCREMENT,
first_name varchar(40) NOT NULL,
last_name varchar(40) NOT NULL,
department_no int(11) DEFAULT NULL,
PRIMARY KEY (employee_no),
KEY emp_dept (department_no),
CONSTRAINT emp_dept FOREIGN KEY (department_no)
REFERENCES departments (department_no)
) ENGINE=InnoDB
EOSQL;
$msg = '';
$r = $dbh->exec($sql_create_dept_tbl);
if($r !== false){
$r = $dbh->exec($sql_create_emp_tbl);
if($r !== false){
$msg = "Tables are created successfully!<br/>";
}else{
$msg = "Error creating the employees table.<br/>";
}
}else{
$msg = "Error creating the departments table.<br/>";
}
// display the message
if($msg != '')
echo $msg;
}catch (PDOException $e){
echo $e->getMessage();
}
I have gone through all the initialization still all I get is
"Error creating the departments table."
But I see a "departments" table already created in the database (empdb).
Why am I getting an error message when the table is already created?? . I am using WAMP server and phpMyadmin to access the database.
Any help regarding this will be of utmost value to me.
Add CREATE TABLE [IF NOT EXISTS] to your table definitions:
CREATE TABLE IF NOT EXISTS departments(
department_no int(11) NOT NULL AUTO_INCREMENT,
name varchar(255) DEFAULT NULL,
PRIMARY KEY (department_no)
) ENGINE=InnoDB
and:
CREATE TABLE IF NOT EXISTS employees
...
You are getting error because your table is already created and can`t be created again, so:
$r = $dbh->exec($sql_create_dept_tbl) // result is false
so below chunk of code getting printed
}else{
$msg = "Error creating the departments table.<br/>";
}
you can check if table already exists and run creation or skip it:
$result = $pdo->query("SELECT 1 FROM $table_name LIMIT 1");
if($result){
//// skip table creation
} else {
//// run table creation script
$r = false;
}
You cannot create a table with same name more than once . It's always a good practice to check whether the table already exist or not . Use this it will help you ,
CREATE TABLE [IF NOT EXISTS] table name

message: successfully created tables but only the first one appears in database

I am trying to populate a database with tables (am new to this) The message I get back upon execution of .php is:
Table "users" successfully created
Table "tempRes" successfully created
Table "empRec" successfully created
However the second and third tables are not appearing in the database in phpMyAdmin. SHOW TABLES & SHOW TABLE STATUS only shows "user" table.
Does anyone know why this is happening? How can I rectify?
Here is my code:
<?php
// connect to the MySQL server
$conn = new mysqli('localhost', 'fiona', 'xxx', 'Org_db');
// check connection
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
// Performs the $sql query on the server to create the table users
$sql = "CREATE TABLE IF NOT EXISTS `users` (
`id` INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(25) NOT NULL,
`pass` VARCHAR(18) NOT NULL,
`email` VARCHAR(45),
`reg_date` TIMESTAMP
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8";
// performs query to check table successfully created or get error message
if ($conn->query($sql) === TRUE) {
echo '<br/>Table "users" successfully created<br/>';
}
else {
echo 'Error: '. $conn->error;
}
// Performs the $sql query on the server to create the table temporary reservations
"CREATE TABLE IF NOT EXISTS `tempRes` (
`tr_id` INT NOT NULL AUTO_INCREMENT,
`aaid` INT NOT NULL,
`cid` INT NOT NULL,
`date_res` DATE NOT NULL,
`rem` VARCHAR(5) NOT NULL,
primary key ( `tr_id` )) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8";
if ($conn->query($sql) === TRUE) {
echo 'Table "tempRes" successfully created<br/>';
}
else {
echo 'Error: '. $conn->error;
}
// Performs the $sql query on the server to create the table employee records
"CREATE TABLE IF NOT EXISTS `empRec` (
`eid` INT NOT NULL auto_increment,
`empPos` VARCHAR( 20 ) NOT NULL,
`tfn` INT NOT NULL,
`emp_DOB` DATE NOT NULL,
`eStart` DATE NOT NULL,
`super_co` VARCHAR( 30 ),
`s_mem_no` INT NOT NULL,
`icin` INT NOT NULL,
`epn` INT NOT NULL,
primary key ( emp_id )) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8";
if ($conn->query($sql) === TRUE) {
echo 'Table "empRec" successfully created<br/>';
}
else {
echo 'Error: '. $conn->error;
}
?>
Your not storing the second and third create statements in $sql variable. That's why isn't it?
Add $sql = infront of those two statements as well

Categories