Looping 2 set of results twice - php

I have a page where I need to pull the titles of 3 of the latest records in one bootstrap row and then few lines further in the next row I need to pull the image of each record (only 3) again.
How can I do this?

On your loop construct two series of HTML entries, one for your titles and another one for your pictrures. Then echo each HTML string to the div you want them to be.
<?php
titlesHTML = "";
imagesHTML = "";
foreach ($result as $row) {
$contentTitle = $row['cont_title'];
$contentImage = $row['cont_picture'];
$titlesHTML .= "<p>" . $contentTitle . "</p>";
$imagesHTML .= "<p>" . $contentImage . "</p>";
// if you want not to echo the image location but the image itself try the following code instead:
// $imagesHTML .= "<img src='" . $contentImage . "'>";
}
?>
<div class="row">
<div class="col-em-12">
<?php echo $titlesHTML; ?>
</div>
<div>
<div class="row">
<div class="col-em-12">
<?php echo $imagesHTML; ?>
</div>
<div>

Related

How to select a result from a result that return by a SQL

I'm using SQL and PHP to pull information from my database and it returned a list of users that met the criteria. And I need to redirect to another page using the selected amount from the picture below. How can I grab this amount to another page?
For example, when I click the first select, I can go to the other page that showing $24, and Rubinsztein Abdel, 182 Crownhardt Lane...
<!--loader end-->
<!-- Main -->
<div id="main">
<!-- wrapper -->
<div id="wrapper">
<div class="content">
<!-- Map -->
<div class="map-container column-map right-pos-map">
<div id="map-main"></div>
<ul class="mapnavigation"></ul>
<div class="scrollContorl mapnavbtn" title="Enable Scrolling"><span><i class="fa fa-lock"></i></span></div>
</div>
<!-- Map end -->
<!--col-list-wrap -->
<div class="col-list-wrap left-list">
<!-- list-main-wrap-->
<div class="list-main-wrap fl-wrap card-listing">
<!-- listing-item -->
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$severname = "localhost";
$username = "root";
$password = "";
$dbname = "dbn";
//$conn = mysqli_connect('xx', 'xx', 'xx','xx');
$conn = mysqli_connect('dxx', 'xx', 'xx','xx');
//check connection
if (mysqli_connect_errno())
{echo nl2br("Failed to connect to MySQL: ". mysqli_connect_error() . "\n"); }
else
{ echo nl2br("");}
$city = mysqli_real_escape_string($conn, $_POST['city']);
$date1 = mysqli_real_escape_string($conn, $_POST['date1']);
$date2 = mysqli_real_escape_string($conn,$_POST['date2']);
$pet = mysqli_real_escape_string($conn, $_POST['pet']);
//var_dump($date2);
$sql = "SELECT CONCAT(s.lname, ' ', s.fname) AS fullName, s.ratings, s.rate, s.phone, s.address FROM Pet_Sitter AS s WHERE s.citystate='".$city."' AND s.pet_type='".$pet."' "
;
//echo $sql."<br/>";
$result = mysqli_query($conn,$sql);
if (!$result) {
printf("Error: %s\n", mysqli_error($conn));
exit();
}
if ($result=mysqli_query($conn,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
printf("");
}
//var_dump($result);
$num_rows = mysqli_num_rows($result);
?> <div class="container"> <?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
//var_dump($row);
// echo "<tr><td>" . $row['fullName'] . " </td><td>" . $row['ratings'] . " </td><td>" . $row['rate'] . " </td></tr>";
// echo '<div class="listing-item">';
echo '<div class="listing-item">';
echo '<article class="geodir-category-listing fl-wrap">';
echo '<div class="geodir-category-img">';
echo '<img src="../images/all/1.jpg" alt="">';
echo '<div class="overlay"></div>';
echo '<div class="list-post-counter"><span>' . $row['rate'] . '</span></div>';
echo '</div>';
echo '<div class="geodir-category-content fl-wrap">';
echo '<a class="listing-geodir-category" href="../index.html">Pet sitting</a>';
echo '<h3>' . $row['fullName'] . '</h3>';
echo '<p>PET-SITTER INFORMATION</p>';
echo '<div class="geodir-category-options fl-wrap">';
echo '<span>' . 'Reviews ' . $row['ratings'] .'</span>';
echo '<div class="geodir-category-location">'. $row['address'] . " ยท " . $row['phone'] .
'</div>';
echo '</div>';
echo '</div>';
echo '</article>';
echo '</div>';
}?>
<?php
} else {
echo "0 results";
}
mysqli_close($conn);
?>
</div>
</div>
An easy way to do it is to create one page (the one you wanna go if you click on your items) and use GET on URL to get the page id;
On your actual page you will use a link like :
<a href="new-page.php?id=<?php echo $row['id']; ?>"
Here the ?id= on URL is a parameter, that you can get on the other page :
$pageId = $_GET['id'];
Then, you just have to make a SQL request
SELECT * FROM Pet_Sitter WHERE id=$pageId
(better to use prepare and execute for this request as the value of $pageId can be change by everybody by changing the URL).
So every time you click on a link, the page will display the matching informations.
Also you should closed <?php when you are writing HTML instead of using a lot of echo.

