The simplest
<?PHP$con=mysql_connect("localhost", "root", "root");if(!$con) { die(' Could not connect: '.Mysql_error()); }if(mysql_query("CREATE DATABASE wzd",$con)) { Echo"Database created"; }Else { Echo"Error Creating Database:".Mysql_error(); }Mysql_close($con);?>
Example (Mysqli-object-oriented)
<?PHP$servername= "localhost";$username= "username";$password= "Password";//Create a connection$conn=NewMysqli ($servername,$username,$password);//Detecting Connectionsif($conn-connect_error) { die("Connection failed:".)$conn-connect_error);} //Create Database$sql= "CREATE DATABASE MyDB";if($conn->query ($sql) ===TRUE) { Echo"Database created successfully";} Else { Echo"Error Creating Database:".$conn-error;}$conn-close ();?>
Creating a Database "Mydbpdo" using the PDO instance
<?PHP$servername= "localhost";$username= "username";$password= "Password";Try { $conn=NewPDO ("mysql:host=$servername;d Bname=mydb ",$username,$password); //Set PDO error mode to exception $conn->setattribute (Pdo::attr_errmode, PDO::errmode_exception); $sql= "CREATE DATABASE mydbpdo"; //use EXEC (), because no results are returned $conn-exec($sql); Echo"Database created Successfully<br>"; }Catch(pdoexception$e) { Echo $sql. "<br>".$e-GetMessage (); }$conn=NULL;?>tip: The biggest benefit of using PDO is that you can use exception classes to handle problems when there is a problem with the database query process. IfTry{} The code block has an exception, the script stops executing and jumps to the firstCatch() {} code block execution code. In the block of code captured above we output the SQL statement and generate an error message.
The object-oriented idea is: The class is a design drawing, the object is produced according to this drawing product,
All the properties and methods of the custom class are for the object of the future instance,
Object-oriented and object-based, object-based objects are changing properties and methods in the presence of objects, while object-oriented is that the object does not exist at the beginning,
Several ways to add a database to PHP