foreach data while inside? - php

Good afternoon, everybody. I have a doubt.
I have a WHILE, and accurate list of the data within it FOREACH . Does anyone know how to do this?
I would be very grateful for the help.
Example code.
$UserIDS= array();
$query->execute();
while ($lista = $query->fetch()){
$mensagem = $lista['mensagem'];
$UserIDS[] = $lista['idUser'];
echo
'
//Data from Forech, was shown here.
<div class="avatar"></div>
<div class="text">
'.utf8_encode($mensagem).'
</div>
';
}
//FOREACH data has to list before the $message, if put into the forech WHILE not sure of the fact that I have an array inside.
foreach ($UserIDS as $idUsua) {
echo "<div class='avatar'>".box::avatar($idUsua)."</div>";
}
Anyone know how do I pull data from FOREACH and put inside the in WHILE? be very grateful for the help.

Referring to my earlier answer to your other question:
// fetch all the data in one go
$query->execute();
$data = $query->fetchAll();
// and then iterate it
foreach ($data as $lista) {
echo "<div id='avatar'>" . box::avatar($lista['idUser']) . "</div>";
echo "<div class='text'>" . utf8_encode($lista['mensagem']). "</div>";
}
Your existing box::avatar call is then still free (as before) to make separate PDO query calls.

why don't you take this part
foreach ($UserIDS as $idUsua) {
echo "<div class='avatar'>".box::avatar($idUsua)."</div>";
}
into a function like
function userId($UserIDS){
$userAvatarDivs="";
foreach ($UserIDS as $idUsua) {
$userAvatarDivs.= "<div class='avatar'>".box::avatar($idUsua)."</div>";
}
return $userAvatarDivs;
}
and call it on
while ($lista = $query->fetch()){
$mensagem = $lista['mensagem'];
$UserIDS[] = $lista['idUser'];
echo
'
//Data from Forech, was shown here.
<div class="avatar"></div>
<div class="text">
'.utf8_encode($mensagem).'
</div>
'.userId($UserIDS);
}

Related

Possible to reduce complexity of fetching and displaying data?

What I'm doing with the following code is fetching data from a table via PHP in order to display the data on a website.
$stri = "SELECT a, b, c, d, e, f FROM table";
$stat = $conn->prepare($stri);
if ($stat->execute()) {
while ($resu = $stat->fetch(PDO::FETCH_ASSOC)) {
foreach ($resu as $key=>$value) {
echo $value . "<br>";
}
echo "<br><br>";
}
}
However, it seems redundant to use two loops. Is there not a more efficient way to accomplish the same thing while allowing each item of each row to be handled independently?
I plan to do something like the following with it which is why I need to be able to handle the items independently.
if ($stat->execute()) {
while ($row = $stat->fetch(PDO::FETCH_ASSOC)) {
echo '<div class="row">';
foreach ($row as $key=>$value) {
echo '<div class=' .$key. '>';
if (empty($value)) echo '---<br>';
else echo $value;
echo '</div>';
}
echo '</div>';
}
}
However, it seems redundant to use two loops.
I cannot get what does it mean, but in all it's quite possible to reduce the complexity. For this you need to use PDO in the full force, not as a just a substitution for mysql_query(). A separation of concerns would also help
Get your data first in the form of array
$sql = "SELECT a, b, c, d, e, f FROM table";
$stmt = $conn->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll();
and then display it, somewhere inside the HTML part of the page
<?php foreach ($data as $row): ?>
<div class="row">
<?php foreach ($row as $key=>$value): ?>
<div class="<?=$key?>">
<?php if (!$value): ?>
---<br>
<?php else ?>
<?=$value?>
<?php endif ?>
</div>
<?php endforeach ?>
</div>
<?php endforeach ?>
function checking($val)
{
if(empty($val))
{
echo "---<br>";
}
else
{
echo $val;
}
}
$stri = "SELECT a, b, c, d, e, f FROM t";
try
{
$stat = $conn->prepare($stri);
$stat->execute();
$results = $stat->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $key=>$value)
{
echo implode('',array_map("checking",$value));
echo "<br><br>";
}
}
catch(Exception $e)
{
error_log($e->getMessage());
}
I do a little bit changed of your code. Instead of use if to catch error, I prefer to use try catch method.