How to fetch news from a db and print them on a PHP page?

I want to fetch the last two news from a DB, then print them on a PHP page using a function.
The two news should be printed one next to the other.
This is what I've done so far, what am I doing wrong?
This is the problem:
<?php
function getAllNewsHome(){
$connection = mysqli_connect("localhost", "root", "", "serverName");
$connection->query("SET NAMES 'utf8'");
$rsNewsHome = mysqli_query($connection, "SELECT * FROM news ORDER BY id DESC LIMIT 2");
$newsHome = mysqli_fetch_all($rsNewsHome, MYSQLI_ASSOC);
mysqli_close($connection);
for($i=0; $i < count($newsHome); $i++){
echo "
<div class='container'>
<div class='row'>
<div class='col-xs-6'>
<h1>".$newsHome[$i]['title']."
</h1>
<p>".$newsHome[$i]['content']."
</div>
<div class='col-xs-6'>
<h1>".$newsHome[$i]['title']."
</h1>
<p>".$newsHome[$i]['content']."
</div>
</div>
</div>
";
}
}
?>
This might be the easiest: increment $i inside of your loop, then make sure that it exists before you echo it out. This will allow you to keep your divs aligned:
for($i = 0; $i < count($newsHome); $i++) {
echo "
<div class='container'>
<div class='row'>
<div class='col-xs-6'>
<h1>" . $newsHome[$i]['title'] . "
</h1>
<p>" . $newsHome[$i]['content'] . "</p>
</div>";
$i++;
echo "
<div class='col-xs-6'>";
if(array_key_exists($i, $newsHome)) {
echo "<h1>" . $newsHome[$i]['title'] . "
</h1>
<p>" . $newsHome[$i]['content'] . "</p>";
}
echo "
</div>
</div>
</div>
";
}
It's doing exactly what you told it to do! Inside the for($i=0; $i < count($newsHome); $i++) loop it produces 2 divs, each containing the same "news" ( $newsHome[$i]['title']) twice!
You want the first div to contain the first article and the second div to contain the second article.
If you remove the second div within the for loop, it will create one div for each "news".
(And you will likely have to move the 2 outer divs (<div class='container'> and <div class='row'> outside the loop)

Don't display the specific empty column of row from database

I have a working code that can insert and update information from the database and echoing it to page. but I like to hide the specific empty column while displaying all the information from the row. check this screenshot
my goal is to hide the "image" column when its null/empty; so the crock image wont display. here is my code below:
<?php
$result = mysqli_query($mysqli, "SELECT * FROM blogs ORDER BY id DESC");
while ($row = mysqli_fetch_array($result))
if (!empty($row['image'] != ""))
{
echo "<div class='row'>
<div class='col-lg-12 box'>
<div class='content-heading'>
<p>
<text>".$row['title']."</text>
</p>
</div>
<p>
<text1 class='pull-right' >".$row['image_text']."</text1><br/>
<img class='img-size' id='hp'src='admin/upload_images/".$row['image']."'/>
<text>".$row['definition']."</text>
</p>
</div>
</div>";
}
?>
but this code if (!empty($row['image'] != "")) is hiding the entire row from my database.
Can anyone have a right solution to my problem?
You could try using the style attribute of the <img> tag to selectively show or hide the image tag:
<img class='img-size'
id='hp'
style='display: '. ($row["image"] != "" ? "block" : "none") . ';'
src='admin/upload_images/".$row['image']."'/>
Instead of hiding entire row, you could just hide the image tag, like this:
<?php
$result = mysqli_query($mysqli, "SELECT * FROM blogs ORDER BY id DESC");
while ($row = mysqli_fetch_array($result))
{
echo "
<div class='row'>
<div class='col-lg-12 box'>
<div class='content-heading'>
<p>
<text>".$row['title']."</text>
</p>
</div>
<p>
<text1 class='pull-right' >".$row['image_text']."</text1><br/>
";
if (!empty($row['image'])) {
echo "<img class='img-size' id='hp'src='admin/upload_images/".$row['image']."'/>";
}
echo "
<text>".$row['definition']."</text>
</p>
</div>
</div>
";
}
?>
Your if condition will hide all other html elements as well instead you should hide only img tag when no value found for image.
Update your code as below :
while ($row = mysqli_fetch_array($result)) {
$image = (!empty($row['image'])) ? "<img class='img-size' id='hp'src='admin/upload_images/" . $row['image'] . "'/>" : "";
echo "<div class='row'>
<div class='col-lg-12 box'>
<div class='content-heading'>
<p>
<text>" . $row['title'] . "</text>
</p>
</div>
<p>
<text1 class='pull-right' >" . $row['image_text'] . "</text1><br/>
" . $image . "
<text>" . $row['definition'] . "</text>
</p>
</div>
</div>";
}

PDO MySQL product loop

Im a real beginner when it comes to queries and PDO, i need some assistance in a project i am busy with. What i want to accomplish is to display products from the database. However the template style i am using forces me to show 3 products per row, is there a way to show 3 products per row and loop the code once there is more than 3 (if there is 5 products, the first 3 will display in the first row, and the rest in the second).
Here is the template i am using, note the div class "top-box", this forces that only 3 products can be shown per row.
<div class="top-box">
<?php
$sql = "SELECT * FROM _products WHERE category = '$cat'";
$result = dbConnect()->query($sql);
// If the SQL query is succesfully performed ($result not false)
if($result !== false) {
$cols = $result->columnCount(); // Number of returned columns
// Generate ADS Feed for each ROW
foreach($result as $row) {
echo '<div class="col_1_of_3 span_1_of_3">
<a href="product.php?i=' . $row['model'] . '">
<div class="inner_content clearfix">
<div class="product_image">
<img src="images/' . $row['model'] . '.jpg" alt=""/>
</div>
<div class="price">
<div class="cart-left">
<p class="title">' . $row['name'] . '</p>
</div>
<div class="clear"></div>
</div>
</div>
</a>
</div>';
}
} else {
echo "<p>No products available at this moment, contact us for more information!</p>";
}
?>
<div class="clear"></div>
</div>
You can solve it like this:
<?php
if ($counter % 3 == 0 && $counter!=$total_row_fetched) {
echo '<div class="clear"></div>';
echo '</div>';
echo '<div class="top-box">';
}
if($counter==$total_row_fetched){
echo '<div class="clear"></div>';
echo '</div>'; // it will close the last open div
}
++$counter;
?>
You can use a count variable inside your products foreach-loop. Every three products you can close the top-box and open a new one (This is an assumption as I don't know exactly how your styles work).
At the end of the foreach-loop:
if ($count != 0 && $count % 3 == 0) {
echo '<div class="clear"></div>';
echo '</div>'; // close last .top-box
echo '<div class="top-box">';
}
++$count;
I don't see how your question is connected to PDO. Keep in mind that using unescaped variables inside a query is potentially dangerous. Have a look here for some help: https://stackoverflow.com/a/60496/2516377
Add a counter and use % arithmetic operator to calculate column number.
$counter=0;
foreach (...) {
$column_number=$counter % 3;
$counter++;
}

Populating Navigation Tabs with SQL?

I'm looking for some kind of Nav tab (vertical) that allows it to be populated by SQL. For example, in the SQL table there would be a column for title (which is the title of the tab) and a column for the contents of the tab.
I have tried building one myself, but I have no idea how to fit it in a nav bar because usually I'd do a while loop to populate something with SQL, but because nav's have two things that need populating (the <li> and the <div> bits), I am unsure of how to do it.
Thanks.
Edit:
<ul>
<?php
$query = tep_db_query("select * table1");
while ($row = mysql_fetch_assoc($query)) {
echo '<li>' . $row['tabtitle'] . '</li>'
}
?>
</ul>
<?php
$query2 = tep_db_query("select * table1");
while ($row = mysql_fetch_assoc($query2)) {
echo '
<div id="tabs-' . $row['tabid'] . '">
<p> ' . $row['tabcontent'] . ' </p>
'
}
?>
What you have seems like it would be okay, you might be able to do something like this in order to eliminate half of your db calls.
//Get information from db.
<?php
$query = tep_db_query("SELECT tabid, tabtitle, tabcontent FROM table1");
while ($row = mysql_fetch_assoc($query)) {
$table[] = $row;
}
?>
<ul>
<?php foreach($table as $row){
echo '<li>' . $row['tabtitle'] . '</li>';
}
?>
</ul>
<?php foreach($table as $row){
echo '
<div id="tabs-' . $row['tabid'] . '">
<p> ' . $row['tabcontent'] . ' </p>
';
}
?>

Categories