0

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.

1
  • Since it is an object you need to return $row->name; And you do not need a loop here. Commented May 8, 2015 at 13:05

3 Answers 3

2

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();
Sign up to request clarification or add additional context in comments.

3 Comments

I am just asking to make sure.
:-) just checked with php.net/manual/en/pdostatement.bindparam.php lokks ok. If any particular suggestion you are welcome
Maybe Jay prefer: $query = $db->prepare("SELECT * FROM dog WHERE id = :id"); $query->bindParam(':id',$id);
0

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

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

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.