Working with databases in PHP. MySQL module

If before (before php 5.0) it was possible to use a more or less trivial way of working with databases in php (using the MySQL module), then with new versions of php it is necessary to switch to new modules, such as mysqli or pdo. The MySQL module is deprecated in php 5.5.x and will soon be completely excluded.

In this note we will remind you how to use the MySQL module, but use modern interfaces for work (see the next notes). To use the minimum functionality of the MySQL module you only need to remember a few functions (of course, there are many more of them, here only the necessary minimum is presented).

  • resource mysql_connect ([ string $server = ini_get("mysql.default_host") [, string $username = ini_get("mysql.default_user") [, string $password = ini_get("mysql.default_password") [, bool $new_link = false [, int $client_flags = 0 ]]]]] )

Establishes a connection with the database. For example:

$db = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
    or die('Connection error: ' . mysql_error());
  • bool mysql_select_db ( string $database_name [, resource $link_identifier = NULL ] )

Selects the database to work with. For example:

mysql_select_db('db_name') or die('Database selection error');
  • resource mysql_query ( string $query [, resource $link_identifier = NULL ] )

Sends a query for execution. For example:

$sql = 'SELECT * FROM db_table';
$query = mysql_query($sql);
  • array mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] )
Processes a row of query result as an associative, numeric, or associative-numeric array, moves the internal data pointer forward. For example:
$result = mysql_fetch_array($query, MYSQL_ASSOC);
In principle, this is the necessary minimum - in the case of an existing database, these queries are sufficient for data manipulation.

There is only one problem left - protection against SQL injections. Data received from users may contain special characters that are used in queries and that can lead to errors or even data loss (in the case of a deliberate attack). Therefore, it is worth escaping the received data using the function

  • string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier = NULL ] )

For example:

$string = mysql_real_escape_string("product 'How I Spent This Summer'");

As a result, the quotes will be escaped:

$string == "product 'How I Spent This Summer'")
So, our example now looks like this:
$db = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
    or die('Connection error: ' . mysql_error());
mysql_select_db('db_name') or die('Database selection error');
$sql = 'SELECT * FROM db_table';
$query = mysql_query($sql); 

while ($result = mysql_fetch_array($query, MYSQL_ASSOC)) {
  echo $result['db_field'];  
};