PHP while loop number of rows - php

im struggling with php while loop. The goal is to get the quote from the database and display it with 3 columns on each row. As it look now the while loop is displaying one column each row. How should i correct this problem?
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$row = $ip['id'];
$row = $ip['quote'];
$row = $ip['topic'];
$row = $ip['author'];
$nr = 0;
$sql = "SELECT * FROM quotes ORDER BY date DESC limit 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc() ) {
$nr++;
echo
"<div class='container row'>
<div class='col s12 m6 l4 z-depth-1'>
<div class='card-panel grey darken-4 white-text center'><h5>Citat: ". $row["id"] ."</h5></div> <pre class='flow-text black-text' wrap='soft'>" ."<p class=''>Författare: ". $row["author"] ."</p>"
. "<p class=''>Citat: ". $row["quote"] ."</p>" . $row["topic"] ."</pre>
<div class='content_wrapper'>
<h4>Vote </h4>
<div class='voting_wrapper' id='". $row["id"] ."'>
<div class='voting_btn'>
<div class='up_button'> </div><span class='up_votes'>0</span>
</div>
<div class='voting_btn'>
<div class='down_button'> </div><span class='down_votes'>0</span>
</div>
<br>
</div>
</div>
</div>
</div>";
}
}else {
echo "0 results";
}
$conn->close();
?>

You could do something like this:
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//DO YOU NEED THESE VARIABLES? I DON'T SEE THEIR USE HERE... BESIDES, $row DOES NOT EXIST YET...
$row = $ip['id'];
$row = $ip['quote'];
$row = $ip['topic'];
$row = $ip['author'];
$nr = 0;
$sql = "SELECT * FROM quotes ORDER BY date DESC limit 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$output = "";
while($row = $result->fetch_assoc() ) {
$topic = trim($row["topic"]);
$quote = trim($row["quote"]);
$author = trim($row["author"]);
$id = trim($row["id"]);
$output .= injectNColumnWrapper(3, $nr, "container row", $nr);
$output .="<div class='col s12 m6 l4 z-depth-1'>";
$output .="<div class='card-panel grey darken-4 white-text center'>";
$output .=" <h5>Citat: {$id}</h5>";
$output .="</div>";
$output .="pre class='flow-text black-text' wrap='soft'>";
$output .="<p class='flow-text-p author'>Författare: {$author}</p>";
$output .="<p class='flow-text-p citat'>Citat: {$quote}</p>";
$output .="<p class='flow-text-p topic'>{$topic}</p>";
$output .="</pre>";
$output .="<div class='content_wrapper'>";
$output .="<h4>Vote </h4>";
$output .="<div class='voting_wrapper' id='vote-{$id}'>";
$output .="<div class='voting_btn'>";
$output .="<div class='up_button'> </div>";
$output .="<span class='up_votes'>0</span>";
$output .="</div>";
$output .="<div class='voting_btn'>";
$output .="<div class='down_button'> </div>";
$output .="<span class='down_votes'>0</span>";
$output .="</div>";
$output .="<br>";
$output .="</div>";
$output .="</div>";
$output .="</div>";
$nr++;
}
$output .= "</div>";
echo $output;
}else {
echo "0 results";
}
$conn->close();
function injectNColumnWrapper($cols_per_row, $closePoint, $cssClass="container row", $nthElem=""){
$blockDisplay = "";
if( ($closePoint == 0) ){
$blockDisplay = "<div class='" . $cssClass . " container_nr_" . $nthElem . "'>" . PHP_EOL;
}else if( ($closePoint % $cols_per_row) == 0 && ($closePoint != 0) ){
$blockDisplay = "</div><div class='" . $cssClass . " container_nr_" . $nthElem . "'>" . PHP_EOL;
}
return $blockDisplay;
}
?>
You should have 3 Columns per Row like so:
<div class="container">
<div class="col s12 m6 l4 z-depth-1">Column 1</div>
<div class="col s12 m6 l4 z-depth-1">Column 2</div>
<div class="col s12 m6 l4 z-depth-1">Column 3</div>
</div>
I hope this helps a little bit...

