0

I am using mySQL. Not matter what syntax I use, I can not fetch the results of my query.

Connecting to the database works just fine. Then I create a PDO, which also works just fine.

But when I try to query the database, no matter what I do I get all kinds of errors. (See specifics in the comments.) I know that my results returned fine, because when I var_dump them I see the array and it has data.

//***********************************************
// Try to retrieve list of states
//**********************************************
try {
  $result = $db->query('SELECT * FROM state');

  echo '<pre> Test 1';
  //$test1 = $result->fetch_array(MYSQLI_NUM);    
  //gives error: undefined method 'fetch_array()''

  echo 'Test 2';
  //$test2 = $result->fetch(PDO::FETCH_ALL);        
  //gives error: Undefined class constant 'FETCH_ALL'

  echo 'Test 3';
  // $test3 = $result->fetch_all();                  
  //gives error: undefined method 'fetch_all()'

  echo 'Test 4';
  //$test4 = $mysqli->fetch_all();                 
  //gives error: undefined method 'fetch_all()'

  echo 'Test 5';
  $test5 = $result->fetch_assoc();                
  //gives error: undefined method 'fetch_assoc()'

  echo '</pre>';
} catch(Exception $e) {
  echo $e->getMessage();
  die();
}

Am I way off here? Some things I've read on this forum indicate problems with the version of php, but I just downloaded the latest this week. Am running version 5.6.12.


OK - new information


IF I run the following code, it works perfectly:

$sql = $db->prepare('SELECT * FROM state');
$sql->execute();
$result = $sql->fetchAll(PDO::FETCH_ASSOC);

So my takeaway is that with mySQL I always have to use the prepare() and execute() methods, that the query() method is not enough. Is that true?

I also don't see how this is a duplicate of "Can I mix MySQL API's in PHP?" That's a question about connections and mine is about getting the results from a query.

B. Krafft
  • 147
  • 1
  • 13
  • 1
    `MYSQLI_NUM` that isn't PDO nor this `fetch_all` nor `fetch_assoc` – Funk Forty Niner Sep 17 '15 at 16:08
  • 1
    I suggest you look at the PHP docs for mysqli and PDO. It appears you are mixing the two. – ductiletoaster Sep 17 '15 at 16:27
  • You can definitely use `query()`. You were using undefined methods and an undefined class constant, which is why the question was closed as a duplicate about mixing APIs. But now you're using `fetchAll(PDO::FETCH_ASSOC)`. See "query vs execute" [here](http://stackoverflow.com/questions/4700623/pdos-query-vs-execute) and [here](http://stackoverflow.com/questions/9233256/pdoquery-vs-pdostatementexecute-php-and-mysql) as well as the php.net examples of [query](http://php.net/manual/en/pdo.query.php#example-998) and [execute](http://php.net/manual/en/pdostatement.execute.php#example-1015). – showdev Sep 18 '15 at 21:09

0 Answers0