Reputation: 29
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.
Upvotes: 1
Views: 551
Reputation:
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);
}
?>
Upvotes: 0
Reputation: 6232
$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);
Upvotes: 0
Reputation: 1219
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.
Upvotes: 0
Reputation: 61
$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);
Upvotes: 1
Reputation: 19736
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.
Upvotes: 2
Reputation: 1135
http://dev.mysql.com/doc/refman/5.0/en/use.html
USE my_db1;
CREATE TABLE ...
USE my_db2;
CREATE TABLE ...
Upvotes: 1