error when creating table - php

In my php program i want to check if table is exist or not. if table not exist want to create a table...
the code i've been tried
<?php
if( isset($_POST['uniqueno']))
{
$uniqueno=$_POST['uniqueno'];
$user=$_SESSION['userid'];
$date=date('Y-m-d H:i:s');
if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$user."'"))==1)
{ echo "table exists"; }
else
{
$create=mysql_query("create table '$user'( uniqueno varchar(10) NOT NULL,
elementno varchar(30),
name varchar(50),
process varchar(30),
date datetime(30),
PRIMARY KEY (uniqueno)
)");
if(!$create)
{
echo mysql_error();
}
}
}
?>
When i try this code displays following error:
"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 ''sai'( uniqueno varchar(10) NOT NULL, elementno varchar(30), ' at line 1 ".
thank you..

Take out single quote for table name and the query should be something as
"create table $user( uniqueno varchar(10) NOT NULL,
elementno varchar(30),
name varchar(50),
process varchar(30),
date datetime,
PRIMARY KEY (uniqueno)
)"

It should be
$create=mysql_query("create table $user ( uniqueno varchar(10) NOT NULL,
elementno varchar(30),
name varchar(50),
process varchar(30),
date datetime,
PRIMARY KEY (uniqueno)
)");
The single quote around $user is not needed.
The field length is not needed for datetime field.

Try this
$create=mysql_query("create table $user ( uniqueno varchar(10) NOT NULL,
elementno varchar(30),
name varchar(50),
process varchar(30),
date datetime(30),
PRIMARY KEY (uniqueno)
)");

<?php
session_start();
//your db connection code here
if( isset($_POST['uniqueno']))
{
$uniqueno=$_POST['uniqueno'];
$userid=$_POST['userid'];
$user=$_SESSION[$userid];
$date=date('Y-m-d H:i:s');
if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$user."'"))==1)
{ echo "table exists"; }
else
{
$create=mysql_query("create table ".$user."(`uniqueno` varchar(10) NOT NULL,`elementno` varchar(30),`name` varchar(50),`process` varchar(30),`date` datetime, PRIMARY KEY(`uniqueno`))");
if(!$create)
{
echo mysql_error();
}
}
}
?>

Related

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;
}

mysqli strange errors 1064, when there is no syntax errors

can anyone please assist me, that whats wrong i m doing. There is no syntax error in the php code, but output is- connection successful
Table customers NOT created. Error: 1064
Table stats NOT created. Error : 1005. I am using XAMPP, with PHP 7
<?php
$conn = mysqli_connect("localhost","root","","test");
if(mysqli_connect_errno()){
echo "Connect failed%\n".mysqli_connect_errno();
exit();
}
else {
echo "connection successful";
}
$sql1 = "CREATE TABLE CUSTOMERS (
P_Id int(10) NOT NULL AUTO_INCREMENT,
Firstname(100) varchar NOT NULL,
Lastname(100) varchar NOT NULL,
Address varchar(500) NOT NULL,
City varchar(100) NOT NULL,
PRIMARY KEY(P_Id)
)";
if(mysqli_query($conn,$sql1)==1){
echo "Table customers created successfully";
}
else
{
echo "<br/>"."Table customers NOT created. Error: ".mysqli_errno($conn);
}
$sql2 = 'CREATE TABLE STATS (
O_Id int(10) NOT NULL AUTO_INCREMENT,
Offers varchar(1000) NOT NULL,
Resorts varchar(1000) NOT NULL,
ArrivalDate date NOT NULL,
P_Id int(10) NOT NULL,
PRIMARY KEY(O_Id),
FOREIGN KEY(P_Id) REFERENCES CUSTOMERS(P_Id)
)';
if(mysqli_query($conn,$sql2)==1){
echo "Table stats created successfully";
}
else
{
echo "<br/>"."Table stats NOT created. Error : ".mysqli_errno($conn);
}
?>
You need to specify the character limit for VARCHAR after the VARCHARkeyword. So, for example, in the query for table CUSTOMERS, the Firstname clause will look like:
Firstname VARCHAR(100) NOT NULL
The error is how you declare your varchar.
Firstname(100) varchar NOT NULL,
Must be :
Firstname varchar(100) NOT NULL,
So change firstname and lastname syntax and all will work right.
Hope this help.
I think your problem is column declarations:
You should use: <name> <type>(length) NOT NULL

