PHP to connect and query from WordPress mysql database
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 …
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…
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 …
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…