简体   繁体   中英

how to establish connection to database using PHP MySql

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

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

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

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.

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.

You should also execute query:

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

Then, your database will be created successfully.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM