PHP: MySQL Database Query Example

By Xah Lee. Date: . Last updated: .

This page shows you how to use php to query a MySQL database.

Prerequisite: we assume you have a database running. In the following, we'll need a server name, user name, password, and a database name.

Here's a example of executing a create table query.

<?
$server = "example.org";
$db_user = "xuser";
$db_password = "th3oceu";
$db_name = "xltest";

// connect to the server
$link = mysql_connect($server, $db_user, $db_password) or die('Could not connect: ' . mysql_error());

// select a db
mysql_select_db($db_name) or die('Could not select database');

// sql query string
$query = <<<ththth
CREATE TABLE user_info (
login_name VARCHAR(50) PRIMARY KEY,
password VARCHAR(17) NOT NULL,
passphrase VARCHAR(17),
user_first_name VARCHAR(20),
user_middle_name VARCHAR(20),
user_last_name VARCHAR(20),
user_email VARCHAR(40),
user_class ENUM("admin","mod","normal","guest"),
school_id INT,
login_creation_date DATE,
timestamp timestamp);
ththth;

$result = mysql_query($query) or die('Query failed: ' . mysql_error());

  mysql_close($link);

If you have a question, put $5 at patreon and message me.

  1. PHP Install
  2. PHP Basics
  3. String Syntax
  4. String Operations
  5. Array
  6. Hash Table
  7. Looping Thru Array
  8. Function
  9. Write Package
  10. Send HTML Mail
  11. Send Mail with Attachment
  12. MySQL Database Query