Try it:-
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$row = $ip['id'];
$row = $ip['quote'];
$row = $ip['topic'];
$row = $ip['author'];
$nr = 0;
$sql = "SELECT * FROM quotes ORDER BY date DESC limit 10";
$result = $conn->query($sql);
$chngrow=0;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc() ) {
$nr++;
$chngrow = $chngrow + 1;
echo
"<div class='container row'>
<div class='col s12 m6 l4 z-depth-1'>
<div class='card-panel grey darken-4 white-text center'><h5>Citat: ". $row["id"] ."</h5></div> <pre class='flow-text black-text' wrap='soft'>" ."<p class=''>Författare: ". $row["author"] ."</p>"
. "<p class=''>Citat: ". $row["quote"] ."</p>" . $row["topic"] ."</pre>
<div class='content_wrapper'>
<h4>Vote </h4>
<div class='voting_wrapper' id='". $row["id"] ."'>
<div class='voting_btn'>
<div class='up_button'> </div><span class='up_votes'>0</span>
</div>
<div class='voting_btn'>
<div class='down_button'> </div><span class='down_votes'>0</span>
</div>
<br>
</div>
</div>
</div>
</div>";
$mod = ($chngrow % 3);
echo ($mod==0) ? "<br>" : "";
}
}else {
echo "0 results";
}
$conn->close();
?>

Elaborating #RuchishParikh comment, which already contains the core of the solution:
$nr = 0;
while ($row = $result->fetch_assoc()) {
$nr++;
if ($nr % 3 == 0) {
echo "<div class='container row'>\n"; # start of row
}
echo "<div class='col s4 m6 l4 z-depth-1'>\n"; # start of column
echo " ...\n";
echo "</div>\n"; # end of column
if ($nr % 3 == 0) {
echo "</div>\n"; # end of row
}
}

Try like this,
$nr =0;
while($row = $result->fetch_assoc() ) {
$nr++;
if(($count-1)%3==0) echo '<div class="row">';
//Add your content units here.
if(($count)%3==0) echo '</div>';
}

increment a counter variable for every loop. open table tag and tr tag outside of the loop. the while loop should have td tag alone. if count%3==0 then close the tr tag and open a new tr tag.
$i=0
?><table><tr><?
while(condition)
{
$i++;
if($i%3==0)
{
?></tr><tr><?
}
?><td>your data</td><?
}
?></tr></table><?

