How to echo multiple images using an Array - php

Using this code:
<?php
$stmt = $pdo->prepare("SELECT pdimg1 FROM products WHERE pdcat LIKE 'fashion%'");
$stmt->execute();
$rows = $stmt->fetchAll();
$img1 = '';
foreach ($rows as $row) {
$Rpdimg1 = $row['pdimg1'];
$img1 .= $Rpdimg1;
}
UPDATED TO INCLUDE BELOW:
$stmt = $pdo->prepare("SELECT * FROM products WHERE pdcat LIKE 'collectibles%'");
$stmt->execute();
$rows = $stmt->fetchAll();
$img2 = '';
foreach ($rows as $row) {
$Rpdimg2 = htmlspecialchars($row['pdimg1']);
$img2 .= $Rpdimg2;
}
$cats = array(
array(
"title" => "FASHION",
"img" => $img1
),
array(
"title" => "COLLECTIBLES & ART",
"img" => $img2,
)
);
foreach ($cats as $cat): ?>
<?php echo $cat["title"]; ?>
<img src="images/<?php echo $cat["img"]; ?>">
<?php endforeach; ?>
I get this result displayed in Inspector Tools on Firefox:
<img src="images/shirt.jpgpants.jpg">
[But on the webpage, this displays as a broken image.]
But what I want is this result:
<img src="images/shirt.jpg">
<img src="images/pants.jpg">
[However, I would like the above results displayed as IMAGES, not as html text.]
Those two images are values echoed from my database. They are from my products table:
pdid | pdimg1
-----------------
1 | shirt.jpg
2 | pants.jpg
So basically
1) I'm selecting rows from my database table products
2) I'm inserting them as variables into an array (which is used for other purposes)
3) I'm using a foreach loop to echo out those variables from that array
4) Now the problem lies in that those IMAGE variables bunch together as a SINGLE WORD (shirt.jpgpants.jpg) instead of as separated values, and do not get encased in their OWN img tags, but are bunched together under the same img tag.
5) So I demonstrated above in bold text the result that I wanted. How would I achieve this? Thank you

Use an extra multidimensional array variable. like this
<?php
$int_data = array();
foreach ($rows as $row) {
$int_data[] = array(
"title" => $row['title'];
"image" => $row['pdimg1'];
);
}
?>
Now display the title and image using foreach loop
<?php
foreach ($int_data as $data) { ?>
Title : <?php echo $data['title]; ?> <br/>
Image : <img src="path/<?php echo $data['image]; ?>"> <br/>
<?php
} ?>

you need to do array assignment inside loop, and bit reduced code like below:
<?php
$stmt = $pdo->prepare("SELECT pdimg1 FROM products WHERE pdcat LIKE 'fashion%'");
$stmt->execute();
$rows = $stmt->fetchAll();
$cats = array();
foreach ($rows as $row) {
$cats[] = array(
"title" => $row['title'];
"img" => $row['pdimg1'];
); // you can add as many column as you get from query
}
foreach ($cats as $cat): ?>
<?php echo $cat["title"]; ?>
<img src="images/<?php echo $cat["img"]; ?>">
<?php endforeach; ?>

<?php
$stmt = $pdo->prepare("SELECT pdimg1 FROM products WHERE pdcat LIKE 'fashion%'");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) { ?>
<img src="images/<?= $row['pdimg1']; ?>">
<?php } ?>

Related

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 }?>

How to append count to variables in php