Want to post multiple search results

I tried to make a search function, when your search a tag, its supposed to give you the images with that tag. When i just echo in the php code (line 101), it gives all the links. However, when i try to post it in the html, it only gives one result back.
php code
$postTags = "";
if (isset($_POST['Find'])) {
try {
$pdoConnect = new PDO("mysql:host=localhost;dbname=imdterest", "root", "");
} catch (Exception $exc) {
echo $exc->getMessage();
exit();
}
$postTags = $_POST['naam'];
$pdoQuery = "SELECT * FROM posts WHERE postTags = :tags";
$pdoResult = $pdoConnect->prepare($pdoQuery);
$pdoExec = $pdoResult->execute(array(":tags" => $postTags));
while ($row = $pdoResult->fetch(PDO::FETCH_ASSOC)) {
$postTags = $row['postImageUrl'];
//echo $postTags;
}
}
html code
<div class="search">
<img src="<?php echo $postTags; ?>">
</div>
the problem is that in your php code you have WHILE loop and you echo link for all found rows. That is why it prints all results. But also you don't store the values but overwrite it every while iteration. In your HTML you don't have while loop and you just print overwritten variable (probably last result).
You can either store the results in an array or move while loop to HTML location.
Storing into array:
$allResults = array();
while ($row = $pdoResult->fetch(PDO::FETCH_ASSOC)) {
$allResults[] = $row['postImageUrl'];
}
and then somewhere in your html code
<div class="search">
<?php
foreach ($allResults as $imageLink){
echo '<img src="' . $imageLink . '">";
}
?>
</div>
The variable $postTags is getting overwritten and will hold only last value of MySQL result set. Create an array and loop over it.
$postTags = array();
while ($row = $pdoResult->fetch(PDO::FETCH_ASSOC)) {
$postTags[] = $row['postImageUrl'];
}
In HTML:
foreach($postTags as $val)
{ ?>
<div class="search">
<img src="<?php echo $val; ?>">
</div>
<?php
} ?>
Change your while loop like this, As you are not using array next data will over write the previous and all you are left with one image link that is last image link. hence to prevent overriding use array.
$postTags=[];
while ($row = $pdoResult->fetch(PDO::FETCH_ASSOC)) {
$postTags[] = $row['postImageUrl'];
//echo $postTags;
}
And html code like this , As now you have multiple images you need to display all and for that you need to iterate and foreach is one method to iterate through array.
<?php
foreach ($postTags as $postTag) {
?>
<div class="search">
<img src="<?php echo $postTag; ?>">
</div>
<?php }?>

print variable above of the while loop (scope) php

