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";
}
Related
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)";
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
I am trying to pick up a few more marks for my coursework and my teacher said that this will help. When creating a variable or table etc, I want to know how I can code it so that if it already exists it doesn't run the code.
$sql2 = "CREATE TABLE referee(refereeID INT (5) NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(20))";
if (mysqli_query($link, $sql)){
echo "Table created successfully";
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
You can try with this query
$sql = "CREATE TABLE IF NOT EXISTS `referee` (
`refereeID` int(11) NOT NULL auto_increment,
`name` varchar(255) NOT NULL default '',
PRIMARY KEY (`refereeID`)
)";
This checks to see if any table like this is in the database.
Hope this helps.
This example sql statement may help you to undersand how to do it
IF NOT EXISTS (SELECT * FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[YourTable]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[YourTable](
....
....
....
)
END
<?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
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.