I am just starting to learn PHP and to compound the issue I am trying to modify existing code to match what I am attempting to do. I have multiple variables I am trying to define all while partially using a counter. My problem is appending the count to my individually defined variables. Also, I'm sure there is a cleaner way to do this (like a loop or nested array), I just can't see how.
<?php
$pageId0 = opt('first_tab_page');
$post0 = get_post($pageId0);
$content0 = apply_filters('the_content', $post0->post_content);
$icon0 = wp_get_attachment_image_src( get_post_thumbnail_id( $post0->ID ), 'full' );
$pageId1 = opt('second_tab_page');
$post1 = get_post($pageId1);
$content1 = apply_filters('the_content', $post1->post_content);
$icon1 = wp_get_attachment_image_src( get_post_thumbnail_id( $post1->ID ), 'full' );
$pageId2 = opt('third_tab_page');
$post2 = get_post($pageId2);
$content2 = apply_filters('the_content', $post2->post_content);
$icon2 = wp_get_attachment_image_src( get_post_thumbnail_id( $post2->ID ), 'full' );
?>
<div>
<?php echo $icon0[0]; ?>
</div>
<div>
<?php echo $icon1[0]; ?>
</div>
<div>
<?php echo $icon2[0]; ?>
</div>
<?php
$tab_position = opt('tab_position');
if ($tab_position == '' || count($tab_position) != 3) {
$tab_position = array(0, 1, 2);
}
for($i=0; $i < count($tab_position); $i++)
{
$selected = '';
if (opt('default_selected_tab') == $tab_position[$i]){
$selected = 'class="selected"';
}
?>
<a <?php echo $selected; ?> href="#tab<?php echo $tab_position[$i];?>">
<?php echo $content//should be 0 to start; ?>
</a>
<?php } ?>
Here is a short example on using arrays. comment in code
// Storing tab names to an array, just add more tabs if required
// and details for all those will be loaded in the following arrays
$tabs = array('first_tab_page', 'second_tab_page', 'third_tab_page');
//declare arrays to store (not required, but better practice)
$pageids = array();
$posts = array();
$content = array();
$icons = array();
//Iterate through the tabs array
foreach ($tabs as $tab){
//Store page id and post in a variable, we require it
$pageid = opt($tab);
$post = get_post($pageid);
// Store pageid in pageids. note the [] this means it will store pageid at next index
//also store other items
$pageids[] = $pageid;
$posts[] = $post;
$contents[] = apply_filters('the_content', $post->post_content);
$icons[] = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
}
now $icons[0] will contain first icon $icons[1] the second one and so on. Same thing applies to other variables.
Note: this code is just typed in here and not checked. Please fix if there is any syntax errors. Also note this is one way and there are more ways.
But I would suggest keeping data of each page together.
Edit: Here is how you can keep things together (only relevant parts shown)
$tabs = array('first_tab_page', 'second_tab_page', 'third_tab_page');
$pages = array();
foreach ($tabs as $tab){
$pageid = opt($tab);
$post = get_post($pageid);
$content = apply_filters('the_content', $post->post_content);
$icon = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
//Store everything to $pages array
$pages[] = array('pageid' => $pageid, 'post' => $post, 'content' => $content, 'icon', $icon);
}
foreach ($pages as $page){
?>
<div>
<?php echo $page['icon'][0]; ?>
</div>
<?php } ?>
foreach ($pages as $page){
?>
<a <?php echo $selected; ?> href="#tab<?php echo $tab_position[$i];?>">
<?php echo $page['content']; //echo the content of page ?>
</a>
<?php } ?>
Instead of foreach to display you can use index also like
<a <?php echo $selected; ?> href="#tab<?php echo $tab_position[$i];?>">
<?php echo $pages[0]['content']; //echo the content of the first page ?>
</a>
<a <?php echo $selected; ?> href="#tab<?php echo $tab_position[$i];?>">
<?php echo $pages[1]['content']; //echo the content of the second page ?>
</a>
I guess there is no other way then (nested) arrays. Also I'm thinking that arrays are a acceptable solution.
foreach ($tabs as $tab) {
$tab['content'] = 'somecontent';
$tab['counter'] = 'counter';
}
or
foreach ($tabs as $tab) {
$tab = [
"content" => "content",
"counter" => "counter"];
}
I'm not sure what you are trying to do as your question is not very clear to me. But i think you are trying to echo $content in your last line of code. If yes, just put your all your variables $content1, $content2 and $content3 in an array like below:
$contents = array($content1, $content2, $content3);
Then use foreach loop and traverse this array like this.
$count = 0;
foreach($contents as $content) {
echo $content.$count;
$count++;
}
Try and let me know if it works for you.

Getting last record value only

