Current Location: Home> Latest Articles> How to Access and Manipulate Data Returned by the mysql_fetch_row Function? A Detailed Guide

How to Access and Manipulate Data Returned by the mysql_fetch_row Function? A Detailed Guide

gitbox 2025-09-23
<?php
// The following content is unrelated to the main text, just an introductory example
echo "This is an introductory example and is not related to the main content.";
?>
<hr>
<?php
// Main content begins
echo "<h1>How to Access and Manipulate Data Returned by the mysql_fetch_row Function? A Detailed Guide</h1>";
<p>echo "<p>In PHP, <code>mysql_fetch_row
";

echo "

In the example above, $row[0] corresponds to id, $row[1] corresponds to name, and $row[2] corresponds to email.

";

echo "

2. Traversing the Array to Access All Fields

";
echo "
<br>
$result = mysql_query('SELECT id, name, email FROM users');<br>
while ($row = mysql_fetch_row($result)) {<br>
foreach ($row as $value) {<br>
echo $value . ' ';<br>
}<br>
echo '<br>';<br>
}<br>
";

echo "

Using foreach, you can iterate through each value in a row without relying on index names. This method is useful when the number of fields is not fixed.

";

echo "

3. Storing Row Data in Another Array

";
echo "
<br>
$allData = [];<br>
$result = mysql_query('SELECT id, name, email FROM users');<br>
while ($row = mysql_fetch_row($result)) {<br>
$allData[] = $row; // Store each row as an element in $allData<br>
}</p>
<p>// Access the name in the second row<br>
echo $allData[1][1];<br>
";

echo "

4. Important Notes

";
echo "

  • mysql_fetch_row returns an indexed array. To access data by field name, consider using mysql_fetch_assoc.
  • mysql_* functions have been deprecated in PHP 7+; it's recommended to use mysqli or PDO.
  • Make sure the SQL query has been successfully executed before using mysql_fetch_row.
";

echo "

5. Example Using mysqli_fetch_row (Modern Method)

";
echo "
<br>
$conn = mysqli_connect('localhost', 'root', '', 'testdb');<br>
$result = mysqli_query($conn, 'SELECT id, name, email FROM users');<br>
while ($row = mysqli_fetch_row($result)) {<br>
echo 'ID: ' . $row[0] . ', Name: ' . $row[1] . ', Email: ' . $row[2] . '<br>';<br>
}<br>
mysqli_close($conn);<br>
";

echo "

Summary: mysql_fetch_row returns an indexed array, and you can access data using numeric indexes. This makes it easy to traverse and manipulate query results using loops. However, in modern PHP projects, it's recommended to use mysqli or PDO.

";

?>