Karina Sakurai
Karina Sakurai

Reputation: 31

Select data using PDO and a PHP function

When I try to select one nome from my bd it doesn't show anything

That's the function to select a name:

public function searchName(){
    $db = new Conection();
    $query = $db->prepare("SELECT * FROM dog WHERE id = 1");
    $query->execute();
    $result = $query->fetchAll(PDO::FETCH_OBJ);
    foreach($result as $row)
    {
        return $row['name'];//return to getName

    }
}

here is the code from getName:

    require 'Conection.php';
    require 'model/Dog.php';

    $dog = new Dog;
    $res = $dog->searchName(1);

    echo $res;

The class Connection is ok.

Upvotes: 0

Views: 753

Answers (3)

Nishant Solanki
Nishant Solanki

Reputation: 2128

there is some problem in your code, you are not using function arguments after passing it and here are just want one row to return than you should use $query->fetch not $query->fetchAll

your code should be like this

public function searchName($id){
    $db = new Conection();
    $query = $db->prepare("SELECT * FROM dog WHERE id = :id");
    $query->execute(array('id'=>$id)); // bind parameters for security
    $result = $query->fetch(PDO::FETCH_ASSOC);     // updated object with assoc... ie if obj used than return $result->name   
    return $result['name'];            
}

and than

echo $res = $dog->searchName(1);

Upvotes: 0

balslev
balslev

Reputation: 361

PDO::FETCH_ASSOC is $row['name']
but
PDO::FETCH_OBJ is $row->name

http://php.net/manual/en/pdostatement.fetch.php

Upvotes: 0

Alex
Alex

Reputation: 17289

Since you use PDO::FETCH_OBJ you should:

return $row->name;

And since you call:

$res = $dog->searchName(1);

Your function declaration must be:

public function searchName($id){
    $db = new Conection();
    $query = $db->prepare("SELECT * FROM dog WHERE id = ?");
    $query->bindParam(1,$id);
    $query->execute();

Upvotes: 2

Related Questions