0

Is the following code correct to create a database in php?

<?php

    $con=mysql_connect('localhost','admin','admin');
    if(!$con)
    {
        die("could not connect:' .mysql_error());
    }


    $sql = "CREATE DATABASE db1";
    mysql_select_db("db1", $con);
    $sql = "CREATE TABLE year
    (
        ayear varchar(10),
        fyear varchar(10)

    )";
    if(isset($_POST['id'])) 
    { 
        $ayear = $_POST['ayear'];
        $fyear = $_POST['fyear'];
        if($ayear != "" && $fyear != "") 
        {
            $query = "INSERT INTO year VALUES ('$ayear', '$fyear')"; 
            $result = mysql_query($query) or die(mysql_error());
        }
        else 
            echo "one of the field is empty";
     } 
    if (!mysql_query($sql,$con))
    {
         die('Error: ' . mysql_error()); 
    }
    mysql_close($con); 

?> 

After executing the code, if i check in MySql for the created database, the database was not created. What is the problem with the code? how can i improvise it? Can't i use create database command inside the

2

5 Answers 5

3

You just have written query to create database didn't execute it.replace below code with your code

$sql = "CREATE DATABASE db1";
mysql_query($sql, $con);
mysql_select_db("db1", $con);
2
  • kindly update your code in que so I can identify possible bug. Commented Jan 28, 2013 at 7:32
  • I can see lots of bugs in you existing code as you have only written sql queries but forgot to execute them most of the times. Commented Jan 28, 2013 at 7:33
1

Try this--

$sql = "CREATE DATABASE db1";
if (mysql_query($sql, $con)) {
    echo "Database db1 created successfully\n";
} else {
    echo 'Error creating database: ' . mysql_error();
}
mysql_select_db("db1", $con);
1

Just for diversity's sake and because we often say here that it's better start using PDO over mysql_* this how you might do that using PDO

<?php
//Connect to mysql, omit db name since we want to check if db exist
$db = new PDO('mysql:host=localhost;charset=UTF-8', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

//Create db if it doesn't exist
$sql = "CREATE DATABASE IF NOT EXISTS db1";
$db->exec($sql);
//Select db since we didn't provide that information in DSN
$sql = "USE db1";
$db->exec($sql);
//Create table if doesn't exist
$sql = "CREATE TABLE IF NOT EXISTS `year`
        (ayear varchar(10), fyear varchar(10))";
$db->exec($sql);

//Don't forget to include all your necessary checks somewhere here
if(isset($_POST['id']) && 
   isset($_POST['ayear']) && $_POST['ayear'] && 
   isset($_POST['fyear']) && $_POST['fyear']) { 

    //Don't forget to include the code to check and sanitize user's input
    $ayear = $_POST['ayear'];
    $fyear = $_POST['fyear'];

    //Insert data using prepared statement
    $query = $db->prepare("INSERT INTO `year` VALUES (:ayear, :fyear)"); 
    $query->execute(array(':ayear' => $ayear, ':fyear' => $fyear));

    //Select data from the table
    $sql = "SELECT * FROM `year`";
    foreach ($db->query($sql) as $row) {
        echo "ayear: " . $row['ayear'] . "  fyear: " . $row['fyear'] . "<br>";
    }
} else {
    echo "One of the field is empty.";
}
//Close the connection to the db
$db = null;
?>

Disclaimer: error handling, checks, input sanitation skipped for brevity.

0

Made change in :

$sql = "CREATE DATABASE db1";
$result = mysql_query($sql);

mysql_select_db("db1", $con);

It should be work. it will create database with db1 name and also create table year in it.

0

You should also execute query:

$sql = "CREATE DATABASE db1";
mysql_query($sql);

Then, your database will be created successfully.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.