0

I know this is insanely easy, but I'm a noob and not sure what I'm doing wrong here:

1: $mysqli = new mysqli('test', 'test', 'test', 'test');
2: if ($stmt = $mysqli->prepare($query)) {
3:     if (!$stmt->execute()) {
4:        $out .= "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
5:    }
6:    $out = $stmt->fetch_array();
7: } else {
8:   $out .= $mysqli->error;
9: }

I get a Fatal error: Call to undefined method mysqli_stmt::fetch_array() error on line 6.

2
  • 1
    So where are you defining $query? Commented Oct 21, 2012 at 22:30
  • MySQLi statements don't have a fetch_array(). There's a fetch() method, which you may call after you have bound out variables with bind_result() Commented Oct 21, 2012 at 22:33

2 Answers 2

2

You can use mysqli_stmt::get_result() if you have PHP 5.3 or greater, then use mysql_result::fetch_array():

$mysqli = new mysqli('test', 'test', 'test', 'test');
if ($stmt = $mysqli->prepare($query)) {
    if (!$stmt->execute()) {
        $out .= "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }
    $res = $stmt->get_result();
    while ($out = $res->fetch_array()) {
    }
else {
    $out .= $mysqli->error;
}

Also, you may want to check out all of the MySQL-Improved documentation.

You can also fetch all rows at once with mysqli_result::fetch_all().

Sign up to request clarification or add additional context in comments.

9 Comments

Just to note, get_result() is PHP 5.3+ only, as it depends on the mysqlnd driver...
It's probably worthwhile to include a link to the php manual for this: php.net/manual/en/mysqli-stmt.get-result.php and to note that he will likely want to tie the mysqli_stmt::get_result call in with a call to mysqli_fetch_array
Ok, this looks a lot easier than I was expecting. Will this handle multi-dimentional arrays?
@TravisHeeter I'm not sure I understand what you mean. Why don't you try doing a print_r($out); using both fetch_array() and fetch_all() to see what kinds of arrays are returned.
@Geoff_Montee I will try that. I added your code, and I'm now getting this error: Fatal error: Call to a member function get_result() on a non-object
|
0

Ok, after regrouping and trying completely different code (because fetch just wasn't working, no idea why) I was able to complete my query function using this:

function run_query($query)
{    
  $out = '';
  $db = new PDO("mysql:host=test;dbname=test","test","test");
  $out = $db->query("$query")->fetchAll(PDO::FETCH_OBJ);
  return $out;
}

Thanks to all for your help.

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.