Creating a table - php

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

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

How to insert values into table once

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;

Run multiple CREATE TABLe queries with MySQL and PHP

I need to create a large number of tables at once and add data to the first one using PHP and MySQL. My code looks like this:
$sql = "CREATE TABLE table1 (
code VARCHAR(5) PRIMARY KEY,
name VARCHAR(50) NOT NULL
);";
//adding businesses to table
$sql .= "INSERT INTO table1 (code, name)
VALUES ('CODE', 'name');";
//^this basic idea is run a few more times
$sql .= "CREATE TABLE table2 (
code VARCHAR(5) PRIMARY KEY,
name VARCHAR(50) NOT NULL
);";
//^same basic thing run a bunch more times w/ variations to columns
if ($conn->multi_query($sql) === TRUE) {
echo "<p>Tables created.</p>
Continue";
} else {
echo "<p>Error creating tables: " . $conn->error . "</p>";
}
This only creates the first table and adds the data to it, it won't create any other tables and I get no error messages (the success message is shown). I've been googling a solution for an hour and I can't come up with anything. I'm thinking I need a way to hold off creating the next table until the previous one has been created?
I'm very new to MySQL so newbie-friendly would be very much appreciated:)
Try using backticks in your SQL statements, such as:
$sql .= "CREATE TABLE `table2` (
`code` VARCHAR(5) PRIMARY KEY,
`name` VARCHAR(50) NOT NULL
);";
You should also use backticks in your INSERT statement (and your first CREATE query).
If I'm not mistaken, name is reserved word.

Javascript image slider doesnt work

I get the "Table creation success" message but no table is created.
<html>
<body>
<?php
$con=mysql_connect("localhost","root","");
//create db
mysql_query("CREATE DATABASE VashDedomenwn2", $con);
echo "Db creation success <br>";
//create table
$sql= mysql_query("CREATE TABLE VashDedomenwn2.phone_book
(
personID int NOT NULL,
PRIMARY KEY(person ID),
LastName varchar(20) NOT NULL,
FirstName varchar(20),
Address varchar(30),
Age int,
Phone varchar(10)
)
");
mysql_query($sql,$con);
echo "Table creation success <br>";
//END CONNECTION
mysql_close($con);
?>
</body>
</html>
I'm a newbie in php! Probably it's a stupid mistake... Thanks fot the help
Before you create a table, you must open the database you created.
//create db
mysql_query("CREATE DATABASE VashDedomenwn2", $con);
echo "Db creation success <br>";
mysql_select_db("database name", $con);
//create table
...
And change
$sql= mysql_query("CREATE TABLE VashDedomenwn2.phone_book
(
...
)
");
to
$sql= mysql_query("CREATE TABLE `VashDedomenwn2.phone_book`
(
...
)
");
OK, as #php_purest said, use mysqli is better. Mysqli is the improved version of mysql which support OOPS. It can reduce the pressure of your server.
Like this:
$conn = new mysqli("localhost","root","");
$conn->query("CREATE DATABASE VashDedomenwn2");
echo "Db creation success <br>";
$conn->select_db("VashDedomenwn2");
//create table
$conn->query("CREATE TABLE `VashDedomenwn2.phone_book`
(
personID int NOT NULL PRIMARY KEY,
LastName varchar(20) NOT NULL,
FirstName varchar(20),
Address varchar(30),
Age int,
Phone varchar(10)
)
");
echo "Table creation success <br>";
//END CONNECTION
$conn->close();

PHP/MYSQL: table was not created in wamp server

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.)

Categories