<?php
// Example PHP code unrelated to the article content
echo "Welcome to my PHP tutorial page!";
<?>
<p><hr></p>
<p><?php<br>
/*<br>
Title: How to Extract Column Information from Database Query Results Using mysqli_result::fetch_fields?<br>
*/</p>
<p>// When working with MySQL databases in PHP, it's often necessary to retrieve column information from query results, such as column names, data types, and lengths. The mysqli fetch_fields method provides a convenient way to extract this information.</p>
<p>// 1. Connect to the database<br>
$servername = "localhost";<br>
$username = "root";<br>
$password = "";<br>
$database = "test_db";</p>
<p>$mysqli = new mysqli($servername, $username, $password, $database);</p>
<p>if ($mysqli->connect_error) {<br>
die("Connection failed: " . $mysqli->connect_error);<br>
}</p>
<p>// 2. Execute query<br>
$sql = "SELECT id, name, email FROM users";<br>
$result = $mysqli->query($sql);</p>
<p>if ($result) {<br>
// 3. Extract column information using fetch_fields<br>
$fields = $result->fetch_fields();</p>
echo "<ul>";
foreach ($fields as $field) {
echo "<li>";
echo "Column Name: " . $field->name . "<br>";
echo "Table Name: " . $field->table . "<br>";
echo "Data Type: " . $field->type . "<br>";
echo "Length: " . $field->length . "<br>";
echo "Maximum Length: " . $field->max_length . "<br>";
echo "</li><br>";
}
echo "</ul>";
// 4. Iterate through the result set
echo "<h2>Query Result Data:</h2>";
while ($row = $result->fetch_assoc()) {
</span>echo "ID: " . $row['id'] . ", Name: " . $row['name'] . ", Email: " . $row['email'] . "<br>";
}
$result->free</span>();
</span>
} else {
echo "Query failed: " . $mysqli->error;
}
$mysqli->close();
/*
Summary:
mysqli_result::fetch_fields() returns an array containing all column information.
Each array element is an object with properties like name, table, type, length, etc.
This is useful for dynamically generating tables, exporting data, or debugging database structures.
*/
>
Related Tags:
mysqli_result