I have this code however, when the database already exists, I get an empty response and echo doesn't show anything:
try
{
//die('here');
$conn = new PDO("mysql:host=$host", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (!PDO_select_db($conn, $dbName)){
echo "Database doesn't exist!";
$sql = "CREATE DATABASE ".$dbName;
if ($conn->query($sql) === TRUE) {
echo "Database was created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
}
else {
echo "Database already exists!";
}
}
What is wrong with this code?
As you see, using Firefox Inspect, in Network tab, I see No response data available for this request
.
Expected behavior: since the database already exists, I am expecting to see Database already exists!
in the Response section of Network tab.
So, my database, named judges
, exists and using $ php -l submit.php
I see that my code has no error.
I can also see this in phpMyAdmin GUI:
CodePudding user response:
The easiest way to use a database in PDO is to name it in the DSN when you connect:
$conn = new PDO("mysql:host=$host;dbname=name_of_db", $username, $password);
If you want to change the default database, you can use PDO::exec()
to run a USE <database>
statement:
$conn->exec("USE name_of_db");
You can't use mysql_select_db()
because all the mysql_*
functions were deprecated in PHP 5.5 (circa 2013), and removed from PHP in version 7.0 (2015). You should use more current resources to learn PHP and PDO.
PS: Honestly, I don't add CREATE DATABASE to my application code. The database just better exist. If it doesn't, references to it will throw an exception, so I create the database manually before I deploy my application. Since that needs to happen only once, it's a waste of time and lines of code to check that the database exists during every PHP request.
CodePudding user response:
Turns out I am using a new version of PHP and the functions I was using were obsolete.
The code below works:
$host = "localhost";
$username = "root";
$password = "";
$dbName = "judges";
try
{
$conn = new mysqli($host, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// If database is not exist create one
if (!mysqli_select_db($conn,$dbName)){
$sql = "CREATE DATABASE ".$dbName;
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
}else {
echo "Error creating database: " . $conn->error;
}
}
}
catch(PDOException $e)
{
echo "in catch block";
echo "Connection failed: " . $e->getMessage();
echo $sql . "<br>" . $e->getMessage();
}