Want to post multiple search results - php

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

Related

How to echo multiple images using an Array

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

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>';
}

Import data from xml

I'm trying to get data from an XML file using simple_xml , so far I can get all the data except the images . How can I call a single image name ?
<?php
$ur="http://services2.jupix.co.uk/api/get_properties.php?clientID=35871cc1b6d9ec6237aaaf94aa0e0836&passphrase=cvYG9f";
$xml = simplexml_load_file($ur);
foreach ($xml->property as $property):
var_dump($property->images->image);
echo 'images->image">'; // this is not displaying
endforeach;?>
My code output as the image below . How can i display image number 1
public 1 => string 'http://media2.jupix.co.uk/v3/clients/657/properties/1356/IMG_1356_9_large.jpg' (length=77)
I think SimpleXMLElement::xpath can do what you are looking for:
You can give this a try:
<?php
$ur="http://services2.jupix.co.uk/api/get_properties.php?clientID=35871cc1b6d9ec6237aaaf94aa0e0836&passphrase=cvYG9f";
$xml = simplexml_load_file($ur);
$image = $xml->xpath('//property/images/image[#modified="2014-07-23 14:22:05"]')[1]->__toString();
var_dump($image);
Or you can loop through all the images and check for the name the you are looking for:
$images = $xml->xpath('//property/images/image');
foreach ($images as $image) {
$url = $image->__toString();
if (false !== strpos($url, "_9_large.jpg")) {
var_dump($url);
}
}
If you want to get the second image of each /images section, then you could do it like this:
$images = $xml->xpath('//property/images');
foreach ($images as $image) {
if (isset($image->children()[1])) {
var_dump($image->children()[1]->__toString());
}
}
Thanks Guy I found solution to my problem .
Looking at the back at the question it seems I did not put it in a proper way
All i wanted is to display images within that section. Xpath was not necessary But i have learned from it . Here is my solution if you can improve it you are much welcome.
$url ="http://services2.jupix.co.uk/api/get_properties.php?clientID=35871cc1b6d9ec6237aaaf94aa0e0836&passphrase=cvYG9f";
$xml = simplexml_load_file($url);
foreach ($xml->property as $property):
?>
<li>
<h3> <?php echo $property->addressStreet;?> </h3>
<?php
$imgCount = count($property->images->image);
for ($i=0; $i < $imgCount; $i++) { ?>
<img src="<?php echo $property->images->image[$i];?>">
<?php } ?>
<p><?php echo limit_text($property->fullDescription,30);?></p>
<h4>£ <?php echo $property->price;?> </h4>
</li>
<?php endforeach; ?>

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.

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