I am trying to populate a database with tables (am new to this) The message I get back upon execution of .php is:
Table "users" successfully created
Table "tempRes" successfully created
Table "empRec" successfully created
However the second and third tables are not appearing in the database in phpMyAdmin. SHOW TABLES & SHOW TABLE STATUS only shows "user" table.
Does anyone know why this is happening? How can I rectify?
Here is my code:
<?php
// connect to the MySQL server
$conn = new mysqli('localhost', 'fiona', 'xxx', 'Org_db');
// check connection
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
// Performs the $sql query on the server to create the table users
$sql = "CREATE TABLE IF NOT EXISTS `users` (
`id` INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(25) NOT NULL,
`pass` VARCHAR(18) NOT NULL,
`email` VARCHAR(45),
`reg_date` TIMESTAMP
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8";
// performs query to check table successfully created or get error message
if ($conn->query($sql) === TRUE) {
echo '<br/>Table "users" successfully created<br/>';
}
else {
echo 'Error: '. $conn->error;
}
// Performs the $sql query on the server to create the table temporary reservations
"CREATE TABLE IF NOT EXISTS `tempRes` (
`tr_id` INT NOT NULL AUTO_INCREMENT,
`aaid` INT NOT NULL,
`cid` INT NOT NULL,
`date_res` DATE NOT NULL,
`rem` VARCHAR(5) NOT NULL,
primary key ( `tr_id` )) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8";
if ($conn->query($sql) === TRUE) {
echo 'Table "tempRes" successfully created<br/>';
}
else {
echo 'Error: '. $conn->error;
}
// Performs the $sql query on the server to create the table employee records
"CREATE TABLE IF NOT EXISTS `empRec` (
`eid` INT NOT NULL auto_increment,
`empPos` VARCHAR( 20 ) NOT NULL,
`tfn` INT NOT NULL,
`emp_DOB` DATE NOT NULL,
`eStart` DATE NOT NULL,
`super_co` VARCHAR( 30 ),
`s_mem_no` INT NOT NULL,
`icin` INT NOT NULL,
`epn` INT NOT NULL,
primary key ( emp_id )) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8";
if ($conn->query($sql) === TRUE) {
echo 'Table "empRec" successfully created<br/>';
}
else {
echo 'Error: '. $conn->error;
}
?>
Your not storing the second and third create statements in $sql variable. That's why isn't it?
Add $sql = infront of those two statements as well
Related
I'm having a problem creating a dynamic table in the database. If the table already exists in the database, then a new one should not be created.
if( mysqli_num_rows(mysqli_query("SHOW TABLES LIKE abc")) == 1){
echo "Already Exit";
} else {
//echo "not exit";
$sql="CREATE TABLE `decoration`.`newtable` (`id` INT NOT NULL AUTO_INCREMENT ,`company_id` VARCHAR( 20 ) NOT NULL ,`list_name` VARCHAR( 50 ) NOT NULL ,`created` INT NOT NULL ,`modified` INT NOT NULL ,`status` INT NOT NULL ,PRIMARY KEY ( `id` )) ENGINE = INNODB";
if ($con->mysqli_query($sql)){
echo "created";
} else {
echo "not created";
}
}
You can go with below query
CREATE TABLE IF NOT EXISTS `schema`.`Employee` (
`idEmployee` VARCHAR(45) NOT NULL ,
`Name` VARCHAR(255) NULL ,
`idAddresses` VARCHAR(45) NULL ,
PRIMARY KEY (`idEmployee`) ,
CONSTRAINT `fkEmployee_Addresses`
FOREIGN KEY `fkEmployee_Addresses` (`idAddresses`)
REFERENCES `schema`.`Addresses` (`idAddresses`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin
IF NOT EXISTS will check the table exists or not and if table exists in the database it will not create new one.
Ref : http://dev.mysql.com/doc/refman/5.7/en/create-table.html
Hope this will help!
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;
}
I'm trying to copy 2 tables structures into a new database.
I use a function that makes by herself the SQL command: When i execute the code on phpmyadmin the code gets executed but when I execute this by PHP, it doesn't execute.
How is possible?
The sql command is this:
CREATE TABLE `tabella_1` (
`campo1` int(11) NOT NULL AUTO_INCREMENT,
`campo2` varchar(100) COLLATE latin1_general_ci NOT NULL,
`campo_3` int(11) NOT NULL,
PRIMARY KEY (`campo1`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
CREATE TABLE `tabella_2` (
`campo1` int(11) NOT NULL DEFAULT '0',
`campo2` varchar(100) COLLATE latin1_general_ci NOT NULL,
`campo_3` int(11) NOT NULL,
PRIMARY KEY (`campo1`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
Thanks
Update this code with your database connection details:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 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 `tabella_1` ( `campo1` int(11) NOT NULL AUTO_INCREMENT, `campo2` varchar(100) COLLATE latin1_general_ci NOT NULL, `campo_3` int(11) NOT NULL, PRIMARY KEY (`campo1`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci";
if ($conn->query($sql) === TRUE) {
echo "Table 1 created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
// sql to create table
$sql2 = "CREATE TABLE `tabella_2` ( `campo1` int(11) NOT NULL DEFAULT '0', `campo2` varchar(100) COLLATE latin1_general_ci NOT NULL, `campo_3` int(11) NOT NULL, PRIMARY KEY (`campo1`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci";
if ($conn->query($sql2) === TRUE) {
echo "Table 2 created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
I got it!
I putted in a array() the functions and it works!
Tkanks to everybody!
I have made a user_login table, having pk = userid.
A credit_request table is created which references to userid as fk.
when the user login, he should see only his entries in the dashboard.
But, here i am not able to insert data, once i link a foreign key to it.
and even the data inserted through phpmyadmin is visible to all users.
Please help me out.
how to insert and retrieve data for logged in users.
<>
//Database setup for Credit request
//Insert data into Credit request
if(isset($_POST['taskid']))
{
$taskid =$_POST['taskid'];
$orderid = $_POST['orderid'];
$status = $_POST['status'];
$query1 = "INSERT INTO credit_request(taskid, orderid, status)
VALUES ('$taskid', '$orderid', '$status')";
if ($connect->query($query1) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $query1 . "<br>" . $connect->error;
}
}
//Display data for credit request
$query2 = "SELECT taskid, orderid, status FROM credit_request WHERE agentid = '$userid'";
$res = $connect->query($query2);
if ($res->num_rows > 0) {
// output data of each row
while($row = $res->fetch_assoc()) {
echo "<br>taskid: " . $row["taskid"]. " -orderid: " . $row["orderid"]. " --:" . $row["status"]."";
}
} else {
echo "0 results";
}
I think you have problem on update, on delete when creating foreign key..
Here's an example of how you'd build your schema:
CREATE TABLE `country` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`country_name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
CREATE TABLE `state_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`state_name` varchar(45) DEFAULT NULL,
`country_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `country_fk` FOREIGN KEY (`country_id`)
REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='';
INSERT INTO country (country_name) VALUES ('US of A');
INSERT INTO state_table (state_name,country_id) VALUES
('Minnesota', 2),
('Arizona', 2);
See this fiddle for more.
I am trying to read from a database in MySQL and insert my data in another database in MySQL .
my first table is like this
CREATE TABLE IF NOT EXISTS `link` (
`_id` bigint(20) NOT NULL AUTO_INCREMENT,
`country` varchar(30) COLLATE utf8 DEFAULT NULL,
`time` varchar(20) COLLATE utf8 DEFAULT NULL,
`link` varchar(100) COLLATE utf8 DEFAULT NULL,
PRIMARY KEY (`_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=6149 ;
and the second table is
CREATE TABLE IF NOT EXISTS `country` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(15) CHARACTER SET utf8 NOT NULL,
`Logo` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `Name_3` (`Name`),
UNIQUE KEY `ID` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8457 ;
There are about 6114 rows in first table that I'm trying to insert to second using this code
<?php
$tmp = mysqli_connect(******, *****, ****, *****); // First table in here
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$main = mysqli_connect(*****, *****, ****, ******); //Second table in here
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$req = "SELECT country FROM link";
$result = mysqli_query($tmp, $req) or die( mysqli_error($tmp) );
echo "-> ".mysqli_num_rows($result)."<br>";
while ($row = mysqli_fetch_array($result)) {
$con = $row["country"];
$req = "INSERT IGNORE INTO country (Name) VALUES ('$con')";
mysqli_query($main, $req) or die( mysqli_error($main) ) ;
}
?>
problem is the php code works but for 6114 take a very long time which I can't afford .
what is causing the code to take this long to work ? is it the "INSERT IGNORE" ?
is there any way I can do this faster ?
Since the databases are on the same server, you can simply use INSERT ... SELECT (which avoids having to bring the data into PHP and loop over the results executing separate database commands for each of them, so will be considerably faster):
INSERT INTO db2.country (Name) SELECT country FROM db1.link
you can try a create an index on column "country" of table Link.