I am getting only the last element value, like in my case i am trying to get value of $dwnld_name
but don't know where i am missing, so only getting download name for the last record
<?php
global $cat_id;
$dwnld_sql = "SELECT * FROM wp_dm_downloads";
$dwnld_qry = mysql_query($dwnld_sql);
while($dwnld_row = mysql_fetch_array($dwnld_qry)){
echo $link = $dwnld_row['link'];
echo $dwnld_name = $dwnld_row['name'];
$cat_id = $dwnld_row['category'];
}
?>
<?php
$sql = "SELECT * FROM wp_dm_category";
$myquery = mysql_query($sql);
echo '<ul>';
while($row = mysql_fetch_array($myquery)){
$x = $row['name'];
echo $x_id = $row['id'];
?>
<li><a href="#"><?php echo $x; ?>
<?php if($x_id == $cat_id) { ?>
<ul>
<li><?php echo $dwnld_name; ?></li>
</ul>
<?php } ?>
</a></li>
<?php echo "<br/>";
}
echo '</ul>';
?>
It is because, you are taking the values from loop in strings.
Everytime loop runs, it overwrites the values by recent values.
You can create an array and append values to that and loop through that array using foreach
Corrected Code:
<?php
global $cat_id;
$dwnld_sql = "SELECT * FROM wp_dm_downloads";
$dwnld_qry = mysql_query($dwnld_sql);
$downloads = array();
while($dwnld_row = mysql_fetch_array($dwnld_qry)){
$downloads['link'] = $dwnld_row['link'];
$downloads['dwnld_name'] = $dwnld_row['name'];
$downloads['cat_id'] = $dwnld_row['category'];
}
?>
Now, loop through $downloads array.
Note: Do not use mysql_ functions are they are deprecated and will be removed in future versions of PHP.
You need to echo $dwnld_name in the loop, or save names into array.
With this solution you overwrite $dwnld_name variable in each loop and as a result after the loop you have the last record.

PHP Execute array multple times on the one page

I want to run two seperate foreach loops on the one page, but only write my SQL once. For example see the below code, only the ul with the id of first runs, the second ul is empty.
<?php
$mylist = 'SELECT * FROM myTable';
$showlist = $pdo->prepare($mylist);
$showlist->execute();
?>
<ul id="first">
<?php foreach ($showlist as $rowid):;?>
<li><?php echo $rowid['id'] ?></li>
<?php endforeach; ?>
</ul>
<ul id="second">
<?php foreach ($showlist as $rowname):;?>
<li><?php echo $rowname['name'] ?></li>
<?php endforeach; ?>
</ul>
I thought renaming the as would allow me to use it again but this doesn't seem to be the case? What is the best approach here?
try:
<?php
$mylist = 'SELECT * FROM myTable';
$showlist = $pdo->prepare($mylist);
$showlist->execute();
$result = $showlist->fetchAll();
foreach ($result as $rowid) {
// do stuff
}
foreach ($result as $rowname) {
// do stuff
}
You'd need to stack your elements in an extra array first:
$mylist = 'SELECT * FROM myTable';
$showlist = $pdo->prepare($mylist);
$showlist->execute();
$rows = array();
foreach($showlist as $row) {
array_push($rows, $row);
}
echo "<ul>";
foreach($rows as $row) {
echo "<li>".$row['id']."</li>";
}
echo "</ul><ul>";
foreach($rows as $row) {
echo "<li>".$row['name']."</li>";
}
echo "</ul>";

Ordering and then setting variables

I have the following code which orders my data in mysql perfectly:
<?php
$con = mysql_connect('localhost','root','password');
mysql_select_db("users");
$pop = mysql_query("
SELECT * FROM images ORDER BY pop DESC LIMIT 9
");
while($row = mysql_fetch_array($pop))
{
echo $row['imagefile'];
echo "<br />";
}
mysql_close($con);
?>
However i would like for each "result" to then automatically be assigned as a variable. So for example "uploads/logo.png" comes out as the first "result" of the above code. I would then want this to be assigned $image_1 - so in code it would read $image_1 = "uploads/logo.png". I then want all the other 8 outputs to be assigned to variables so that $image_2 corresponds to the second output and so on. This is only a prototype. I wish for it to eventually output 100 results. Is this at all possible? Thanks a lot for your time.
Use an array.
$images = array();
while($row = mysql_fetch_array($pop))
$images[] = $row['imagefile'];
Or keep the associative array:
$imageData = array();
while($row = mysql_fetch_array($pop))
$imageData[] = $row;
// $imageData[0]['imageFile'] will be "uploads/logo.png"
Edit for comment below:
First method from above:
<?php
foreach ($images as $image) {
echo <<<EOT
<div class="box"><img src= "$image" width="200" height="150"></a></div>
EOT;
}
?>
Second method could be more involved, depending on your data:
<?php
foreach ($imageData as $image) {
$imagePath = $image['imageFile'];
$imageWidth = $image['width'];
$imageHeight = $image['height'];
echo <<<HTML
<div class="box"><img src= "$imagePath" width=$imageWidth height=$imageHeight></a></div>
HTML;
}
?>

Categories