PHP and MYSQL database connection and table creation only once - php

I'm developing a small application for my academic. i have a registration form and a log_in form. Here is what i want, i have a database configuration file which contains "connection to server, creating database and creating table queries" included in it. I've included this database file at the top of my registration form so that when the page is loaded the "query should execute and create database and table ONLY ONCE". But the problem is the query is successfully executing for the first time but when the registration page is loaded again, it prompt's an error "DATABASE ALREADY EXISTS". Please me.
I've attached the db.php code..
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$connect = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$connect) {
die('SERVER CONNECTION FAILED...\n: ' . mysql_error());
}
;
$sql = 'CREATE DATABASE USERS';
$retval = mysql_query($sql, $connect);
if (!$retval) {
die('DATABASE CREATION FAILED\n: ' . mysql_error());
}
;
$sql = "CREATE TABLE USERS( " . "Memberid int(10) NOT NULL AUTO_INCREMENT,
" . "Name varchar(100) NOT NULL,
" . "Username varchar(20) NOT NULL,
" . "Password varchar(10) NOT NULL,
" . "Email varchar(20) NOT NULL,
" . "Activation varchar(40) DEFAULT NULL,
" . "Status int(1) NOT NULL DEFAULT '1',
" . "PRIMARY KEY (`Memberid`)); ";
mysql_select_db('USERS');
$retval = mysql_query($sql, $connect);
if (!$retval) {
die('COULD NOT CREATE TABLE\n: ' . mysql_error());
}
;
mysql_close($connect);
?>
<html>
<body>
//registration form code
</body>
</html>

query to create database only once if it doesn't exists
CREATE DATABASE IF NOT EXISTS DBName;
query to create table only once if it doesn't exists
CREATE TABLE IF NOT EXISTS tablename;

You are able to create database/table once only.
Change
CREATE DATABASE
To:
CREATE DATABASE IF NOT EXISTS
Same changes should be applied for the table creation statement.

Try this change
CREATE DATABASE IF NOT EXISTS USERS
And for table
CREATE TABLE IF NOT EXISTS tablename;

Related

Cannot create a Table in database

I'm writing an simple form in PHP that get input and insert it to database, I had succeeded in creating a database, but not a table. I use Xampp for the database.
Here is my code for creating a table:
mysqli_select_db($DBconnect, $DBname);
$TableName = "Bugtrack";
$SQLstring = "SHOW TABLES LIKE ' " . $TableName . "' ";
if ($stmt = mysqli_prepare($DBconnect, $SQLstring)) {
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
if (mysqli_stmt_num_rows($stmt) == 0) {
mysqli_stmt_close($stmt);
$SQLstring = "CREATE TABLE" . $TableName . "(BugID SMALLINT
. NOT NULL AUTO_INCREMENT PRIMARY KEY,
. Game VARCHAR(10), Version VARCHAR(5),
Platform VARCHAR(10), Frequency VARCHAR(5),
proposed_solution TINYTEXT)";
if ($stmt = mysqli_prepare($DBconnect, $SQLstring)) {
$QueryResult = mysqli_stmt_execute($stmt);
if ($QueryResult === FALSE) {
echo "<p>Unable to create the table.</p>"
. "<p>Error code "
. mysqli_errno($DBConnect)
. ": " . mysqli_error($DBConnect)
. "</p>";
}
mysqli_stmt_close($stmt);
}
}
}
Try echoing $SQLstring and run the query in mysql console. It will point you to the exact problem with your query.
Modify this line to $SQLstring = "CREATE TABLE" . $TableName . "(BugID SMALLINT to $SQLstring = "CREATE TABLE " . $TableName . " (BugID SMALLINT
Instead of checking $SQLstring = "SHOW TABLES LIKE ' " . $TableName . "' "; you can check it like $SQLstring = "CREATE TABLE " . $TableName . " if not exists (BugID SMALLINT
If you are using XAMPP, go to localhost/phpmyadmin using your webbrowser.
Select your database, then select sql.
To create your table.
CREATE TABLE Bugtrack (
BugID INT(8) NOT NULL AUTO_INCREMENT PRIMARY KEY,
Game VARCHAR(10), Version VARCHAR(5),
Platform VARCHAR(10),
Frequency VARCHAR(5),
proposed_solution TINYTEXT
)
If you really want to do it with php. I would use PDO.
$username = 'me';
$password = 'my_super_secret_password';
$dsn = 'mysql:host=localhost;dbname=my_database';
$conn = new PDO($dsn, $username, $password);
$sql = 'CREATE TABLE Bugtrack (
BugID INT(8) NOT NULL AUTO_INCREMENT PRIMARY KEY,
Game VARCHAR(10), Version VARCHAR(5),
Platform VARCHAR(10),
Frequency VARCHAR(5),
proposed_solution TINYTEXT
)';
$conn->execute($sql);
OR
Go to localhost/phpmyadmin, click on you database on the left hand side. You will see an option to create a table. I also would make sure that you have permission for the database that you created. To do that, while you are in phpmyadmin, click your database, select the privileges tab that is almost at the top of the page. From there just follow the prompts.

