MySQLi Tutorial MySQLi References

mysqli_result $lengths Property



The mysqli_result::$lengths / mysqli_fetch_lengths() function returns an array containing the lengths of every column of the current row within the result set.

Syntax

//Object-oriented style
$mysqli_result->lengths;

//Procedural style
mysqli_fetch_lengths(result)

Parameters

result Required. For procedural style only: Specify a mysqli_result object returned by mysqli_query(), mysqli_store_result(), mysqli_use_result() or mysqli_stmt_get_result().

Return Value

Returns an array of integers representing the size of each column (not including any terminating null characters). false if an error occurred.

mysqli_fetch_lengths() is valid only for the current row of the result set. It returns false if it is called before calling mysqli_fetch_row/array/object or after retrieving all rows in the result.

Example: Object-oriented style

The example below shows the usage of mysqli_result::$lengths property.

<?php
//establishing connection to the database
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
  echo "Failed to connect to MySQL: ". $mysqli->connect_error;
  exit();
}

//getting query result from the database
$sql = "SELECT EmpId, Name, Age FROM Employee ORDER BY Age";

if ($result = $mysqli->query($sql)) {

  //fetching one row of data from the result set
  $row = $result->fetch_row();

  //displaying column lengths
  foreach ($result->lengths as $i => $val) {
    printf("Field %2d has Length %2d\n", $i+1, $val);
  }

  //free the memory associated with the result
  $result->close();
}

//closing the connection
$mysqli->close();
?>

The output of the above code will be similar to:

Field 1 has Length 4
Field 2 has Length 12
Field 3 has Length 3

Example: Procedural style

The example below shows the usage of mysqli_fetch_lengths() function.

<?php
//establishing connection to the database
$mysqli = mysqli_connect("localhost", "user", "password", "database");
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: ". mysqli_connect_error();
  exit();
}

//getting query result from the database
$sql = "SELECT EmpId, Name, Age FROM Employee ORDER BY Age";

if ($result = mysqli_query($mysqli, $sql)) {

  //fetching one row of data from the result set
  $row = mysqli_fetch_row($result);

  //displaying column lengths
  foreach (mysqli_fetch_lengths($result) as $i => $val) {
    printf("Field %2d has Length %2d\n", $i+1, $val);
  }

  //free the memory associated with the result
  mysqli_free_result($result);
}

//closing the connection
mysqli_close($mysqli);
?>

The output of the above code will be similar to:

Field 1 has Length 4
Field 2 has Length 12
Field 3 has Length 3

❮ MySQLi Functions Reference