Error in Table creation through PDO - php

<?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

Related

mysqli cannot create a table [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 5 years ago.
I have a trouble with my mysql. It connects to database but it doesn't make a table. Here is an example of my code:
$db = new mysqli('localhost', 'user.name', 'user.pass', 'db');
if ($db === FALSE) {
echo "ERRROR";
}
$sql = "CREATE TABLE IF NOT EXISTS db (
ID INT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(20) NULL
)";
$db->query($sql);
if (mysqli_query($db, $sql)) {
echo "TABLE CREATED SUCCESSFULLY";
} else {
echo "TABLE CREATED UNSUCCESSFULLY";
}
I appreciate every answer, thank you for help!
MySQL only allows auto-increment columns if they are defined as a key. Given that the column is labelled ID, which means you probably want it as a primary key, try this:
$sql = "CREATE TABLE IF NOT EXISTS db (
ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
NAME VARCHAR(20) NULL
)";
Because there is error in MySQL query
CREATE TABLE IF NOT EXISTS db (
ID INT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(20) NULL;
Incorrect table definition; there can be only one auto column and it must be defined as a key
fix :
CREATE TABLE IF NOT EXISTS db (
ID INT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(20) NULL,
key idx_ID(ID)
);
PRIMARY KEY is not compulsory, normal key can work too.
Can you please try this.
$db = new mysqli('localhost', 'user.name', 'user.pass', 'db');
if ($db === FALSE) {
echo "ERRROR";
}
$sql = "CREATE TABLE IF NOT EXISTS db (
ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
NAME VARCHAR(20) NULL
)";
$db->query($sql);
if (mysqli_query($db, $sql)) {
echo "TABLE CREATED SUCCESSFULLY";
} else {
echo "TABLE CREATED UNSUCCESSFULLY";
}

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

How to create multiple MySQL tables via PHP using a single query?

I am trying to create a "setup script" for my website. I would like to create the database, adding tables and some content at the same time. So far this is how I did it, but it seems kind off messy using multiple queries:
<?php
$servername = "localhost";
$username = "root";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE MYDB";
if ($conn->query($sql) === TRUE) {
echo "1. Database created successfully <br/>";
$conn->select_db("MYDB");
$sql_members = "CREATE TABLE MEMBERS (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
USERNAME VARCHAR(30) NOT NULL,
EMAIL VARCHAR(40) NOT NULL,
DISCOUNT VARCHAR(5),
PASSW CHAR(128),
ROLE VARCHAR(9)
)";
if ($conn->query($sql_members) === TRUE) {
echo "2. Table MEMBERS created successfully <br/>";
} else {
echo "Error creating table: " . $conn->error;
}
$sql_content = "CREATE TABLE CONTENT (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
TITLE VARCHAR(30) NOT NULL,
TEXT VARCHAR(30) NOT NULL
)";
if ($conn->query($sql_content) === TRUE) {
echo "3. Table CONTENT created successfully <br/>";
} else {
echo "Error creating table: " . $conn->error;
}
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
Is there a better way?
Thanks!
== UPDATE ==
I have tried to export the database and use the resulted .sql file as my setup query, but something is wrong, I get:
Error creating tables: 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 'INSERT INTO CONTACTS (ID, NAME, PHONE,
EMAIL, ADDRESS, CITY, `COUN' at line 12
CREATE TABLE IF NOT EXISTS `CONTACTS` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`NAME` varchar(25) COLLATE utf8_romanian_ci NOT NULL,
`PHONE` varchar(16) COLLATE utf8_romanian_ci NOT NULL,
`EMAIL` varchar(35) COLLATE utf8_romanian_ci NOT NULL,
`ADDRESS` text COLLATE utf8_romanian_ci NOT NULL,
`CITY` varchar(16) COLLATE utf8_romanian_ci NOT NULL,
`COUNTRY` varchar(16) COLLATE utf8_romanian_ci NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_romanian_ci AUTO_INCREMENT=2 ;
INSERT INTO `CONTACTS` (`ID`, `NAME`, `PHONE`, `EMAIL`, `ADDRESS`, `CITY`, `COUNTRY`) VALUES
(1, 'Peter Brown', '0742062307', 'office#shop.com', 'Avenue 13.', 'Santaclaus', 'Austria');
== SOLUTUION ==
I needed "multi_query()" for executing my multiple queries.
You can try this too :p
$errors = [];
$table1 = "CREATE TABLE MEMBERS (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
USERNAME VARCHAR(30) NOT NULL,
EMAIL VARCHAR(40) NOT NULL,
DISCOUNT VARCHAR(5),
PASSW CHAR(128),
ROLE VARCHAR(9)
)";
$table2 = "CREATE TABLE CONTENT (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
TITLE VARCHAR(30) NOT NULL,
TEXT VARCHAR(30) NOT NULL
)";
$tables = [$table1, $table2];
foreach($tables as $k => $sql){
$query = #$conn->query($sql);
if(!$query)
$errors[] = "Table $k : Creation failed ($conn->error)";
else
$errors[] = "Table $k : Creation done";
}
foreach($errors as $msg) {
echo "$msg <br>";
}
You could export the whole database including all tables using the command line or using PhPMyAdmin. Then query the content of the file in php to create the database.
you can create a file and put all your sql queries in it..
CREATE TABLE MEMBERS (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
USERNAME VARCHAR(30) NOT NULL,
EMAIL VARCHAR(40) NOT NULL,
DISCOUNT VARCHAR(5),
PASSW CHAR(128),
ROLE VARCHAR(9)
);
CREATE TABLE CONTENT (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
TITLE VARCHAR(30) NOT NULL,
TEXT VARCHAR(30) NOT NULL
);
then in your php code:
$query = file_get_contents ('queries.sql');
if ($conn->query($query) === TRUE) {
echo "all tables created successfully <br/>";
} else {
echo "Error creating tables: " . $conn->error;
}

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

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.

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