Error Notice: Undefined offset: 0 when getting PHP PDO data


By using the following function I get that error, the function is used to verify whether or not there is a string in DB , if it does not remove that error, but if it does not exist I get the error


"Notice: Undefined offset: 0"

I have already verified the code, the connection to the DB and everything is correct. This function I had previously used on another page, and it worked properly for me, but now that I have moved on to another project, it does not work for me and I made sure everything was well written.


function selectUser($username){
      $con = connect();
      $query = "SELECT * FROM accounts WHERE user = :user";
      $stmt = $con->prepare($query);
      ':user' => $username
      $result = $stmt->fetchAll(); 
        return $result;
        $con = null;
    }catch (PDOException $e) {
        return 'Connection Failed: ' . $e->getMessage();

asked by Astaroth 01.03.2018 в 21:56

1 answer


The code of the function is fine.

The problem

The problem is in the handling that you do of the result obtained a posteriori.

$s = selectUser("d"); 
echo $s[0]["user"]; 

When there are no results, fetchAll returns an empty array, therefore, you can not access $[0] in that case, since the empty array that is returning fetchAll does not have an index 0 , hence the News:

Notice: Undefined offset: 0

The solution

You can check the non-nullity of $s before working with the data.

Something like this:

$s = selectUser("d"); 

if ($s){
    echo $s[0]["user"]; 
    echo "No se encontraron datos"; 

If you want to read all the rows obtained, you can modify the code like this:

$s = selectUser("d"); 

if ($s){
    foreach ($s as $row){
        //$strHTML.=" - ". $row["otra-columna-del-select"];
        $strHTML.=PHP_EOL; //Esto es un salto de línea
    echo $strHTML;
    echo "No se encontraron datos"; 

What I have done has been basically:

  • Create a variable called $strHTML to which to concatenate the results of the different rows (it can be done differently, I like to write clean code).
  • Open a for cycle that traverses the variable $s , and take it out of it the different values of each column and each row. In $row["..."] you have to put the column name (as they are called in the table) of each value you want.
  • At the end of each cycle add the constant PHP_EOL (line break) to the chain of concatenation.
  • Out of the loop I print all the result obtained in $strHTML .

It will be something like this:

Usuario X  -  otro valor de otra columna ...
Usuario Y  -  otro valor de otra columna ...
Usuario Z  -  otro valor de otra columna ...

In this way you can create a table, fill out a form with the values, etc, etc, etc.

I hope it serves you.

answered by 01.03.2018 / 22:23