1

JSFiddle here, with unfunctionaing PHP obviously, but on the local host it pulls through the information just fine.

I am trying to append data in a loop into a specific set of tags, inside a di of a certain class.

For example, for every row in the the table, add a div with the class "card" and append "Title" into a H2, "description" into a P tag etc.

Anyone know how I could go about doing this? I'm googling but finding it hard to phrase my question right.

Div "Card" markup:

<div class="card">
  <h2>Health and Wellbeing</h2>
  <p>Sometimes you just did too much sitting not enough jumping go go go.</p>
</div> 

PHP pull:

$sql = "SELECT title, description, count FROM relevant_topics";
    $result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<b>Title: </b>" . $row["title"]. " - Description: " . $row["description"]. " " . $row["count"]. "<br>"; 
}
} else {
echo "0 results";
}
ladanta
  • 459
  • 2
  • 6
  • 18

2 Answers2

2

You can echo the div markup into the PHP code like this:

while($row = $result->fetch_assoc()) {
echo'<div class="card">
         <h2>'.$row["title"].'</h2>
         <p>'.$row["description"].'
     </div>';
}

Not sure where you want the Row['count'] though.

Also you might wanna use PDO instead of mysql, Since mysql is outdated: How can I prevent SQL injection in PHP?

Community
  • 1
  • 1
  • Quick question, if I have a column called "class" with things like "green and "red" in the different rows, how do I addthis to the divs classname? I've tried this, but keep getting – ladanta Mar 09 '15 at 11:43
  • Quick question, if I have a column called "class" with things like "green and "red" in the different rows, how do I addthis to the divs classname? I've tried this, but keep getting " unexpected '$class' (T_VARIABLE), expecting ',' or ';' " Turns out I can't paste code here, oops. – ladanta Mar 09 '15 at 11:43
  • I don't understand your question. can u create a JSFiddle for me? So i can see the code :) –  Mar 09 '15 at 12:34
  • Oh maybe I understand. Try this: `echo'
    ';` Note that with the `'` you will be opening and closing the echo. The `"` is purely for the CSS styling. The `.` is actually just a `+`
    –  Mar 09 '15 at 12:50
  • Figured it out :) ANd it was also exactly what you said, thanks a lot :) – ladanta Mar 09 '15 at 14:01
1

check this

if ($result->num_rows > 0) {

// output data of each row
while($row = $result-> mysql_fetch_array()) {//if not works change mysql_fetch_array() to fetch_assoc()
    echo'<div class="card"><h2>';
    echo '.$row["title"].';
    echo '</h2><p>';
    echo '.$row["description"].';
    echo '</P></div>'; 

} 
Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85