You messed up with the variables.
Don't need to declare $row below:
$row = $ip['id'];
$row = $ip['quote'];
$row = $ip['topic'];
$row = $ip['author'];
As stated here Why shouldn't I use mysql_* functions in PHP? don't use mysql_* functions.
You need to fetch 3 rows and place them inside one container.
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$db = new PDO("mysql:host=$servername;dbname=$dbname;charset=UTF-8",
$username
$password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = "SELECT * FROM quotes ORDER BY date DESC limit 10";
$nr = 0;
$stmt = $db->query('SELECT * FROM table');
while($row1 = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row2 = $stmt->fetch(PDO::FETCH_ASSOC);
$row3 = $stmt->fetch(PDO::FETCH_ASSOC);
$rows[] = $row1;
if ($row2) $rows[] = $row2;
if ($row3) $rows[] = $row3;
echo "<div class='container row'>\n"
foreach($rows as $row) {
$nr++;
$id_ = $row["id"];
$author_ = $row["author"];
$quote_ = $row["quote"];
$topic_ = $row["topic"];
echo
"<div class='col s12 m6 l4 z-depth-1'>
<div class='card-panel grey darken-4 white-text center'><h5>Citat:$id_ </h5></div>
<pre class='flow-text black-text' wrap='soft'>
<p class=''>Författare: $author_</p>
<p class=''>Citat: $quote_</p>
$topic_
</pre>
<div class='content_wrapper'>
<h4>Vote </h4>
<div class='voting_wrapper' id='$id_'>
<div class='voting_btn'>
<div class='up_button'> </div><span class='up_votes'>0</span>
</div>
<div class='voting_btn'>
<div class='down_button'> </div><span class='down_votes'>0</span>
</div>
<br />
</div>
</div>
</div>";
}
echo "</div>\n";
$rows = null;
}
if ($nr == 0){
echo "0 results";
}
?>

Try this
$i=0
?><table><tr><?
while(condition)
{
$i++;
if($i%3==0)
{
?></tr><tr><?
}
?><td>your data</td><?
}
?></tr></table><?

Related

How to set PHP variable for first iteration of while loop?

I am trying to set the variable $OnWishList to display a tick or a plus symbol depending on if the property is in the wish list. Though it does this it skips the first property in the wile loop and shows the correct symbol for the first property on the second property. How can I get the symbols to show on the correct properties. I apologize if this is a simple question as I am new to PHP and SQL and have struggled with this problem for a while.
$city = (isset($_GET['city'])) ? $_GET['city'] : 0;
$suburb = (isset($_GET['suburb'])) ? $_GET['suburb'] : 0;
$minBed = (isset($_GET['minBed'])) ? $_GET['minBed'] : 0;
$maxBed = (isset($_GET['maxBed'])) ? $_GET['maxBed'] : 0;
$minBath = (isset($_GET['minBath'])) ? $_GET['minBath'] : 0;
$maxBath = (isset($_GET['maxBath'])) ? $_GET['maxBath'] : 0;
$minPrice = (isset($_GET['minPrice'])) ? $_GET['minPrice'] : 0;
$maxPrice = (isset($_GET['maxPrice'])) ? $_GET['maxPrice'] : 0;
$pagingVariable = '';
$cityName ='';
//}
$rowsPerPage = 8; // edit the number of rows per page
$query = "SELECT tbl_property.property_ID, tbl_property.name, tbl_property.location, tbl_property.description, tbl_property. price, tbl_property.landsize, tbl_property.property_image, tbl_property.bedrooms, tbl_property.bathrooms, tbl_property.garage, tbl_agents.agent_name, tbl_agents.agent_image, tbl_city.cityName FROM tbl_property INNER JOIN tbl_agents ON tbl_property.agent_ID=tbl_agents.agent_ID INNER JOIN tbl_city ON tbl_property.city_ID=tbl_city.city_ID";
//$query = "SELECT tbl_property.property_ID, tbl_property.name, tbl_property.location, tbl_property.description, tbl_property. price, tbl_property.landsize, tbl_property.property_image, tbl_property.bedrooms, tbl_property.bathrooms, tbl_property.garage, tbl_agents.agent_name, tbl_agents.agent_image FROM tbl_property INNER JOIN tbl_agents ON tbl_property.agent_ID=tbl_agents.agent_ID";
$pagingLink = getPagingLink($query, $rowsPerPage);
$result = mysqli_query($link, getPagingQuery($query, $rowsPerPage));
if($city == 0){
$query .= " WHERE ";
}
if($city != 0){
$query = "SELECT tbl_property.property_ID, tbl_property.name, tbl_property.location, tbl_property.description, tbl_property.price, tbl_property.landsize, tbl_property.property_image, tbl_property.bedrooms, tbl_property.bathrooms, tbl_property.garage, tbl_agents.agent_name, tbl_agents.agent_image, tbl_city.cityName FROM tbl_property INNER JOIN tbl_agents ON tbl_property.agent_ID=tbl_agents.agent_ID INNER JOIN tbl_city ON tbl_property.city_ID=tbl_city.city_ID WHERE tbl_property.city_ID ='$city'";
$pagingVariable .= "&city=".$_GET['city'];
$pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable);
$result = mysqli_query($link, getPagingQuery($query, $rowsPerPage));
}
if($suburb != 0){
$query .= "AND suburb_ID ='$suburb'";
$pagingVariable .= "&suburb=".$_GET['suburb'];
$pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable);
$result = mysqli_query($link, getPagingQuery($query, $rowsPerPage));
}
if($minBed != 0 && $maxBed == 0 && $city == 0){
$query .= " bedrooms >='$minBed'";
$pagingVariable .= "&minBed=".$_GET['minBed'];
$pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable);
$result = mysqli_query($link, getPagingQuery($query, $rowsPerPage));
}
if($minBed != 0 && $city != 0){
$query .= "AND bedrooms >='$minBed'";
$pagingVariable .= "&minBed=".$_GET['minBed'];
$pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable);
$result = mysqli_query($link, getPagingQuery($query, $rowsPerPage));
}
if($maxBed != 0 && $minBed == 0 && $city == 0){
$query .= " bedrooms <='$maxBed'";
$pagingVariable .= "&maxBed=".$_GET['maxBed'];
$pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable);
$result = mysqli_query($link, getPagingQuery($query, $rowsPerPage));
}
if($maxBed != 0 && $minBed == 0 && $city != 0){
$query .= "AND bedrooms <='$maxBed'";
$pagingVariable .= "&maxBed=".$_GET['maxBed'];
$pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable);
$result = mysqli_query($link, getPagingQuery($query, $rowsPerPage));
}
if($minBed != 0 && $maxBed != 0 && $city != 0){
$query .= "AND (bedrooms BETWEEN '$minBed' AND '$maxBed')";
$pagingVariable .= "&minBed=".$_GET['minBed']."&maxBed=".$_GET['maxBed'];
$pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable);
$result = mysqli_query($link, getPagingQuery($query, $rowsPerPage));
}
if($minBed != 0 && $maxBed != 0 && $city == 0){
$query .= " (bedrooms BETWEEN '$minBed' AND '$maxBed')";
$pagingVariable .= "&minBed=".$_GET['minBed']."&maxBed=".$_GET['maxBed'];
$pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable);
$result = mysqli_query($link, getPagingQuery($query, $rowsPerPage));
}
if ( ((($minBed != 0 || $maxBed != 0) && $city != 0)) || ((($minBed != 0 || $maxBed != 0) && $city == 0)) || ((($minBed == 0 && $maxBed == 0) && $city != 0))){
$query .= " AND";
}
if($minBath != 0 && $maxBath == 0 && $city == 0){
$query .= " bathrooms >='$minBath'";
$pagingVariable .= "&minBath=".$_GET['minBath'];
$pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable);
$result = mysqli_query($link, getPagingQuery($query, $rowsPerPage));
}
if($minBath != 0 && $maxBath == 0 && $city != 0){
$query .= " bathrooms >='$minBath'";
$pagingVariable .= "&minBath=".$_GET['minBath'];
$pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable);
$result = mysqli_query($link, getPagingQuery($query, $rowsPerPage));
}
if($minBath != 0 && $maxBath != 0 && $city == 0){
$query .= " (bathrooms BETWEEN '$minBath' AND '$maxBath')";
$pagingVariable .= "&minBath=".$_GET['minBath']."&maxBath=".$_GET['maxBath'];
$pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable);
$result = mysqli_query($link, getPagingQuery($query, $rowsPerPage));
}
if($minBath != 0 && $maxBath != 0 && $city != 0){
$query .= " (bathrooms BETWEEN '$minBath' AND '$maxBath')";
$pagingVariable .= "&minBath=".$_GET['minBath']."&maxBath=".$_GET['maxBath'];
$pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable);
$result = mysqli_query($link, getPagingQuery($query, $rowsPerPage));
}
if($maxBath != 0 && $minBath == 0 && $city == 0){
$query .= " bathrooms <='$maxBath'";
$pagingVariable .= "&maxBath=".$_GET['maxBath'];
$pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable);
$result = mysqli_query($link, getPagingQuery($query, $rowsPerPage));
}
if($maxBath != 0 && $minBath == 0 && $city != 0){
$query .= " bathrooms <='$maxBath'";
$pagingVariable .= "&maxBath=".$_GET['maxBath'];
$pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable);
$result = mysqli_query($link, getPagingQuery($query, $rowsPerPage));
}
//
//
if ($minBath != 0 || $maxBath != 0){
$query .= " AND";
}
if($minPrice != 0 && $maxPrice == 0 && $city == 0){
$query .= " Price >='$minPrice'";
$pagingVariable .= "&minPrice=".$_GET['minPrice'];
$pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable);
$result = mysqli_query($link, getPagingQuery($query, $rowsPerPage));
}
if($minPrice != 0 && $maxPrice == 0 && $city != 0){
$query .= " Price >='$minPrice'";
$pagingVariable .= "&minPrice=".$_GET['minPrice'];
$pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable);
$result = mysqli_query($link, getPagingQuery($query, $rowsPerPage));
}
if($minPrice != 0 && $maxPrice != 0 && $city == 0){
$query .= " (Price BETWEEN '$minPrice' AND '$maxPrice')";
$pagingVariable .= "&minPrice=".$_GET['minPrice']."&maxPrice=".$_GET['maxPrice'];
$pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable);
$result = mysqli_query($link, getPagingQuery($query, $rowsPerPage));
}
if($minPrice != 0 && $maxPrice != 0 && $city != 0){
$query .= " (Price BETWEEN '$minPrice' AND '$maxPrice')";
$pagingVariable .= "&minPrice=".$_GET['minPrice']."&maxPrice=".$_GET['maxPrice'];
$pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable);
$result = mysqli_query($link, getPagingQuery($query, $rowsPerPage));
}
if($maxPrice != 0 && $minPrice == 0 && $city == 0){
$query .= " Price <='$maxPrice'";
$pagingVariable .= "&maxPrice=".$_GET['maxPrice'];
$pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable);
$result = mysqli_query($link, getPagingQuery($query, $rowsPerPage));
}
if($maxPrice != 0 && $minPrice == 0 && $city != 0){
$query .= " Price <='$maxPrice'";
$pagingVariable .= "&maxPrice=".$_GET['maxPrice'];
$pagingLink = getPagingLink($query, $rowsPerPage, $pagingVariable);
$result = mysqli_query($link, getPagingQuery($query, $rowsPerPage));
}
if (mysqli_num_rows($result) < 1) {
$noResults = "Sorry, no results were found!";
} else {
while($row = mysqli_fetch_array($result)) {
extract($row);
?>
<div class="col-md-6">
<div class="propertyCardOuter card">
<div title="add to watchlist" class="displayWishAdd"><div class="plusSymbol"><?php echo $OnWishList;?></div></div>
<a class="propertyCardLink" href="viewProperty.php?propertyID=<?php echo $row['property_ID']; ?>"><div class="card propertyCard">
<div class="propertyImgContainer">
<img alt="Photo" class="PropertyImagesHome img-fluid" src="<?php echo 'property-images/'.$row['property_image']; ?>" title="<?php echo $row['name']; ?>" />
</div>
<div class="row">
<div class="col-md-9 propertyInfoBox">
<div class="propertyName">
<?php echo $row['name']; ?></div>
<div style="font-size: 14px;">
<?php echo $row['location']; ?>
</div>
<hr>
<div class="houseDetails">
<?php echo $row['bedrooms']; ?> <i class="fa fa-bed icons"></i><?php echo $row['bathrooms']; ?>
<i class="fa fa-bath icons"></i><?php echo $row['garage']; ?>
<i class="fa fa-car icons"></i><?php echo $row['landsize'] . 'sqm'; ?>
<img src="images/landSizeIcon.png" width="19px;" alt="landsize"/>
<span class="propertyPrice"><?php echo '$' . number_format($row['price']); ?></span>
</div>
</div>
<div class=" col-sm-12 col-md-3">
<div class="agentContainer">
<div class="agentPhotoContainer">
<img alt="Photo" class="agentImage" src="<?php echo 'property-images/'.$row['agent_image']; ?>" title="photo" />
</div>
<div style="text-align:center; margin-top: 10px;"><?php echo $row['agent_name']; ?></div></div>
</div>
</div>
</div></a></div>
<h3 style="text-align:right;">
</h3>
</div>
<?php
$propertyID2 = $row['property_ID'];
$query2 = "SELECT * FROM tbl_wishlist WHERE member_ID='$memberID' && property_wishList_ID='$propertyID2' ";
$result2 = mysqli_query($link, $query2); // execute the SQL
if ($row = mysqli_fetch_array($result2)) {
$OnWishList = "<span id='tickSpan'>✓</span>";
}
else {
$OnWishList = "<span id='plusSpan'>+</span>";
}
}
} // end of while loop
}
?>
I would like the $OnWishList variable to display the tick and plus symbols starting with the first property in the while loop. However the symbols are displayed skipping the first property in the loop and showing its symbol on the second property and so on.
It is generally considered, though there is some debate, that it yields better performance to craft a prepared statement before any loops and execute multiple times within a loop with different variables being passed in. That was the intention here in using a prepared statement and assigning variables to placeholders in the sql.
By moving this code to near the top of the loop on the first iteration into the loop it will be called before you attempt to use the variable $OnWishList
<?php
$sql='select * from `tbl_wishlist` where `member_id`=? and `property_wishlist_id`=?';
$stmt=$link->prepare( $sql );
$stmt->bind_param( 'ii', $memberID, $wishlistid );
while( $row = mysqli_fetch_array( $result ) ) {
extract( $row );
$wishlistid=$row['property_ID'];
$stmt->execute();
$stmt->store_result();
$count=$stmt->num_rows;
$OnWishList=$count > 0 ? "<span id='tickSpan'>✓</span>" : "<span id='plusSpan'>+</span>";
?>
<div class="col-md-6">
<div class="propertyCardOuter card">
<a href="addWishList.php?propertyID=<?php echo $row['property_ID']; ?>">
<div title="add to watchlist" class="displayWishAdd">
<div class="plusSymbol"><?php echo $OnWishList;?></div>
</div>
</a>
<a class="propertyCardLink" href="viewProperty.php?propertyID=<?php echo $row['property_ID']; ?>">
<div class="card propertyCard">
<div class="propertyImgContainer">
<img alt="Photo" class="PropertyImagesHome img-fluid" src="<?php echo 'property-images/'.$row['property_image']; ?>" title="<?php echo $row['name']; ?>" />
</div>
<div class="row">
<div class="col-md-9 propertyInfoBox">
<div class="propertyName">
<?php echo $row['name']; ?>
</div>
<div style="font-size: 14px;">
<?php echo $row['location']; ?>
</div>
<hr>
<div class="houseDetails">
<?php echo $row['bedrooms']; ?><i class="fa fa-bed icons"></i>
<?php echo $row['bathrooms']; ?><i class="fa fa-bath icons"></i>
<?php echo $row['garage']; ?><i class="fa fa-car icons"></i>
<?php echo $row['landsize'] . 'sqm'; ?><img src="images/landSizeIcon.png" width="19px;" alt="landsize"/>
<span class="propertyPrice"><?php echo '$' . number_format($row['price']); ?></span>
</div>
</div>
<div class=" col-sm-12 col-md-3">
<div class="agentContainer">
<div class="agentPhotoContainer">
<img alt="Photo" class="agentImage" src="<?php echo 'property-images/'.$row['agent_image']; ?>" title="photo" />
</div>
<div style="text-align:center; margin-top: 10px;"><?php echo $row['agent_name']; ?></div>
</div>
</div>
</div>
</div>
</a>
</div>
<h3 style="text-align:right;"></h3>
</div>
<?php
}//end while loop
?>
There is huge error in your second if clause:
if ($row = mysqli_fetch_array($result2)) {
// ^ only one equal sign !!
$OnWishList = "<span id='tickSpan'>✓</span>";
}
else {
$OnWishList = "<span id='plusSpan'>+</span>";
// this will NEVER be executed
}
So instead checking if the row is equal to something, you are actually checking, if $row can be assigned mysqli_fetch_array($result2) Therefore, the else clause will be executed only if you cannot assign new value to the $row variable.
Check first iteration in while loop like
<?php
$i=1;
while($row = mysqli_fetch_array($result)) {
?>
<?php
if($i==1){
echo "Yes or your code";
}
else
{
echo "no or your code";
}
?>
<?php $i++; } ?>