Table in php is not being created when ran through the query

I did this earlier and it worked just fine and I even brought in another table and it was created just fine. I am stuck.
Here is the table that is not working.
<?php
include_once('dbconx.php');
$tbl_pages = "CREATE TABLE IF NOT EXISTS pages (
id INT(11) NOT NULL AUTO_INCREMENT,
label VARCHAR(20) NOT NULL,
title VARCHAR(50) NOT NULL,
body TEXT NOT NULL,
slug VARCHAR(50) NOT NULL,
create TIMESTAMP NOT NULL,
updated TIMESTAMP NULL,
PRIMARY KEY(id),
)";
$query = mysqli_query($dbcon, $tbl_pages);
if ($query === TRUE) {
echo "<h3>Pages table created OK :) </h3>";
} else {
echo "<h3>Pages table NOT created :( </h3>";
}
?>
One of your field names is a MySQL reserved words create. Try changing the field name to something like created. See MySQL Keywords and Reserved Words
You also have an extra comma after the primary key definition.
Try this query:
$tbl_pages = "CREATE TABLE IF NOT EXISTS pages (
id INT(11) NOT NULL AUTO_INCREMENT,
label VARCHAR(20) NOT NULL,
title VARCHAR(50) NOT NULL,
body TEXT NOT NULL,
slug VARCHAR(50) NOT NULL,
created TIMESTAMP NOT NULL,
updated TIMESTAMP NULL,
PRIMARY KEY(id)
)";
You can also echo mysqli_error if it fails so you can see details of the error.

Not able to run create sql command with mysqli_query php