is there is any way to define a variable under the while loop and print it above the while loop
something like this
print $catName
while ($b = mysqli_fetch_assoc($results)) {
$catName = $b['cat'];
}
EDIT
$getBooks = $db->prepare('SELECT
id, cat, instituteId, title, cover, authorName FROM books_library WHERE instituteId=? AND cat=?');
$getList = array();
$getBooks->bind_param('ii', $inId, $cid);
if ($getBooks->execute()) {
$libResults = $getBooks->get_result();
$getList[] = $libResults;
?>
HTML CODE COME HERE
<h3 class="marginBottom8px margin-top_30px text-bold text-danger"><?php echo catName ?></h3>
AND THEN THE WHILE LOOP
while ($book = mysqli_fetch_assoc($libResults)) {
$bokId = $book['id'];
$bookTitle = $bokId['title'];
$catName = $bokId['cat'];
$catName = $bokId['cat'];
now under the while loop I got the $catName How can I echo it above in the <h3></h3>
After the while block, put your h3 html in a variable and print it.
$myHtml = '<h3 class="marginBottom8px margin-top_30px text-bold text-danger">'
. $catName . '</h3>';
print $myHtml;
Don't mix html and php like that.
I think this is what you're after based on the edited question
while ($book = mysqli_fetch_assoc($libResults)) {
echo '<h3>' . $book['cat'] . '</h3>';
}

What is the quickest way to randomize a data set?

For a multiple choice quiz application i would like to show the dummy answers with the correct answer. But with the correct answer being in a different position at each different question.
This is what i've tried but it doesn't seem to be working:
if ($question->type == 1)
{
echo "<div id='dummy_answers'>";
//Show Dummy
echo '<h3>Dummy Answers</h3>';
//Get Dummy Answers
$query = $this->test_model->getDummyAnswers($question->id);
$dummy_num = 1;
foreach ($query->result() as $row)
{
$rand_number = rand(1, 3);
if ($dummy_num == $rand_number)
{
$dummy_num = $rand_number + 2;
echo '<h4>Answer '.$dummy_num.'</h4>';
echo '<p>';
echo $row->option;
echo '</p>';
//Now echo the real answer
echo '<h4>Answer '.$rand_number.'</h4>';
echo '<p>';
echo $row->option;
echo '</p>'; //Get id's for each.echo $row->id;
}
else
{
echo '<h4>Answer '.$dummy_num.'</h4>';
echo '<p>';
echo $row->option;
echo '</p>';
$dummy_num++;
}
}
echo '</div>';
echo ' <hr/>';
}
?>
You should use shuffle function.
In your case it will be:
if ($question->type == 1)
{
echo "<div id='dummy_answers'>";
//Show Dummy
echo '<h3>Dummy Answers</h3>';
//Get Dummy Answers
$query = $this->test_model->getDummyAnswers($question->id);
$answers=$query->result();
shuffle($answers);
foreach ($answers as $nr=>$row)
{
echo '<h4>Answer '.($nr+1).'</h4>';
echo '<p>';
echo $row->option;
echo '</p>';
}
echo '</div>';
echo ' <hr/>';
}
?>
Put the answers in an array the use shuffle
$random_array = shuffle($answers);
All you need to do is put the keys for your answers in an array and call shuffle(). Something like this:
$keys = array_keys($answers);
shuffle($keys);
for ($key in $keys) {
echo $answers[$key];
}
I would suggest putting all the answers into an array and using the shuffle() function to randomize them. Once they're shuffled, just iterate the array with a loop and build the markup.
You could put the results into an array (1 correct and 3 incorrect), then shuffle, then output them?
$answers = array();
array_push($answers, "answer1");
array_push($answers, "answer2");
array_push($answers, "answer3");
array_push($answers, "answer4");
shuffle($answers);
foreach ($answers as $answer) {
echo $answer;
}

PHP parse array to add css

I have the following code:
while($row = mysql_fetch_array($result)){
$output_items[] = $row["title"]; } // while
print(implode("\n", $output_items));
Which does what it says and splits the array with a new line for each item.
But how do I do the same and allow formatting with i.e. I basically want to say
foreach of the $output_items echo "<div class=whatever>$output_items</div> etc etc
Tearing my hair out with this!
Many thanks for all help
Darren
foreach ($output_items as $oi){
echo "<div class=whatever>$oi</div>";
}
doesn't work? or i did not get what you are searching for
Pretty simple, to make it easier to read I'd do something like this:
while($row = mysql_fetch_array($result))
{
echo '<div class="whatever">';
echo $row["title"];
echo '</div>' . "\n";
} // while
Although you could still do this with your original code pretty easily:
while($row = mysql_fetch_array($result)){
$output_items[] = '<div class="whatever">' . $row["title"] . '</div>'; } // while
print(implode("\n", $output_items));
Rather than implode() them all with line breaks, use string interpolation to add them together:
$out_string = "";
// Loop over your array $output_items and wrap each in <div />
// while appending each to a single output string.
foreach ($output_items as $item) {
$out_string .= "<div class='whatever'>$item</div>\n";
}
echo $out_string;

Categories