php - mysqli to pdo

Hello everyone I'm completely new to mysqli and PDO. I tried to convert my msqli code to PDO but I keep getting errors. Can someone please help me? the error is like when i click on post, nothing happens and I searched everywhere how to convert from msqli to pdo and I converted some of them but it still doesn't work
<?php
$databaseHost = 'localhost';
$databaseName = 'test';
$databaseUsername = 'test';
$databasePassword = 'pass';
try {
$dbConn = new PDO("mysql:host={$databaseHost};dbname={$databaseName}", $databaseUsername, $databasePassword);
$dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo $e->getMessage();
}
if (isset($_POST['save'])) {
$name = $_POST['name'];
$comment = $_POST['comment'];
$sql = "INSERT INTO comments (name, comment) VALUES ('{$name}', '{$comment}')";
if ($result = $dbConn->query($sql)) {
$id = $link->insert_id;
$saved_comment = '<div class="comment_box">
<span class="delete" data-id="' . $id . '" >delete</span>
<span class="edit" data-id="' . $id . '">edit</span>
<div class="display_name">'. $name .'</div>
<div class="comment_text">'. $comment .'</div>
</div>';
echo $saved_comment;
}else {
echo "Error: ".($dbConn);
}
exit();
}
// delete comment fromd database
if (isset($_GET['delete'])) {
$id = $_GET['id'];
$sql = "DELETE FROM comments WHERE id=" . $id;
($dbConn->prepare($sql));
exit();
}
if (isset($_POST['update'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$sql = "UPDATE comments SET name='{$name}', comment='{$comment}' WHERE id=".$id;
if ($dbConn->prepare($sql)) {
$id =($dbConn);
$saved_comment = '<div class="comment_box">
<span class="delete" data-id="' . $id . '" >delete</span>
<span class="edit" data-id="' . $id . '">edit</span>
<div class="display_name">'. $name .'</div>
<div class="comment_text">'. $comment .'</div>
</div>';
echo $saved_comment;
}else {
echo "Error: ". ($dbConn);
}
exit();
}
// Retrieve comments from database
$sql = "SELECT * FROM comments";
$result = $dbConn->prepare($sql);
$comments = '<div id="display_area">';
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$comments .= '<div class="comment_box">
<span class="delete" data-id="' . $row['id'] . '" >delete</span>
<span class="edit" data-id="' . $row['id'] . '">edit</span>
<div class="display_name">'. $row['name'] .'</div>
<div class="comment_text">'. $row['comment'] .'</div>
</div>';
}
$comments .= '</div>';
?>
You used ->prepare(), but did not use ->execute().
Documentation:
http://php.net/manual/en/pdostatement.execute.php

why my function is not working in php while loop?

I have review function which I need to run in PHP while loop. But somehow it's not working if I call the function in while loop.
But If I manually put the code (Rating Function) in while then it's working. Can you tell me why ?
Here is the function code:
function rating($star) {
echo "<div class='my_all_star'>";
$total = "";
for ($i=1; $i <= $star; $i++) {
$total .= "<img src='../images/star.png'/> ";
}
for ($i=1; $i <= (5 - $star); $i++) {
$total .= "<img src='../images/star_null.png'/> ";
}
if($star > 1 ){
$reviews = " Reviews";
}else{
$reviews = " Review";
}
$total .= ($star) . $reviews;
return $total;
echo "</div>";
}
Update : While Loop:
<?php
$grq = mysqli_query($conn, "SELECT tbl_reviews.*, tbl_users.FName, tbl_users.LName FROM tbl_reviews LEFT JOIN tbl_users ON tbl_reviews.reviewerID = tbl_users.UserID WHERE tbl_reviews.ProductID = '$pid' ");
while($allreviews = mysqli_fetch_array($grq)){
$review_text = inputvalid($allreviews['ReviewText']);
$review_date = inputvalid($allreviews['ReviewDate']);
$st_rating = (int) $allreviews['StarRating'];
$fname = inputvalid($allreviews['FName']);
$lname = inputvalid($allreviews['LName']);
?>
<div class="single_main_reviews">
<div class="col-sm-2 text-center rev_author_info">
<img src="../images/avater-1.png" alt="" />
<p>Reviewed by</p>
<?php echo $fname ." ". $lname; ?>
</div>
<div class="col-sm-10 rev_author_content">
<div class="rev_author_content_head">
<div class="">
<?php
echo "<div class='my_all_star'>";
$total = "";
$star = $st_rating;
for ($i=1; $i <= $star; $i++) {
$total .= "<img src='../images/star.png'/> ";
}
for ($i=1; $i <= (5 - $star); $i++) {
$total .= "<img src='../images/star_null.png'/> ";
}
if($star > 1 ){
$reviews = " Reviews";
}else{
$reviews = " Review";
}
$total .= ($star) . $reviews;
echo $total;
echo "</div>";
?>
</div>
<div class="pull-right"><span class="review-date"><?php echo $review_date; ?></span></div>
</div>
<div class="clear"></div>
<p><?php echo $review_text; ?></p>
</div>
</div>
<?php
}
?>
dont echo and return data at the same time.
function rating($star) {
$total = "<div class='my_all_star'>";
for ($i=1; $i <= $star; $i++) {
$total .= "<img src='../images/star.png'/> ";
}
for ($i=1; $i <= (5 - $star); $i++) {
$total .= "<img src='../images/star_null.png'/> ";
}
if($star > 1 ){
$reviews = " Reviews";
}else{
$reviews = " Review";
}
$total .= ($star) . $reviews;
$total .="</div>";
return $total;
}

How to refresh a database query using jQuery

I'm working on a real basic chat that is mostly php powered. I'd like to use jQuery to check for new messages and update the #cbox div every few seconds. So far I have tried accomplishing that using the code below. For a frame of reference, this is my first time including jQuery into any of my scripts, so the problem is likely a very simple error that I am overlooking in my newbishness.
The problem I'm running into is the #cbox div displays blank, it doesn't seem to be calling to chat_post.php at all. I will post that code as well, in case the problem is with that and not with my jQuery. To fix, I tried also including <div id='cbox'> in chat_post.php, but that yielded no results. At this point, I'm pretty much grasping at straws.
<div id='sb_content'>
<center><div id='chat'>
<div id='ribbon' style='position: relative; margin-top:-50px; margin-left:-32px;'><center><span class='ribbon'>chat box</span></center></div>
<div style='margin-top: -20px;'><center><span style='text-shadow: 0 0 0.2em #000;' class='admin'>admin</span> || <span style='text-shadow: 0 0 0.2em #000;' class='mod'>mod</span></center></div>
<div id="cbox">
<script>
$(document).ready(function() {
setInterval(function(){getUpdates()}, 2000);
});
function getUpdates() {
$("#cbox").load("chat_post.php");
}
</script>
</div>
<form name="message" method='post' action="chat_post.php" id="cbox_input">
<input name="usermsg"id='usermsg' type="text" size="63" maxlength="255" />
</form>
</div></center>
</div>
chat_post.php
<div id='cbox' align='left'>
<?php
$username = $_SESSION['login'];
$ug = $_SESSION['user_group'];
// Display messages
$sql = <<<SQL
SELECT *
FROM `chat_entries`
ORDER BY `ts` DESC
LIMIT 0,50
SQL;
$result = $db->query($sql);
$count = $result->num_rows;
if ($count != 0){
while ($row = mysqli_fetch_array($result)) {
$c_name = $row['author'];
$c_text = $row['text'];
$c_ts = $row['ts'];
$c_id = $row['id'];
$sqlm = <<<SQL
SELECT *
FROM `users`
WHERE username = '$c_name'
SQL;
$resultm = $db->query($sqlm);
$countm = $resultm->num_rows;
if ($count != 0){
while ($rowm = mysqli_fetch_array($resultm)) {
$c_level = $rowm['user_group'];
}
}
if ($c_level == 'mod') {
echo "
<a href='/user/" . $c_name . "' class='mod'>" . $c_name . "</a>
";
}
if ($c_level == 'admin') {
echo "
<a href='/user/" . $c_name . "' class='admin'>" . $c_name . "</a>
";
}
if ($c_level == 'member') {
echo "
<a href='/user/" . $c_name . "' class='member'>" . $c_name . "</a>
";
}
if ($c_level == 'guest') {
echo "
<i>" . $c_name . "</i>
";
}
echo "
: " . $c_text . "<div id='cbox_div'>";
echo "<span style='float:left;'><i>" . $c_ts . "</i></span>";
echo "<span style='float:right;'>";
if ($ug == 'mod' || $ug == 'admin'){
echo " <a href='#'>Delete</a> || <a href='#'>Block</a> ||";
}
if ($_SESSION['login']) {
echo "Report</span></div>
";
}
}
}
?>
After removing the extra id on chat_post.php, my code worked just fine. Funny how something so simple can really mess things up. (: Thank you everyone for your help!

Images in loop with different div class in PHP

Suppose I have code like bellow
<?php
$sql = "SELECT * FROM images";
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query)) {
echo '<div class="single">';
echo '<img src="'.$row['image'].'" alt="'.$row['title'].' " />';
echo '</div>';
}
?>
And I want to append first and last in div class <div class="single"> in every set of 5 images i.e
<div class="single first">
<img src="image1.jpg" alt="title1" />
</div>
<div class="single">
<img src="image2.jpg" alt="title2" />
</div>
<div class="single">
<img src="image3.jpg" alt="title3" />
</div>
<div class="single">
<img src="image4.jpg" alt="title4" />
</div>
<div class="single last">
<img src="image5.jpg" alt="title5" />
</div>
How to do it through loop, please help,
Thanks :)
Using modulo:
<?php
$sql = "SELECT * FROM images";
$query = mysql_query($sql);
$i = 0;
$class = "";
while($row = mysql_fetch_assoc($query)) {
if($i % 5 == 0){
$class = 'first';
}else if($i % 5 == 4){
$class = 'last';
}else{
$class = "";
}
echo '<div class="single ' . $class . '">';
echo '<img src="'.$row['image'].'" alt="'.$row['title'].' " />';
echo '</div>';
$i++;
}
?>
<?php
$sql = "SELECT * FROM images";
$query = mysql_query($sql);
$x=0;
while($row = mysql_fetch_assoc($query)) {
$x++;
if ( $x == 1 ) { $c = ' first'; }
elseif ( $x == 5 ) { $c = ' last'; }
else { $c = ''; }
echo '<div class="single' . $c . '">';
echo '<img src="'.$row['image'].'" alt="'.$row['title'].' " />';
echo '</div>';
}
?>
You need to count your iterations, and use the modulo function to get parts of 5:
$sql = "SELECT * FROM images";
$query = mysql_query($sql);
$i = 0;
while($row = mysql_fetch_assoc($query)) {
if($i % 5 == 0)
echo '<div class="single first">';
else if($i % 5 == 4)
echo '<div class="single last">';
else
echo '<div class="single">';
echo '<img src="'.$row['image'].'" alt="'.$row['title'].' " />';
echo '</div>';
$i++;
}
How about this:
$index = 0;
while($row = mysql_fetch_assoc($query)) {
$classes = 'single';
switch ($index % 5) {
case 0:
$classes .= ' first';
break;
case 4:
$classes .= ' last';
break;
}
echo <<<HTML
<div class="$classes">
<img src="{$row['image']}" alt="{$row['title']}" />
</div>;
HTML;
$index++;
}
As a sidenote, have you considered using CSS nth-child property instead?

Categories