1

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'>&nbsp;</div><span class='up_votes'>0</span>
            </div>
            <div class='voting_btn'>
                <div class='down_button'>&nbsp;</div><span class='down_votes'>0</span>
            </div>
             <br>
        </div>


        </div>
        </div>
</div>";

}
 }else {
     echo "0 results";
}

$conn->close();
?> 
4
  • 1
    Use if($nr%3 == 0) then add next row otherwise create 3 columns. Commented Apr 29, 2016 at 10:36
  • Please use PHP html friendly syntax. Commented Apr 29, 2016 at 10:39
  • provide the html format you want Commented Apr 29, 2016 at 10:40
  • Possible duplicate of PHP and MySQL: Number of rows returned Commented Apr 29, 2016 at 10:41

7 Answers 7

1

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'>&nbsp;</div>";
        $output .="<span class='up_votes'>0</span>";
        $output .="</div>";
        $output .="<div class='voting_btn'>";
        $output .="<div class='down_button'>&nbsp;</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...

Sign up to request clarification or add additional context in comments.

12 Comments

Thanks! It helped very much.
@Thun Could you, please, mark the Question as complete or at least flag it as helpful? It might be beneficial to someone else...
just one more question. is is to much space beteen the $row["author"] and {$row["quote"]}. How do i make it more compact?
@Thun Just wrap the Values in PHP trim function like so: trim({$row["author"]}) and trim({$row["quote"]}). Trim removes extra white-spaces both before & and after a String. Thus " peace " would become "peace" when run through trim()
Great! but how do i wrap it within the html code part. When i write the function it just shows trim( data here)?Do i need to wrap it {trim({$row["author"]})}?
|
0

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'>&nbsp;</div><span class='up_votes'>0</span>
            </div>
            <div class='voting_btn'>
                <div class='down_button'>&nbsp;</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();
?> 

Comments

0

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

Comments

0

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

Comments

0

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

Comments

0

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'>&nbsp;</div><span class='up_votes'>0</span>
            </div>
            <div class='voting_btn'>
                <div class='down_button'>&nbsp;</div><span class='down_votes'>0</span>
            </div>
            <br />
        </div>
        </div>
        </div>";
    }

    echo "</div>\n";
    $rows = null;
}

if ($nr == 0){
   echo "0 results";
}
?>

Comments

0

Try this

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

    ?><td>your data</td><?
}
?></tr></table><?

2 Comments

Code only answers are not terribly useful because they don't explain what the problem was, and why/how the code solves it. Adding an explanation to this would be helpful.
please provide some explanation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.