Question

I am trying to test magento 2.4 with PHP7.4.

I have a custom module with this code:

//checking for absolute weight
$res = $this->_objectManager->get('Magento\Framework\App\ResourceConnection');
$con = $res->getConnection('read');
$row = $con->fetchRow("select `absolute_weight`, `absolute_sku`, `sku_order` from {$res->getTableName('dynamicproductoptions_options')} where `product_id`={$product->getId()} and (`store_id`={$product->getStoreId()} or `store_id`=0) order by `store_id` desc");
$isAbsoluteWeight = (int) $row['absolute_weight'];
$isAbsoluteSku = (int) $row['absolute_sku'];

But this line:

$isAbsoluteWeight = (int) $row['absolute_weight'];

return error when I try to add a product in cart:

Notice: Trying to access array offset on value of type bool in my file.php

How can I fix it the right way please?

Was it helpful?

Solution

Notice: Trying to access array offset on value of type bool in my file.php

This means $row is false, your query returned no results. You need to at least add in if statements for the case where the query returns no results. More accurately you need to check if these array offsets exist when using them. An Example based on your code:

//checking for absolute weight
$res = $this->_objectManager->get('Magento\Framework\App\ResourceConnection');
$con = $res->getConnection('read');
$row = $con->fetchRow("select `absolute_weight`, `absolute_sku`, `sku_order` from {$res->getTableName('dynamicproductoptions_options')} where `product_id`={$product->getId()} and (`store_id`={$product->getStoreId()} or `store_id`=0) order by `store_id` desc");
$isAbsoluteWeight = null;
$isAbsoluteSku = null;
if (!empty($row)) {
    $isAbsoluteWeight = !empty($row['absolute_weight']) ? (int) $row['absolute_weight'] : false;
    $isAbsoluteSku = !empty($row['absolute_sku']) ? (int) $row['absolute_sku'] : false;
}

Then what you attempt to process those values you need to add the conditionals necessary to prevent the errors.

if ($isAbsoluteWeight && $isAbsoluteSku) {
    //Do stuff
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top