Cannot create TABLE with php mysql

I'm not sure what's happening here but I cannot seem to create the table.
Is this a syntax error or something else?
When I tried to paste the CREATE TABLE part into the SQL part on PHPMyAdmin, I had to tinker with the syntax a bit before it worked.
What I want to be able to do it via PHP directly.
$server = 'localhost';
$user = 'root';
$pass = '';
$conn = mysqli_connect($server, $user, $pass);
if (!$conn){
echo "Failed to connect to Server";
}else{
echo "Connected";
}
$sql = 'CREATE DATABASE college';
$table = 'CREATE TABLE students(
student_id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
student_name VARCHAR(255) NOT NULL,
student_email VARCHAR(255) NOT NULL,
student_city VARCHAR(255) NOT NULL,
)';
if(mysqli_query($conn,$sql)){
echo"Database created";
}else{
echo 'Failed to create Database';
};
if(mysqli_query($conn,$table)){
echo "Table Created";
}else{
echo "Failed to create Table";
};
After create database successfully to need to select database then use create statement
mysqli_select_db ( $conn , 'college' );// select database first
if(mysqli_query($conn,$table)){
echo "Table Created";
}else{
echo "Failed to create Table";
};
Remove the comma in the end of the below line inside the CREATE TABLE
student_city VARCHAR(255) NOT NULL,
it will cause the error below:
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 ''' at line 1

Error performing sql query in PHP

I am trying to learn using mysql in php. I started off trying to create a table in mysql, and using the mysqli extension.
My code:
<?php
$truemsg = "Table created successfully";
$falsemsg = "Error creating table: ";
$servername = "localhost";
$username = "myuser";
$password = "mypass";
$db = "mytable";
// Create database
$sql = "USE ".$db.";".
'CREATE TABLE IF NOT EXISTS Authentication (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
userid VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL,
role VARCHAR(20) NOT NULL,
email VARCHAR(50)
);';
print "Sql command is ".$sql;
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
print "<p></p>";
if ($conn->query($sql) === TRUE) {
echo $truemsg;
} else {
echo $falsemsg . $conn->error;
}
$conn->close();
?>
The error is:
Sql command is USE mytable;CREATE TABLE IF NOT EXISTS Authentication ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, userid VARCHAR(30) NOT NULL, password VARCHAR(30) NOT NULL, role VARCHAR(20) NOT NULL, email VARCHAR(50) );
Error creating table: 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 'CREATE TABLE IF NOT EXISTS Authentication ( id INT(6) UNSIGNED AUTO_INCREMENT PR' at line 1
I tried pasting the same command on the mysql command line, and it works fine. What's the problem using this in php?
You are supposed to run queries one by one
$sql = "query one";
$conn->query($sql);
$sql = 'query two';
$conn->query($sql);
instead of coupling them all in one statement.
DO NOT use mysqi_multi_query() either, this asynchronous function is not intended for the everyday use.
Also, in this particular case USE query is superfluous. Database should go into constructor:
$conn = new mysqli($servername, $username, $password, $db);
^^^ here
Also, tell mysqli to throw errors by itself, automatically, instead of checking result of every database command manually:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
This way you will get neat and clean code:
<?php
$servername = "localhost";
$username = "myuser";
$password = "mypass";
$db = "mytable";
// Create data table
$sql = 'CREATE TABLE IF NOT EXISTS Authentication (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
userid VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL,
role VARCHAR(20) NOT NULL,
email VARCHAR(50)
)';
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $db);
// Run a query
$conn->query($sql);
echo "Table created successfully";
This code will either report that table has been created successfully, or emit an error, with a detailed explanation on what went wrong.
This seems to be like a mysql multiple query problem
$conn->select_db($db);
you can use this function before the query to use the database and remove the use database statement from your query string , then you query string becomes
$sql = 'CREATE TABLE IF NOT EXISTS Authentication (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
userid VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL,
role VARCHAR(20) NOT NULL,
email VARCHAR(50)
)';
that may work for you ..

Creating database tables within Dreamweaver not working

I've used this script to link to my database account (1&1), using Dreamweaver, which proves to be a successful connection yet cannot seem to create tables for my database when this is linked, was just wondering if anyone has any idea in how to go about the right way with this as I can't seem to get it working.
My database connection which works.
<?php
$hostname="db************";
$database="db********";
$username="db********";
$password="*********";
$link = mysql_connect($hostname, $username, $password);
if (!$link) {
die('Connection failed: ' . mysql_error());
}
else{
echo "Connection to MySQL server " .$hostname . " successful!
" . PHP_EOL;
}
$db_selected = mysql_select_db($database, $link);
if (!$db_selected) {
die ('Can\'t select database: ' . mysql_error());
}
else {
echo 'Database ' . $database . ' successfully selected!';
}
mysql_close($link);
?>
This is the tables script i'm using which doesn't work .
<?php
include_once("php_includes/db_conx.php");
// CREATE TABLE USER
$sql= "CREATE TABLE USER (
id_user_pk INT NOT NULL AUTO_INCREMENT,
nick VARCHAR(40),
email VARCHAR(40),
password VARCHAR(20),
user_reg_date DATE,
PRIMARY KEY (id_user_pk)
) TYPE=INNODB";
mysql_query($sql);
?>
You must use "ENGINE=INNODB" instead of "TYPE=INNODB";
CREATE TABLE `user` (
`id_user_pk` int(11) NOT NULL AUTO_INCREMENT,
`nick` varchar(40) DEFAULT NULL,
`email` varchar(40) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
`user_reg_date` date DEFAULT NULL,
PRIMARY KEY (`id_user_pk`)
) ENGINE=INNODB;

Attempting to create a database and table and insert some data

This is what I have so far.... I do not understand why it is not working? Any ideas? This is just a simple script to connect to a database, create a table and insert some data. I also want to retrieve the data but I think I may be jumping a little a head.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
if (mysql_query("CREATE_DATABASE nogjhghkgst98", $link))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
if ($link="CREATE TABLE contactsZ8 (id int(6) NOT NULL auto_increment,first varchar(15) NOT NULL,last varchar(15) NOT NULL,phone varchar(20) NOT NULL,mobile varchar(20) NOT NULL,fax varchar(20) NOT NULL,email varchar(30) NOT NULL,web varchar(30) NOT NULL,PRIMARY KEY (id),UNIQUE id (id),KEY id_2 (id))") {
echo "ineserted";
}
else
{
echo "not inserted" . mysql_error();
}
$link = "INSERT INTO contactsZ VALUES ('','John','Smith','01234 567890','00112 334455','01234 567891','johnsmith#gowansnet.com','http://www.gowansnet.com')";
$link="SELECT * FROM contactsZ";
$link=mysql_query($link);
mysql_close($link);
?>
There is definitely something wrong:
if ($link="CREATE TABLE contactsZ8 (id int(6) NOT NULL auto_increment,first varchar(15) NOT NULL,last varchar(15) NOT NULL,phone varchar(20) NOT NULL,mobile varchar(20) NOT NULL,fax varchar(20) NOT NULL,email varchar(30) NOT NULL,web varchar(30) NOT NULL,PRIMARY KEY (id),UNIQUE id (id),KEY id_2 (id))") {
an assignment in an if
query not executed (that is not so bad: once the table is created, executing again the query when reloading the page will fail)
assigning to $link ! this is confusing (but should not generate any error)...
Then :
$link = "INSERT INTO contactsZ VALUES ('','John','Smith','01234 567890','00112 334455','01234 567891','johnsmith#gowansnet.com','http://www.gowansnet.com')";
The query is not executed.
Edit: the INSERT is done in contactsZ, whereas the CREATE TABLE creates contactsZ8.
Edit2: And finally:
mysql_close($link);
After re-assigning 3 times $link, $link is not the (optional, by the way) link identifier any more...

Categories