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?
1 Answer 1
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
}
-
Its a very bad idea to use the object manager and it should be avoided. So i would not recommend this solutions as you will encounter issues in the future.Petar Borisovski– Petar Borisovski2020年10月02日 14:26:39 +00:00Commented Oct 2, 2020 at 14:26
-
The answer is very clear that it is limiting the response to using the existing code in the question and giving the minimum necessary changes. This includes the object manager. But while you are technically correct the object manager should not be used in this way, the solution focus' on sanity checking all unknown information before use.Mark Rees– Mark Rees2020年10月02日 16:29:31 +00:00Commented Oct 2, 2020 at 16:29