Using same mysql connection for multiple times

Consider that I have these codes for connection:
In database.php:


$server_name = 'localhost';

$user_name = 'root';

$password = '';

$db_name = 'gallery';

$image_table_name = 'images';

$information_table_name = 'info';

$connection = new mysqli($server_name, $user_name, $password, $db_name);



    die("Connection to database failed".$connection->connect_error);



in index.php:

ini_set('display_errors', TRUE);
require "../app/core/database.php";
$sql = "SELECT * FROM info limit 1";
$result = $connection->query($sql);

I want to use While() loop between html codes more than once. The first loop works fine but next loops doesn’t work. There is no error.
For example I write:

<?php while($row = $result->fetch_assoc()) { ?>
html codes.......<?php $row['image_text'] ?>
<?php } ?>

and in other part of the code I use again:

<?php while($row = $result->fetch_assoc()) { ?>
html codes.......<?php $row['info'] ?>
<?php } ?>

Is there any way to use same query multiple times to access different columns?
I tested <?php Unset($result) ?> but it does not work.

While’s keep an index of the current pointer into the results. It is changed each time you loop thru it.
Therefore, it can only be used once that way. Instead of using ASSOC versions, you could uses indexing into the full set of records, but, that is not a good way. If you need more than one WHILE, just rerun the query a second time.

A better way would be to create the HTML code as a string using just ONE WHILE loop. Then, just echo the strings where it is needed in the page. HTML is just text, therefore you can store it into a string with ease and place where needed on the page.

Hope this helps…

I found a solution. The first loop consumes all data from mysql already, so there is nothing left in the second loop. I can store the rows data in the meanwhile however and then re-use that store.

<?php while ($row = $result2->fetch_assoc()) { $rows[] = $row ?>

and next time:

<?php foreach($rows as $row) { ?>

Well, extra work, I mean, storing the data uses a lot of resources. Just running the query a second time would be less work. Your choice!

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service