问题
I've been sifting through the MySQLi docs, and as far as I can tell, I there's no way to create a database using PHP and MySQLi. Is this correct?
回答1:
The CREATE DATABASE statement is used to create a database in MySQL.
- Syntax:
CREATE DATABASE database_name
To get PHP to execute the SQL instructions, first you must create a mysqli object with the connection to the server, then use the query() method of the MySQLi class.
- Syntax:
mysqliObj->query($sql_query)
- mysqliObj - is the mysqli object created with new mysqli()
- $sql_query - is a string with SQL instructions. This method sends a query or command to a MySQL connection, will return a result object, or TRUE on success. FALSE on failure.
The following example creates a database called "tests":
<?php
// connect to the MySQL server
$conn = new mysqli('localhost', 'root', 'pass');
// check connection
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
// sql query with CREATE DATABASE
$sql = "CREATE DATABASE `tests` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci";
// Performs the $sql query on the server to create the database
if ($conn->query($sql) === TRUE) {
echo 'Database "tests" successfully created';
}
else {
echo 'Error: '. $conn->error;
}
$conn->close();
?>
Check this link http://coursesweb.net/php-mysql/php-mysql-using-mysqli
回答2:
If you have the permissions, you can execute a CREATE DATABASE
statement using mysqli_query
.
回答3:
You can create a database. Here is an example
<?php
$con=mysqli_connect("example.com","peter","abc123");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Create database
$sql="CREATE DATABASE my_db";
if (mysqli_query($con,$sql))
{
echo "Database my_db created successfully";
}
else
{
echo "Error creating database: " . mysqli_error($con);
}
?>
Found here http://www.w3schools.com/php/php_mysql_create.asp
来源:https://stackoverflow.com/questions/16403400/mysqli-is-it-possible-to-create-a-database