PDO array Undefined offset Undefined index fetchAll(PDO::FETCH_ASSOC) fetch(PDO::FETCH_ASSOC)
When you use PDO, try to get
fetchAll(PDO::FETCH_ASSOC)
fetch(PDO::FETCH_ASSOC)
return is Array. This Array have rows, it’s mean :
array[0] = array[“field1”, “field2”, “field3”]
array[1] = array[“field1”, “field2”, “field3”]
……
array[10] = array[“field1”, “field2”, “field3”]
So get array index or row maybe not exist, when you try to get value, get error code.
You can try to make two function:
function ar_get($val, $ar){
return array_key_exists($val, $ar)?$ar[$val]:"";
}
function crud_ar_get($val, $ar, $rec_arrow=0){
return (isset($ar[$rec_arrow]))?ar_get($val, $ar[$rec_arrow]) : “";
}
Example 1:
ar_get for array get value
$prduct = array(“product_name”=>“a”, “product_price=>“100”);
ar_get(“product_name”, $product);
ar_get(“product_price”, $product);
If no index, just return "”
Example 2:
crud_ar_get for array get value
$prduct[0] = array(“product_name”=>“a”, “product_price=>“100”);
$prduct[1] = array(“product_name”=>“b”, “product_price=>“200”);
crud_ar_get(“product_name”, $product); // a
crud_ar_get(“product_price”, $product); // 100
crud_ar_get(“product_name”, $product, 1); // b
crud_ar_get(“product_price”, $product, 1); // 200
If no offset, just return "”
This way can avoid Warning Message. For small website.
BUT performace…… maybe no good..