Search code examples
phparraysforeachvar-dump

I can't find out this extra line in array


I don't know what's that mean in my array.

my code is

   try {

  $conn=new PDO("mysql:host=localhost;dbname=moviesite","root","");
  $conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

  $stmt=$conn->prepare("SELECT movie_name,movie_year,movie_type,movie_leadactor,movie_director
                          FROM movie
                            ORDER BY movie_name,movie_year");
  $stmt->execute();
  $result=$stmt->fetchAll();
  foreach ($result as  $row) {
    var_dump($row);
  }
} catch (PDOException $e) {
echo $e->getmessage();
}


**And my result**

enter image description here

My Problem is

0 => string 'Bruce Almighty' (length=14)
1 => string '2003' (length=4)
.
.
.

I just request for movie_name, movie_year, movie_type, movie_leadactor, movie_director

but it show me extra line like 0 => string 'Bruce Almighty' (length=14)


Solution

  • The first parameter of fetchAll() is fetch_style which

    Controls the contents of the returned array as documented in PDOStatement::fetch(). Defaults to value of PDO::ATTR_DEFAULT_FETCH_MODE (which defaults to PDO::FETCH_BOTH)

    That's why when you var_dump($row);, you got both numeric and associative format data in your array.You just need to set $stmt->setFetchMode(PDO::FETCH_ASSOC);before your $stmt->execute(); Or use $result = $stmt->fetchAll(PDO::FETCH_ASSOC) for associative index.

    try {
    
      $conn = new PDO("mysql:host=localhost;dbname=moviesite","root","");
      $conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    
      $stmt = $conn->prepare("SELECT movie_name,movie_year,movie_type,movie_leadactor,movie_director
                              FROM movie
                                ORDER BY movie_name,movie_year");
       //ADD BELOW LINE
      $stmt->setFetchMode(PDO::FETCH_ASSOC);
      $stmt->execute();
    
      //OR REPLACE BELOW LINE LIKE $result=$stmt->fetchAll(PDO::FETCH_ASSOC);
      $result = $stmt->fetchAll(); 
      foreach ($result as  $row) {
        var_dump($row);
      }
    } catch (PDOException $e) {
    echo $e->getmessage();
    }