Skip to content

fetch_lengths

In this article, we will focus on the mysqli_fetch_lengths() function in PHP. It returns an array containing the lengths of each column in the current row of a MySQLi result set. We will provide an overview of how it works and show examples of its use.

Introduction to the mysqli_fetch_lengths() function

The mysqli_fetch_lengths() function is a built-in PHP function that returns an array of column lengths for the current row of a MySQLi result set. It is useful when you need to know the size of each column's data in the active row.

How to use the mysqli_fetch_lengths() function

Using the mysqli_fetch_lengths() function is straightforward. It operates on the current row pointer, so you typically call it inside a fetch loop (e.g., after mysqli_fetch_row()). Here is an example:

How to use the mysqli_fetch_lengths() function?

php
<?php
$mysqli = mysqli_connect("localhost", "username", "password", "database");

if (!$mysqli) {
    die("Connection failed: " . mysqli_connect_error());
}

$query = "SELECT * FROM my_table";
$result = mysqli_query($mysqli, $query);

if ($result) {
    while ($row = mysqli_fetch_row($result)) {
        $lengths = mysqli_fetch_lengths($result);
        if ($lengths !== false) {
            for ($i = 0; $i < count($lengths); $i++) {
                printf("Length of column %d: %d\n", $i, $lengths[$i]);
            }
        }
    }
}

mysqli_close($mysqli);
?>

In this example, we connect to the database and execute a query. We check if the connection and query succeeded. Inside the while loop, mysqli_fetch_row() advances the row pointer. We then call mysqli_fetch_lengths() to get an array of column lengths for that specific row. The function returns false on failure, so we verify the result before looping through the lengths with a for loop to print them.

Conclusion

The mysqli_fetch_lengths() function is a practical tool for retrieving column sizes in the current row of a MySQLi result set. Understanding its row-pointer behavior and return values helps you integrate it reliably into your database workflows.

Practice

What does the mysqli_fetch_lengths function do in PHP?

Dual-run preview — compare with live Symfony routes.