Current Location: Home> Latest Articles> Add type casting mechanism to result set data

Add type casting mechanism to result set data

M66 2025-06-02

When using MySQL databases, PHP provides a powerful mysqli extension to interact with the database. A common operation is to use mysqli_query() to execute a query and get the results. Typically, the result set of a query is accessed through the mysqli_result object. When processing result sets, you may encounter different types of data, such as numbers, strings, dates, etc. To avoid data type errors, we may need to add a type casting mechanism when fetching the data.

This article will introduce how to add a type cast mechanism to the result set of the mysqli_result function to ensure that each field is processed according to the expected data type.

1. Get the mysqli_result result set

First, let’s review how to use the mysqli_query() function to execute SQL queries and obtain the mysqli_result object.

 <?php
// Create a database connection
$mysqli = new mysqli('localhost', 'username', 'password', 'database_name');

// Check if the connection is successful
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Execute a query and get the result set
$query = "SELECT id, name, price, created_at FROM products";
$result = $mysqli->query($query);

// Check whether the query is successful
if ($result) {
    // Process query results
    while ($row = $result->fetch_assoc()) {
        // Process each row of data
    }
} else {
    echo "Query failed: " . $mysqli->error;
}

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

In this example, we execute an SQL query through the mysqli_query() function and return a mysqli_result object. Next, we will operate on the object and read the data in it.

2. Add type cast

The fetch_assoc() function of mysqli_result returns data as a string by default, even if the actual type of the field may be an integer or a floating number. This requires us to manually perform type casting when processing query results to ensure that the data meets the expected type.

2.1 Casting to integer

If a field is of an integer type, we can convert it to an integer by (int) casting:

 <?php
while ($row = $result->fetch_assoc()) {
    $id = (int) $row['id'];  // Cast to integer
    echo "Product ID: " . $id . "<br>";
}
?>

2.2 Cases to floating numbers

If a field is a floating numeric type, we can convert it to a floating type by (float) or (double) cast:

 <?php
while ($row = $result->fetch_assoc()) {
    $price = (float) $row['price'];  // Cast to floating number
    echo "Product Price: " . $price . "<br>";
}
?>

2.3 Casting to Boolean type

For boolean fields, we can convert it to true or false :

 <?php
while ($row = $result->fetch_assoc()) {
    $is_active = (bool) $row['is_active'];  // Cast to Boolean type
    echo "Product Active: " . ($is_active ? 'Yes' : 'No') . "<br>";
}
?>

2.4 Casting to date type

If a field is of date type, we can convert it to a date object using the DateTime::createFromFormat() method, or directly use strtotime() to convert it to a timestamp:

 <?php
while ($row = $result->fetch_assoc()) {
    $created_at = strtotime($row['created_at']);  // Convert to timestamp
    echo "Created At: " . date('Y-m-d H:i:s', $created_at) . "<br>";
}
?>

3. Use custom functions for batch conversion

If you have multiple fields that need to be typed, you can encapsulate a custom function and batch process type conversion. This can improve the maintainability and reusability of the code.

 <?php
function convert_types($row) {
    $row['id'] = (int) $row['id'];
    $row['price'] = (float) $row['price'];
    $row['is_active'] = (bool) $row['is_active'];
    $row['created_at'] = strtotime($row['created_at']); // Convert to timestamp

    return $row;
}

while ($row = $result->fetch_assoc()) {
    $row = convert_types($row);
    echo "Product ID: " . $row['id'] . "<br>";
    echo "Product Price: " . $row['price'] . "<br>";
    echo "Product Active: " . ($row['is_active'] ? 'Yes' : 'No') . "<br>";
    echo "Created At: " . date('Y-m-d H:i:s', $row['created_at']) . "<br>";
}
?>

In this example, the convert_types() function converts the data of each row into the expected type, and then displays or other operations can be easily performed.

4. Summary

By adding a type cast mechanism to the mysqli_result result set, we can better control the type of data and avoid errors caused by type mismatch. Whether converting data to integers, floating numbers, booleans, or date types, casting ensures the correctness and consistency of data. By encapsulating the conversion function, the code can also be made more concise and maintainable.

Hope this article will be helpful to you when processing MySQL query results!