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:
2
Answers
Turns out I am using a new version of PHP and the functions I was using were obsolete.
The code below works:
The easiest way to use a database in PDO is to name it in the DSN when you connect:
If you want to change the default database, you can use
PDO::exec()
to run aUSE <database>
statement:You can’t use
mysql_select_db()
because all themysql_*
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.