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();
?> 
Thun
  • 27
  • 1
  • 9

7 Answers7

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

Poiz
  • 7,611
  • 2
  • 15
  • 17
  • Thanks! It helped very much. – Thun Apr 30 '16 at 10:34
  • @Thun Could you, please, mark the Question as complete or at least flag it as helpful? It might be beneficial to someone else... – Poiz Apr 30 '16 at 14:46
  • just one more question. is is to much space beteen the $row["author"] and {$row["quote"]}. How do i make it more compact? – Thun May 02 '16 at 09:46
  • @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() – Poiz May 02 '16 at 11:49
  • 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"]})}? – Thun May 03 '16 at 07:17
  • I just updated the code right now so check that Part. If the code works for you; you may want to indicate the relevance by up-voting the answer ;-) – Poiz May 03 '16 at 07:34
  • Thanks, but i copy your updated code but it still som white spaces. Its like when you hit enter an extra time. Can it be something in my database? – Thun May 04 '16 at 12:49
  • Could you just simply manually check your Database - using phpMyAdmin or mysql Workbench, perhaps...? Since we are getting these values from the DB; the spaces could be coming from the DB as well because **trim()** should trim-off all spaces before and after the Strings.... Let me know what you find, K? – Poiz May 04 '16 at 13:41
  • I'v been looking for some issues in the phpMyadmin but cant find anything. When i mark my website with the mouse i see one empty row for each object (topic, author...) also much white space between. Is there common for phpMyAdmin to add space like this? – Thun May 16 '16 at 11:46
  • The White-Space is coming from your Heredoc. You can strip them and everything will be fine. It has nothing to do with phpMyadmin.... – Poiz May 16 '16 at 12:34
  • @Thun The Heredoc is now removed and the Code updated... Try the new, updated version..... Cheers & Good Luck... ;-) – Poiz May 16 '16 at 12:41
  • Dont know if i should make a new question. But is it easy to implement a pagnation with limit to 20 into this setup? – Thun May 19 '16 at 13:15
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
  }
}
MarcoS
  • 17,323
  • 24
  • 96
  • 174
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();
?> 
Asheesh
  • 161
  • 3
  • 16
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";
}
?>
Community
  • 1
  • 1
Luiz Vaz
  • 1,669
  • 1
  • 19
  • 32
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>';
}
Jobz
  • 424
  • 1
  • 4
  • 13
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><?
Prog Sspl
  • 9
  • 2
0

Try this

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

    ?><td>your data</td><?
}
?></tr></table><?
Mostafiz
  • 7,243
  • 3
  • 28
  • 42