I have below code I am trying to run..Connection is successfully created but still mysqli_query does not create a table.What I am missing...
here is the script I am executing...
error_reporting(E_ALL);
ini_set('display_errors', '1');
$con=mysqli_connect("localhost","xxxxxx","xxxxx","xxx");
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
exit();
} else {
echo "Successful database connection";
}
$tbl_users = "CREATE TABLE IF NOT EXISTS users (
id INT(11) NOT NULL AUTO_INCREMENT,
firstname VARCHAR(255) NOT NULL,
lastname VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
gender ENUM('m','f') NULL,
state VARCHAR(255) NULL,
country VARCHAR(255) NULL,
userlevel ENUM('admin','user') NOT NULL DEFAULT 'user',
ip VARCHAR(255) NOT NULL,
signup DATETIME NOT NULL,
lastlogin DATETIME NOT NULL,
activated ENUM('0','1') NOT NULL DEFAULT '0',
PRIMARY KEY (email)
)";
$query = mysqli_query($con, $tbl_users);
if ($query === TRUE) {
echo "<h3>user table created OK :) </h3>";
} else {
echo "<h3>user table NOT created :( </h3>";
}
You need to change your Primary key to the auto_increment column, remove it from email, you can set this (email) to unique if it should be
CREATE TABLE IF NOT EXISTS users (
id INT(11) NOT NULL // >>> PRIMARY KEY //<<< AUTO_INCREMENT,
firstname VARCHAR(255) NOT NULL,
[Err] 1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key
PRIMARY KEY (email) is the issue. Make id your primary key.

Database trouble and php trouble

I am having trouble with my create a table .php script, It creates all tables in the database except one which is 'useroptions'. I am new to php but still understand it to an extent, feedback and help would be greatly appreciated.
<?php
include_once("php_includes/db_connect.php");
$tbl_users = "CREATE TABLE IF NOT EXISTS users (
id INT(11) NOT NULL AUTO_INCREMENT,
firstname VARCHAR(100) NOT NULL,
lastname VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
gender ENUM('m','f') NOT NULL,
avatar VARCHAR(255) NULL,
ip VARCHAR(255) NOT NULL,
signup DATETIME NOT NULL,
lastlogin DATETIME NOT NULL,
notescheck DATETIME NOT NULL,
activated ENUM('0','1') NOT NULL DEFAULT '0',
PRIMARY KEY (id),
UNIQUE KEY email (email)
)";
$query = mysqli_query($db_connect, $tbl_users);
if ($query === TRUE) {
echo "<h3>user table created OK :) </h3>";
} else {
echo "<h3>user table NOT created :( </h3>";
}
////////////////////////////////////
$tbl_useroptions = "CREATE TABLE IF NOT EXISTS useroptions (
id INT(11) NOT NULL,
question VARCHAR(255) NULL,
answer VARCHAR(255) NULL,
PRIMARY KEY (id),
UNIQUE KEY email (email)
)";
$query = mysqli_query($db_connect, $tbl_useroptions);
if ($query === TRUE) {
echo "<h3>useroptions table created OK :) </h3>";
} else {
echo "<h3>useroptions table NOT created :( </h3>";
}
////////////////////////////////////
$tbl_friends = "CREATE TABLE IF NOT EXISTS friends (
id INT(11) NOT NULL AUTO_INCREMENT,
user1 VARCHAR(100) NOT NULL,
user2 VARCHAR(100) NOT NULL,
datemade DATETIME NOT NULL,
accepted ENUM('0','1') NOT NULL DEFAULT '0',
PRIMARY KEY (id)
)";
$query = mysqli_query($db_connect, $tbl_friends);
if ($query === TRUE) {
echo "<h3>friends table created OK :) </h3>";
} else {
echo "<h3>friends table NOT created :( </h3>";
}
////////////////////////////////////
$tbl_blockedusers = "CREATE TABLE IF NOT EXISTS blockedusers (
id INT(11) NOT NULL AUTO_INCREMENT,
blocker VARCHAR(100) NOT NULL,
blockee VARCHAR(100) NOT NULL,
blockdate DATETIME NOT NULL,
PRIMARY KEY (id)
)";
$query = mysqli_query($db_connect, $tbl_blockedusers);
if ($query === TRUE) {
echo "<h3>blockedusers table created OK :) </h3>";
} else {
echo "<h3>blockedusers table NOT created :( </h3>";
}
////////////////////////////////////
$tbl_status = "CREATE TABLE IF NOT EXISTS status (
id INT(11) NOT NULL AUTO_INCREMENT,
osid INT(11) NOT NULL,
account_name VARCHAR(100) NOT NULL,
author VARCHAR(100) NOT NULL,
data TEXT NOT NULL,
postdate DATETIME NOT NULL,
PRIMARY KEY (id)
)";
$query = mysqli_query($db_connect, $tbl_status);
if ($query === TRUE) {
echo "<h3>status table created OK :) </h3>";
} else {
echo "<h3>status table NOT created :( </h3>";
}
////////////////////////////////////
$tbl_photos = "CREATE TABLE IF NOT EXISTS photos (
id INT(11) NOT NULL AUTO_INCREMENT,
user VARCHAR(100) NOT NULL,
gallery VARCHAR(16) NOT NULL,
filename VARCHAR(255) NOT NULL,
description VARCHAR(255) NULL,
uploaddate DATETIME NOT NULL,
PRIMARY KEY (id)
)";
$query = mysqli_query($db_connect, $tbl_photos);
if ($query === TRUE) {
echo "<h3>photos table created OK :) </h3>";
} else {
echo "<h3>photos table NOT created :( </h3>";
}
////////////////////////////////////
$tbl_notifications = "CREATE TABLE IF NOT EXISTS notifications (
id INT(11) NOT NULL AUTO_INCREMENT,
firstname VARCHAR(100) NOT NULL,
initiator VARCHAR(100) NOT NULL,
app VARCHAR(255) NOT NULL,
note VARCHAR(255) NOT NULL,
did_read ENUM('0','1') NOT NULL DEFAULT '0',
date_time DATETIME NOT NULL,
PRIMARY KEY (id)
)";
$query = mysqli_query($db_connect, $tbl_notifications);
if ($query === TRUE) {
echo "<h3>notifications table created OK :) </h3>";
} else {
echo "<h3>notifications table NOT created :( </h3>";
}
?>
Also I'm getting this error when I click on database ?
Error
SQL query:
SELECT tracking_active
FROM `phpmyadmin`.`pma_tracking`
WHERE db_name = 'circle'
AND table_name = 'blockedusers'
ORDER BY version DESC
MySQL said:
1146 - Table 'phpmyadmin.pma_tracking' doesn't exist
Your useroptions create table statement has an invalid unique key ref: UNIQUE KEY email (email). There is no column email on useroptions. Remove it and it will likely run clean.
As for the query issue, not really sure what you're trying to do.

Categories