user756659
user756659

Reputation: 3512

mysqli prepared - store results into array?

I want to optimize this section of code a bit to use an array such as $_SESSION['user']= $arr;.

// Store user db info in session for use
$stmt = $mysqli->prepare("SELECT id,user,pass,email,timezone,lastIP,currIP,dtLastLogin,dtCurrLogin FROM test_users WHERE user = ?");
// bind params
$stmt->bind_param('s', $user);
// execute prepared statement
$stmt->execute();
// Bind result variables
$stmt->bind_result($_SESSION['id'], $_SESSION['user'], $_SESSION['pass'], $_SESSION['email'], $_SESSION['timezone'], $_SESSION['lastIP'], $_SESSION['currIP'], $_SESSION['dtLastLogin'], $_SESSION['dtCurrLogin']); 
// fetch values
$stmt->fetch();     
// close statement
$stmt->close();

I tried using :

$rs = $stmt->get_result();
$arr = $rs->fetch_all(MYSQLI_ASSOC);
// close statement
$stmt->close();
//store array into session
$_SESSION['user']= $arr;

but I received a Call to undefined method mysqli_stmt::get_result(). I have php 5.3.8 and MySQL 5.1.70-cll running.

Upvotes: 3

Views: 650

Answers (1)

lonesomeday
lonesomeday

Reputation: 237895

mysqli_stmt::get_result is only available if you are running the MySQL native driver (mysqlnd).

This is documented in the manual page for the method.


To clarify:

There are three ways of accessing a MySQL database from PHP: the ancient mysql functions, the modern mysqli functions/class, and the PDO mysql extension.

All three of these interact with the database in the same way, using the library called libmysqlclient. Properly speaking, this is not part of PHP. It is a C library, which PHP uses.

In PHP 5.3, however, the mysqlnd driver was introduced. This is a native part of PHP (that's what the n stands for). In 5.3, it needs to be installed deliberately. From 5.4, it is the default way to access MySQL.

So to get it working, either install PHP 5.4 or compile PHP 5.3 with the options given in the installation page for mysqlnd.

In the meantime, your method is probably the best to get the data. The only other way would be to use PDO instead, which might offer a nicer syntax. This, for instance, would be possible:

$stmt = $dbh->prepare("SELECT id,user,pass,email,timezone,lastIP,currIP,dtLastLogin,dtCurrLogin FROM test_users WHERE user = :user");
$stmt->bindParam(':user', $user);
$stmt->execute();

$_SESSION['user'] = $stmt->fetch(PDO::FETCH_ASSOC);

Upvotes: 2

Related Questions