11.07.2015 Views

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

www.it-ebooks.infoCHAPTER 30 • USING <strong>PHP</strong> WITH MYSQL// Select the database$mysqli->select_db('corporate');Once a database has been successfully selected, you can then execute database queries against it.Executing queries, such as selecting, inserting, updating, and deleting information with the mysqliextension, is covered in later sections.Once a script finishes execution, any open database connections are automatically closed and theresources are recuperated. However, it’s possible that a page requires several database connectionsthroughout the course of execution, each of which should be closed as appropriate. Even in the casewhere a single connection is used, it’s no<strong>net</strong>heless good practice to close it at the conclusion of thescript. In any case, close() is responsible for closing the connection. An example follows:$mysqli = new mysqli();$mysqli->connect('localhost', 'catalog_user', 'secret', 'corporate');// Interact with the database…// close the connection$mysqli->close()Handling Connection ErrorsOf course, if you’re unable to connect to the <strong>MySQL</strong> database, then little else on the page is going tohappen as planned. Therefore, you should be careful to monitor connection errors and reactaccordingly. The mysqli extension includes a few features that can be used to capture error messages, oralternatively you can use exceptions (as introduced in Chapter 8). For example, you can use themysqli_connect_errno() and mysqli_connect_error() methods to diagnose and display informationabout a <strong>MySQL</strong> connection error.Retrieving Error InformationDevelopers always strive toward that nirvana known as bug-free code. In all but the most trivial ofprojects, however, such yearnings are almost always left unsatisfied. Therefore, properly detecting errorsand returning useful information to the user is a vital component of efficient software development. Thissection introduces two functions that are useful for deciphering and communicating <strong>MySQL</strong> errors.Retrieving Error CodesError numbers are often used in lieu of a natural-language message to ease software internationalizationefforts and allow for customization of error messages. The errno() method returns the error codegenerated from the execution of the last <strong>MySQL</strong> function or 0 if no error occurred. Its prototype follows:class mysqli {int errno}An example follows:591

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!