PHP to connect and query from WordPress mysql database

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

In this tutorial, we will learn how to write PHP to connect to a mysql database and then perform a query.  For a newer tutorial, see here also. For the purpose of demonstration, the mysql database that we will query will be a WordPress database.

1.  Start with a basic PHP file called index.php …

PHP connecting to mysql

PHP connecting to mysql

2.  To connect to the mysql database, we create a new mysqli object passing into its constructor the database host, the database user, the database user password, and the database name.  You need to have these four credentials in order to gain access.  If $mysqli->connect_errno has a non-zero number, that means the connection failed and we display the error number and error message by $mysqli->connect_errno and $mysqli->connect_error respectively.

3.  Otherwise, connection was successful and we continue with our newly instantiated $mysqli object which we put to good use by invoking its query method…

mysqli query

mysqli query

For the purpose of this example, we are just querying a WordPress database for posts that are published and of post_type=’post’.

If the query fails, it returns false.  Otherwise, we get a mysqli_result object which has a host of methods we can use.

4. We’ll use the fetch_assoc() in a while loop to get our result rows …

fetch rows

fetch rows

5. The individual fields of the row can be accessed by $row[‘ID’] and $row[‘post_title’].  We are not going to assume that the data coming out of the database is sanitized, so we pass it through htmlspecialchars() before displaying them out in <li>’s of an unordered list.

And this is what we get…

sql query output

sql query output