Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Which PHP functions are used in the PHP script to fetch data from an existing MySQL table?
PHP provides several functions to fetch data from an existing MySQL table. The most commonly used functions are mysql_query() for executing SQL queries and mysql_fetch_array() for retrieving rows from the result set.
mysql_query() Function
This function executes an SQL query against a MySQL database and returns a result resource on success or FALSE on failure ?
Syntax
bool mysql_query( sql, connection );
Parameters
| Parameter | Description |
|---|---|
| sql | Required − SQL query to fetch data from an existing MySQL table |
| connection | Optional − MySQL connection resource. If not specified, the last opened connection by mysql_connect() will be used |
mysql_fetch_array() Function
This function retrieves a row from the result set and returns it as an associative array, numeric array, or both. It returns FALSE when there are no more rows ?
Syntax
mysql_fetch_array(result, resulttype);
Parameters
| Parameter | Description |
|---|---|
| result | Required − Result set identifier returned by mysql_query(), mysql_store_result() or mysql_use_result() |
| resulttype | Optional − Specifies array type: MYSQL_ASSOC (associative), MYSQL_NUM (numeric), or MYSQL_BOTH (both types) |
Example
Here's how to use these functions together to fetch data from a MySQL table ?
<?php
// Establish database connection
$connection = mysql_connect("localhost", "username", "password");
mysql_select_db("database_name", $connection);
// Execute SQL query
$query = "SELECT id, name, email FROM users";
$result = mysql_query($query, $connection);
// Fetch and display data
while($row = mysql_fetch_array($result)) {
echo "ID: " . $row['id'] . "<br>";
echo "Name: " . $row['name'] . "<br>";
echo "Email: " . $row['email'] . "<br><br>";
}
// Close connection
mysql_close($connection);
?>
Conclusion
Note: The mysql_* functions are deprecated as of PHP 5.5.0 and removed in PHP 7.0.0. Use MySQLi or PDO for new projects instead.
