Skip to content
Advertisement

PHP Undefined offset: 0 error in server log. How to avoid it?

I am getting the title error in my Nginx server log. I have checked the many other similarly asked questions without success. The php script works as intended but the error keeps appearing everytime the page is hit.

Here’s the affected code:

$user_slug=$_GET['user-id'];
$where = array("user_url"=>$user_slug);
$user_info = $operation->select_record('*',$where,'tbl_users');
$user_name =   $user_info[0]['user_name'];  
$user_email =   $user_info[0]['user_email']; 
$user_text =   $user_info[0]['user_text'];

And the relevant function (select_record) is as follows:

function select_record($tblfld,$where,$table){
            $sql = "";
            $condition = "";
            foreach ($where as $key => $value) {
            $condition .= $key . "='" . $value . "' AND ";
            }
            $condition = substr($condition, 0, -5);
            $sql .= "SELECT ".$tblfld." FROM ".$table." WHERE ".$condition;
            $smt = $this->conn->prepare($sql);
            $smt->execute();
            return $smt->fetchAll();
            }

I’d greatly appreciate some help on this.

Advertisement

Answer

Check your result array before accessing..

$user_slug=$_GET['user-id'];
$where = array("user_url"=>$user_slug);
$user_info = $operation->select_record('*',$where,'tbl_users');
if (!empty($user_info)) {
   $user_name =   $user_info[0]['user_name'];  
   $user_email =   $user_info[0]['user_email']; 
   $user_text =   $user_info[0]['user_text'];
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement