Two technologies complement each other with no questions asked, PHP and MySQL. This article will teach you how to use PHP to fetch data stored in a MySQL database.
What is mysql_fetch_array()
The PHP mysql_fetch_array()
is a function that allows you to fetch a MySQL row as a numeric array or a PHP associative array.
It gets a row from the mysql_query()
function and returns the result as an array. If the function fails, it produces a Boolean false.
The syntax of the function can be expressed as:
mysql_fetch_array(data, array_type);
The parameter data
refers to a specific data pointer. This is usually the result of the mysql_query()
method.
You can also specify the array type to be returned from the function.
Supported values for this parameter include:
MYSQL_ASSOC
– Returns an associative array.MYSQL_NUM
– Return a numeric array.MYSQL_BOTH
– Both numeric and/or associative arrays.
Let us explore how we can use this function using PHP examples.
How to use mysql_fetch_array()
Take a look at the code snippet provided below. It shows an example of how to use the function.
<?php
$mysqli = **new** mysqli("localhost", "root", "mysql", "sakila");
**if** (mysqli -> connect_errno) {
**die**("Error connecting to server" . $mysqli -> connect_error);
}
$query = "SELECT * FROM film WHERE rating > 8";
$result = $mysqli -> query($query);
$sql_array = $result -> fetch_array();
print_r($sql_array);
?>
The above script connects to the MySQL database using the mysql_connect()
function.
We then use the mysql_query()
method to perform a query to the database and select the rows where the rating is greater than 8 in the film table of the sakila database.
To get an array, we store the result from the mysql_query()
and pass that value tomysql_fetch_array()
.
Example 2
The following example shows how to use the MYSQL_NUM option to return a numerical array.
<?php
$mysqli = **new** mysqli("localhost", "root", "mysql", "sakila");
**if** (mysqli -> connect_errno) {
**die**("Error connecting to server" . $mysqli -> connect_error);
}
$query = "SELECT * FROM film WHERE rating > 8";
$result = $mysqli -> query($query);
**while** ($sql_array = fetch_array($result, MYSQL_NUM)) {
printf("id %s", $row[0], $row[1]);
}
mysql_free_result($result);
print_($sql_array);
?>
Other variations of the code are as:
<?php
$mysqli = **new** mysqli("localhost", "root", "mysql", "sakila");
**if** (mysqli -> connect_errno) {
**die**("Error connecting to server" . $mysqli -> connect_error);
}
$query = "SELECT * FROM film WHERE rating > 8";
$result = $mysqli -> query($query);
**while** ($sql_array = fetch_array($result, MYSQL_ASSOC)) {
printf("id %s" "name", $row["id"], $row["name"]);
}
mysql_free_result($result);
print_($sql_array);
?>
Conclusion
In this tutorial, we learned how to use the PHP mysql_fetch_array()
function to fetch the results of a row as an array.