View Full Version : Resolved Using Fetch on the same query multiple times

07-14-2012, 10:04 AM
I'm working on writing a basic PHP book, and I'm trying to code an example that will run different types of MySQLi fetch functions on the same query. The issue is the query is only giving the results to the first fetch function. Is there any way to give the results to all the fetch functions without duplicating the query before each individual fetch function? If I duplicate the query before each fetch function all works fine, I just don't want to have everybody type the same query over and over again; there's gotta be a better way.

require 'db_connect.php';

$query_result=mysqli_query($db, "SELECT `username`, `password` FROM `users`
WHERE `username`='Vega'");
$fetch_numeric_array_alternate=mysqli_fetch_array($query_result, MYSQLI_NUM);
$fetch_associative_array_alternate=mysqli_fetch_array($query_result, MYSQLI_ASSOC);
$fetch_array=mysqli_fetch_array($query_result, MYSQLI_BOTH);

echo "<p>Associative Array </p>
<p>Your Username is: {$fetch_associative_array['username']}</p>
<p>Your hashed password is: {$fetch_associative_array['password']}</p>";

echo "<p>Numeric Array </p>
<p>Your Username is: {$fetch_numeric_array[0]}</p>
<p>Your hashed password is: {$fetch_numeric_array[1]}</p>";

echo "<p>Alternative Numeric Array </p>
<p>Your Username is: {$fetch_numeric_array_alternate[0]}</p>
<p>Your hashed password is: {$fetch_numeric_array_alternate[1]}</p>";

echo "<p>Alternative Associative Array </p>
<p>Your Username is: {$fetch_associative_array_alternate['username']}</p>
<p>Your hashed password is: {$fetch_associative_array_alternate['password']}</p>";

echo "<p>Associative/Numeric Array </p>
<p>Your Username is: {$fetch_array['username']} - Using Associative</p>
<p>Your hashed password is: {$fetch_array[1]} - Using Numeric </p>

07-14-2012, 05:33 PM
All you have to do is rewind it. In MySQLi you would issue:

mysqli_data_seek($query_result, 0);
// or, for OO:

Then you can issue a fetch again.
Obviously with this type of handling this would be infeasible (except in a learning situation like above). All you'd need to use is the mysql_fetch_array with the default or MYSQLI_BOTH to fetch the same data you need and cover for every case scenario.

07-14-2012, 08:35 PM
Thanks, that will definitely do it.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum