Jeff
Jeff

Reputation: 2068

Uploading data from database through php

The problem is uploading announcements as a div element. I looked for a way to do this through jQuery however I have very little knowledge in jQuery so I couldn't find a solution. I did find a solution through PHP which works, however it's not very elegant and I feel there is a better way to do this.

Here is the code (announcements.php):

<?php
$sql = $link->prepare('SELECT content, dateset FROM announcements WHERE email=":email"');
$sql->bindParam(':email', $_SESSION['email']);
$sql->execute();
$row = $sql->fetchAll(PDO::FETCH_ASSOC);
foreach ($row as $r) {
    echo '<div class="announcement"><div class="announcementTopBar"><div class="announcementPic"><img src="smiley.png" alt="pic" width="25" height="25" /></div><span>Some Dude</span></div><div id="announcementContent"><span>';
    foreach ($r as $data) {
        echo $data;
    }
    echo '</span></div></div>';
}
?>

HTML file:

<div id="somediv">
    <?php include("announcements.php"); ?>
</div>

Is there any other method I can use? Is this solution (with some refining) sufficient?

Upvotes: 3

Views: 129

Answers (2)

Knight Rider
Knight Rider

Reputation: 188

I can see here that you are creating nested tags with specific classes, tag and displaying data between them. This can be achieved through jquery also by creating tags , adding classes to them and appending it to their respective parent into the hierarchy.

var x =  $("<div></div>").addClass("className");

$("#parentDiv").append(x);

For getting the data from the server AJAX Call is always a better option which is an Async call (can be changed).

For AJAX call read here POST AJAX REQUEST

Upvotes: 0

scrowler
scrowler

Reputation: 24406

There's nothing wrong with your solution. The other alternative is to use an AJAX call to retrieve the data, and use Javascript to append it to the DOM.

Reasons to use PHP:

  • Not all browsers support Javascript, and you can turn Javascript off
  • Consistent output of your data at all times

Reasons to use AJAX:

  • If you want new data to be added to your page without having to refresh the page. E.g.:
    • A "click here to load" button loading the content without refreshing the page
    • Automatically adding new content to a page at intervals (like Facebook's news feed)
    • Removing or editing data in the same way

Note: the only error I can see in your code is that you're defining an element with the ID announcementContent within your loop - HTML specs only allow one instance of an ID in the DOM. You should use a class here instead which are meant to be used for (potentially) multiple instances of an element.

Upvotes: 4

Related Questions