when I run this php file in my wamp server it connects to database, selects database but not create table .
the output is this:
connected to database succussfully.
connected to database store_db succussfully.
table users was not created.
what is the problem???
php code:
<?php
$sql='CREATE TABLE users
(
PID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PID),
NAME CHAR(20),
PASSWORD CHAR(15),
)';
mysql_connect("localhost","root","") or die('could not connect to database.');
echo 'connected to database succussfully.<br>';
mysql_select_db('store_db') or die('database store_db not found.');
echo 'connected to database store_db succussfully.<br>';
mysql_query($sql) or die('table users was not created');
echo 'table users was created in database store_db succussfully.<br>';
?>
<?php
$sql='CREATE TABLE users
(
PID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PID),
NAME CHAR(20),
PASSWORD CHAR(15),
)';
remove the comma after PASSWORD CHAR(15),
in the event of an error, you can always retrieve errors using mysql_error().
however. you should not be using the old mysql functions. much better and more secure options exist in the PDO and MySQLi extensions.
Your $sql:
$sql='CREATE TABLE users
(
PID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PID),
NAME CHAR(20),
PASSWORD CHAR(15),
)';
should be:
$sql='CREATE TABLE users
(
PID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PID),
NAME CHAR(20),
PASSWORD CHAR(15)
)';
You should remove comma right after PASSWORD CHAR(15)
To get the proper error message always use below code so that you can figure out exact error in future.
mysql_query($sql) or die(mysql_error());
Make sure the MySQL user you are attempting to create the table with has permissions to do so. (e.g. the user has been granted the 'CREATE' privileges for that database.)
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)";
Every time I run my code or add new date to database my values get added again to tables. I don't know if it is an issue with how I create table or add values.
my code:
$uzk_len="create table if not exists buyers
(
id int(4) primary key auto_increment,
code varchar(4),
name varchar(30),
adress varchar(30)
)";
$uzk_lenv=mysql_query($uzk_len) or die ("table not created");
$uzk_duom="insert into buyers
(code,name,adress)
values
('1001','Maxima','Tilzes 25'),
('1002','IKI','Tilzes 111'),
('1003','Rimi','Saules 58'),
('1004','Norfa','Pramones 195')";
$uzk_duomv=mysql_query($uzk_duom) or die ("Failed to insert");
Drop the table before creating new.
DROP TABLE IF EXISTS buyers;
I use the following gist to make an OOP attempt to create a database connection:
https://gist.github.com/jonashansen229/4534794
It seems to work so far.
But the creation of the database table passed_exams fails.
Edit:
After recent comments and suggestions i updated my code:
require_once 'Database.php'; // the gist 4534794
class DatabaseSchema {
public function createStudents() {
$db = Database::getInstance();
$mysqli = $db->getConnection();
$create_students = 'CREATE TABLE IF NOT EXISTS students (
id INT(6) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(40) NOT NULL,
lastname VARCHAR(40) NOT NULL,
university VARCHAR(50)
)';
$result = $mysqli->query($create_students);
}
public function createPassedExams() {
$db = Database::getInstance();
$mysqli = $db->getConnection();
$create_passed_exams = 'CREATE TABLE IF NOT EXISTS passed_exams (
id INT(6) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(40) NOT NULL,
student_id INT(6),
FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE
)';
$result = $mysqli->query($create_passed_exams);
}
}
$db_student = new DatabaseSchema();
$db_student->createStudents();
$db_student->createPassedExams();
When i look in the mysql console, only table students is created.
Why is table passed_exams missing?
You create the string to check $query_students = 'SELECT ID FROM STUDENTS';
but you never actually run this. Then u check the string if it is Empty, it will never be empty in your code.
What you should do is use the CREATE ... IF NOT EXISTS syntax of mysql, and not what you do here.
First example show the syntax https://dev.mysql.com/doc/refman/5.5/en/create-table.html
The id column on your students table is INT(6) UNSIGNED but the student_id column on the passed_exams table is a signed INT(6). Therefore the FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE clause will fail with "Error Code: 1215. Cannot add foreign key constraint".
I advise you to implement some error handling so that you would see this error message rather than blindly continue executing code.
Probably a simple overlook, but I cannot seem to create a table with my PHP script. My first question is that I want to add a table to an existing DB. How do I tell the server which DB to create the table in? The code to create a table is pretty simple, but here it is ..
CREATE TABLE Countr(ID INT IDENTITY(1,1) PRIMARY KEY,Page VARCHAR(50),
Month INT, Always INT);
Any assistance would be appreciated.
In your PHP server you should be connecting to your database. Your code might be like this:
mysqli_connect("sqlserver.mysite.com", "username", "password") or die("SQL Error: Cant connect to database.");
Then you should do:
mysqli_select_db("database_name") or die("SQL Error: Cant select database");
to select the database before performing any other sql statements. Such as creating tables.
http://dev.mysql.com/doc/refman/5.0/en/use.html
USE my_db1;
CREATE TABLE ...
USE my_db2;
CREATE TABLE ...
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db('database_name', $link);
CREATE TABLE Countr(ID INT IDENTITY(1,1) PRIMARY KEY,Page VARCHAR(50), Month INT, Always INT);
Try this code to create table in any database.
CREATE TABLE db_name.Countr(ID INT IDENTITY(1,1) PRIMARY KEY,Page VARCHAR(50), Month INT, Always INT);
Note: Current database user has create table privileges in the other database.
$sql = "CREATE TABLE wp_shifts (
user_id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
transact_id int(64),
hours decimal(10,2),
date varchar(64),
time1 varchar(64),
PRIMARY KEY (user_id)
)";
$results = $wpdb->query($sql);
Create a Table
The CREATE TABLE statement is used to create a table in MySQL.
We must add the CREATE TABLE statement to the mysqli_query() function to execute the command.
The following example creates a table named "Persons", with three columns: "FirstName", "LastName" and "Age":
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Create table
$sql="CREATE TABLE Persons(FirstName CHAR(30),LastName CHAR(30),Age INT)";
// Execute query
if (mysqli_query($con,$sql))
{
echo "Table persons created successfully";
}
else
{
echo "Error creating table: " . mysqli_error($con);
}
?>
I'm trying to create a table whose name is the value of what is stored inside the variable $name. I have tried numerous different methods but none seem to work for me. Here is the code I am using currently:
mysql_connect("localhost", "peltdyou_admin", "123456") or die(mysql_error());
mysql_select_db("peltdyou_orders") or die(mysql_error());
mysql_query("CREATE TABLE '" .$_POST['name']. "' ( name VARCHAR(30), age INT, car VARCHAR(30))");
I know it is something to do with '" .$_POST['name']. "' but I can't work out what.
I have tried '$name' in its place which gets it's value from further up in the code.
Any help would be great!
Use backticks around table name, not quotes. And escape the input! Also, while this works on localhost, make sure that the user running on your production server has the privilege to CREATE tables (usually it's not, AFAIK, on shared hostings of course).
A word of warning: are you really sure you want to create a table on a user input?? how many tables are you going to create in this way? Can't you just redesign the whole thing so that you insert values instead?
$name = mysql_real_escape_string($_POST['name']);
mysql_query("CREATE TABLE `".$name."` ( name VARCHAR(30), age INT, car VARCHAR(30))");
Put it in another variable and it will work, there's a conflict with the "'" character in the POST variable and in the mysql_query.
<?php
mysql_connect("localhost", "peltdyou_admin", "123456") or die(mysql_error());
mysql_select_db("peltdyou_orders") or die(mysql_error());
$name = mysql_real_escape_string($_POST['name']);
mysql_query("CREATE TABLE '$name' ( name VARCHAR(30), age INT, car VARCHAR(30))");
?>
I posted this code to help you in your code but you should not use the mysql_* functions you should use the mysqli_* functions.
You can read more about them here:
http://php.net/manual/en/book.mysqli.php
You should really be using PDO or MySQLi instead of mysql_* functions. mysql_* functions are in the process of being deprecated and they are full of security holes.
With that said you don't need to quote your table name and instead should use nothing or backticks.
Using the newest Mysqli connector, you can do something like this:
1. Create a variable from the user's input like so $variable=$_POST['name']
2. Use the variable in your query as shown in the complete code below here
$variable=$_POST['name'];
mysqli_connect("localhost", "peltdyou_admin", "123456") or die(mysql_error());
mysqli_select_db("peltdyou_orders") or die(mysqli_connect_error());
mysqli_query("CREATE TABLE $variable ( name VARCHAR(30), age INT, car VARCHAR(30))");
$query = "CREATE TABLE $name" . '(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
age INT,
name varchar(30),
car VARCHAR(30)
)';
CREATE TABLE IF NOT EXISTS `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL,
`description` text NOT NULL,
`price` double NOT NULL,
`created` datetime NOT NULL,
`modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;