Hello Joy of PHP readers,
An asture reader has pointed out a bug in one of my scripts and, frankly, it was so embarassing that I just had to share it with you all. I’d like to think it’s a mistake any beginner can make, and as such I want to share it with you so that you don’t learn the wrong things.
The mistake I made was related to using PHP to interact with the mySQL database. There are actually two different libraries for interacting with mySQL and those two libraries are 1) mysql and 2) mysq1i
The mysql library was the original way to access mySQL using PHP, but along the way some smart people figured out a better way to do it, and came out with the mysqli (for mysql – improved) library. In general, the mysqli is the preferred way to access mySQL from PHP now. Here’s a link to more documentation about mysqli
At page 84 of the book (Kindle readers can search for th phrase ‘Code Listing: createdb.php’ since Kindle doesn’t have page numbers) you will find a script that creates the database which stores information about the cars. The mistake I made was to use mysqli to create the database, but I used mysql to display any errors. You can’t mix mysql and mysqli in the same script, you have to pick.
In particular lines 9 – 12 worked fine if your username and password were correct, but didn’t really trap the error if there was a mistake. Again, the problem was incorrectly mixing mysqli and mysql. The corrected code is shown below.
Original Code:
[php]
<?php
/**
* Joy of PHP sample code
* Demonstrates how to create a database, create a table, and insert records.
*/
$mysqli = new mysqli(‘localhost’, ‘root’, ‘mypassword’ );
if (!$mysqli) {
die(‘Could not connect: ‘ . mysql_error());
}
echo ‘Connected successfully to mySQL. <BR>’;
/* Create table doesn’t return a resultset */
if ($mysqli->query("CREATE DATABASE Cars") === TRUE) {
echo "<p>Database Cars created</P>";
}
else
{
echo "Error creating Cars database: " . mysql_error()."<br>";
}
[/php]
Corrected Code
[php]
<!–?php <br ?–>
/**
* Joy of PHP sample code
* Demonstrates how to create a database, create a table, and insert records.
*/
$mysqli = new mysqli(‘localhost’, ‘root’, ‘mypassword’ );
if (mysqli_connect_error()) {
die(‘Could not connect: ‘ . mysqli_connect_error());
echo ‘Connected successfully to mySQL.’;
/* Create table doesn’t return a resultset */
if ($mysqli->query("CREATE DATABASE Cars") === TRUE) {
echo "Database Cars created";
}
else
{
echo "Error creating Cars database: " . $mysqli->error."<br>";
}
[/php]
A special thanks to Matteo Sisti Sette for taking the time to point this out to me! I appreciate it.
I will fix this in the book and make a few other changes too. Look for a second edition in approximately the next 30 days or so.
Happy coding,
Alan