简体   繁体   中英

mySQLi query to put results in an array and different DIVs

I want to query the content of multiple (6 in total, IDs 1 to 6) IDs from a mySQL database using mySQLi. After that I want to put the result ("introtext") in different DIVs. At the moment I use the following code (works perfect):

<?php
$q = $db->query("SELECT introtext FROM content WHERE id=1");
$r = $q->fetch_object();
?>
<div id="content1" class="toggle"><?php echo "$r->introtext";?></div>

<?php
$q = $db->query("SELECT introtext FROM content WHERE id=2");
$r = $q->fetch_object();
?>
<div id="content2" class="toggle"><?php echo "$r->introtext";?></div>

<?php
$q = $db->query("SELECT introtext FROM content WHERE id=3");
$r = $q->fetch_object();
?>
<div id="content3" class="toggle"><?php echo "$r->introtext";?></div>

And so on...

How can I optimize this code to query mySQL only once (put the results in array) and assign the different results into the different DIVs?

Cheers Shredder

Good question
Basically you will need 2 loops
one to get your array with data:

<?php
$data = array();
$res = $db->query("SELECT id, introtext FROM content ORDER BY id LIMIT 6");
while($row = $res->fetch_assoc()) {
    $data[$row['id']] = $row['introtext'];
}
?>

You can use whatever SQL to filter out your queries. ORDER BY id LIMIT 6 seems most convenient for the present case "get first 6 ids", as consecutiveness is never guaranteed.

And then another loop to display

<? foreach ($data as $id => $introtext): ?>
<div id="content<?=$id?>" class="toggle"><?=htmlspecialchars($introtext?)></div>
<? endforeach ?>

By the way, if use not raw Mysqli API but some helper library the PHP part will be reduced to one line:

<?php
$data = $db->getIndCol("id","SELECT id, introtext FROM content ORDER BY id LIMIT 6");
?>

Why don't you use IN mysql operator?

SELECT introtext FROM content WHERE id IN (1,2,3,4,5,6);

Then fetch results in object/array .

If the project is not huge i can suggest to give a try to RedBean ORM solution. To see how it works go here Is very simple and it requires nothing else than include the rb.php file in your project!

By the way if you still want to use mysqli manually the solution is to make a new WHERE in your query with id >= 1 and id <= 6 and then use the php reference to extract the result to an array... mysqli quickstart guide

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM