Updating DB with AJAX and PHP using checkboxes without a form - php

I have a table in which the last cell is a bit value. When new data is inserted, the bit is automatically set to 1. I used PHP to display the contents of the table, in <table> form, wherein the last cell contains a checkbox. I didn't surround these checkboxes in <form></form> tags, they're just <input ... /> with name="stat[]." I used an array for the name so that PHP knows that $_POST['stat'] will be an array containing all the inputs.
One or more checkboxes can be checked and submitted to update the bit value to 0.
Questions:
Do I have to use <form> tags for this? The AJAX isn't working.
Can the <button> element be assigned a method and action?
HTML Button. Notice there is no form here.
<input type="submit" id="updateList" type="button" method="post" action="classes/requests/updateList.php" value="update list" />
jQuery and AJAX
$('input#updateList').on('click', function (e) {
e.preventDefault();
var open = 'yes';
if ($('.update:checked').length <= 0) {
$('.fade_bg').fadeIn(200);
$('#updateStat').slideDown(600);
$('span#stat2').fadeIn(400).text('You must make a selection');
$('a#closeBox2').show();
return false;
}
else {
$('.update').each(function (index) {
var chckd = $('#chck' + index).val();
open = 'no';
$.ajax ({
type: 'post',
url: 'classes/requests/updateList.php',
data: {
stat: chckd
},
success: function(data) {
if (data === 'updated') {
alert(data);
// $('.fade_bg').fadeIn(200);
// $('#reqStat').slideDown(600);
// $('span#stat').fadeIn(400).text('Thank you. Your request has been submitted.');
// $('a#successClose').show();
}
else {
$('span#stat').fadeIn(400).text('There was an error in submitting your request');
$('a#closeBox').show();
return false;
}
}
});
});
}
});
PHP for rendering the HTML list
include('../dbconnect.php');
$closed = 'no';
$pdo = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_password);
$stmt = $pdo->prepare("SELECT RequestID, DateAdded, Graphic1Desc, Graphic2Desc, Graphic3Desc, ColorChart, Hex1, Hex2, Hex3, Hex4, Hex5, Hex6, Hex7, Hex8 FROM GraphicsRequest WHERE fulfilled = :done AND RequestID > 0");
print '<table id="pendingReqs">';
print '<tr id="headers">
<td>Date</td>
<td>Gr. 1</td>
<td>Gr. 2</td>
<td>Gr. 3</td>
<td>Colors?</td>
<td>HEX Vals 1-8</td>
<td>Done</td>
</tr>';
$stmt->bindParam(':done', $closed);
for ($r = 0; $r <= $stmt->rowCount(); $r++) {
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$id = $row[$r]['RequestID'];
$date = $row[$r]['DateAdded'];
$d1 = $row[$r]['Graphic1Desc'];
$d2 = $row[$r]['Graphic2Desc'];
$d3 = $row[$r]['Graphic3Desc'];
$chart = $row[$r]['ColorChart'];
$h1 = $row[$r]['Hex1'];
$h2 = $row[$r]['Hex2'];
$h3 = $row[$r]['Hex3'];
$h4 = $row[$r]['Hex4'];
$h5 = $row[$r]['Hex5'];
$h6 = $row[$r]['Hex6'];
$h7 = $row[$r]['Hex7'];
$h8 = $row[$r]['Hex8'];
print '<tr>
<td>' . $date . '</td>
<td class="desc">' . $d1 . '</td>
<td class="desc">' . $d2 . '</td>
<td class="desc">' . $d3 . '</td>
<td>' . $chart . '</td>
<td>'
. $h1 . ', '
. $h2 . ',<br />'
. $h3 . ', '
. $h4 . ',<br />'
. $h5 . ', '
. $h6 . ',<br />'
. $h7 . ', '
. $h8 . '<br /></td>
<td><input type="checkbox" class="update" name="stat[]" id="chk' . $id . '"/></td></tr>';
}
print '</table>';
print $id;
PHP for updating the list
function updateStatus() {
include('../../../dbconnect.php');
$updated = false;
$open = 'yes';
$id = 0;
try {
$pdo = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_password);
$stat = $pdo->prepare('SELECT RequestID FROM GraphicsRequest WHERE fulfilled = :open');
$stat->bindParam(':open', $open);
$_POST['stat'] = array();
for ($r = 0; $r <= $stat->rowCount(); $r++) {
$stat->execute();
$row = $stat->fetchAll(PDO::FETCH_ASSOC);
$id = $_POST['stat'][$row[$r]['RequestID']];
if (ISSET($_POST['stat[' . $id . ']'])) {
$open = 'no';
$stmt = $pdo->prepare('UPDATE GraphicsRequest SET fulfilled = :open');
$stmt->bindParam(':open', $open);
$stmt->execute();
$pdo = null;
if ($stmt->rowCount() == 0)
echo('rowCount = 0');
else
$updated = true;
return $updated;
}
}
}
catch (PDOException $err){
echo $e->getMessage();
return $updated;
}
}

I haven't checked all of your source code, but it is absolutely possible to use AJAX to send some data to the server without the need of <form> tag. Using a form makes it only a lot easier to receive all "form values" at once.

Related

making php on-input search but jquery $.ajax and $.post not working

i am trying to make a live search box using ajax using the following code but its not working. When i echo "hello"; from the php file and remove everything else it just echos it out on the screen and does not work, no errors or return values, leading me to believe it has to do with my jquery code but i am not sure.
jquery:
$("#search").keyup(function(){
var value = $("#search").val();
$.post(walldb.php, {value: value}, function(data){
console.log(data);
})
});
heres the php:
<?php
$arr = [];
$searchq = "%{$_POST['value']}%";
$stmt = $pdo->prepare("SELECT * FROM walldb WHERE wallname LIKE :s");
$stmt->bindParam(':s',$searchq);
$result=$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$mlink = $row['mainlink'];
$tlink = $row['thumbnail'];
$dlink = $row['download'];
$info = $row['info'];
$val = $row['wallname'];
$arr[] = '<li>' . "" . "<span>" . "$val" . "</span><img class='searchbutton1 s1' src='/images/info.png'>" . '<br>' . "<a id='wall1.download' href=" . "$dlink" . "><img class='searchbutton2' src='/images/download.png'></a>" . '<br>' . "<ul class='searchmenu menu1'><p>" . "$info" . "</p>
</ul>" . '</li>';
}
$final = '<ul>' . implode('', $arr) . '</ul>';
echo $final; //just echos everything on the screen :(
?>
html:
<form action= "" method= "post">
<img id="glass" src="/images/search.png" type= "submit" name="submit-search"><input id="search" name="search-input" type="search" placeholder="Search By Name" autocomplete="off"><img id="cancle" src="/images/cancle.png">
</form>
i would also appreciate some help on making the whole thing work making it search on input since i am very new to pdo/php.
i fixed this issue by using generic javascript XMLHttpRequest, jquery never worked for me and i have no idea why. I would love to receive some insight as to why my below solution works and the jquery version does not (i am using the latest version of jquery).
javascript:
$("#search").keyup(function () {
var http = new XMLHttpRequest();
var value = $("#search").val();
http.open("POST", 'walldb.php', true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onload = function () {
if (this.status == 200) {
$("#result").html(this.responseText);
}
}
http.send("value=" + value);
});
php:
<?php
$arr = [];
$searchq = "%{$_POST['value']}%";
$stmt = $pdo->prepare("SELECT * FROM walldb WHERE wallname LIKE :searchq");
$stmt->bindParam(':searchq',$searchq);
$result=$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$mlink = $row['mainlink'];
$tlink = $row['thumbnail'];
$dlink = $row['download'];
$info = $row['info'];
$val = $row['wallname'];
$arr[] = '<li>' . "" . "<span>" . "$val" . "</span><img class='searchbutton1 s1' src='/images/info.png'>" . '<br>' . "<a id='wall1.download' href=" . "$dlink" . "><img class='searchbutton2' src='/images/download.png'></a>" . '<br>' . "<ul class='searchmenu menu1'><p>" . "$info" . "</p>
</ul>" . '</li>';
}
$final = '<ul>' . implode('', $arr) . '</ul>';
if (isset($_POST['value'])) { //added this
echo $final;
}
?>
Try to correct that:
$stmt = $pdo->prepare('SELECT * FROM walldb WHERE wallname LIKE ?');
$stmt->execute([$searchq]);
to
$searchq = '%' .$_POST['value']. '%'; //edited
$stmt = $pdo->prepare('SELECT * FROM walldb WHERE wallname LIKE ?');
$stmt->bind_param('s', $searchq);
$stmt->execute();
while($row= $stmt->fetch_assoc()){
Or PDO
$searchq = '%' .$_POST['value']. '%'; //edited
$stmt= $pdo->prepare('SELECT * FROM walldb WHERE wallname LIKE :searchq');
$stmt->bindParam(':searchq', $searchq, PDO::PARAM_STR);
$stmt->execute();
while($row= $stmt->fetch_assoc()){

php return stops the loop

good day I write a function where I want to display the records which will match on the dates last week but it only loop one time. Is there a way to return all the dates and show all the records that will match with the dates? Here is my code.
function fetch_week(){
$today = date('F d Y');
for($i = 1; $i <= 7; $i++)
{
$repeat = strtotime("-1 day",strtotime($today));
$today = date('F d Y',$repeat);
$output = '';
$conn = mysqli_connect("localhost", "root", "", "sample");
$sql = "SELECT * FROM list WHERE datee = '".$today."' ORDER BY id DESC";
$result = mysqli_query($conn, $sql);
if(empty(mysqli_num_rows($result))){
echo '<td colspan="6"><h5><center>NO RECORDS.</center></h5></td>';
}
else{
while($row = mysqli_fetch_assoc($result)){
$output .= '<tbody id="appTable">
<tr class="content" style="font-weight: normal text-align: center">
<td>'.$row["name"].'</td>
<td>'.$row["address"].'</td>
<td>'.$row["contact"].'</td>
<td>'.$row["datee"].'</td>
</tr>
</tbody>
';
}
return $output;
}
}
}
You can create an array and return that after your loop ends. Check below code:
function fetch_week() {
$today = date('F d Y');
$response = [];
for ($i = 1; $i <= 7; $i++) {
$repeat = strtotime("-1 day", strtotime($today));
$today = date('F d Y', $repeat);
$output = '';
$conn = mysqli_connect("localhost", "root", "", "sample");
$sql = "SELECT * FROM list WHERE datee = '" . $today . "' ORDER BY id DESC";
$result = mysqli_query($conn, $sql);
if (empty(mysqli_num_rows($result))) {
echo '<td colspan="6"><h5><center>NO RECORDS.</center></h5></td>';
} else {
$output = '<tbody id="appTable">';
while ($row = mysqli_fetch_assoc($result)) {
$output .= '<tr class="content" style="font-weight: normal text-align: center">
<td>' . $row["name"] . '</td>
<td>' . $row["address"] . '</td>
<td>' . $row["contact"] . '</td>
<td>' . $row["datee"] . '</td>
</tr>';
}
$output .= '</tbody>';
$response[] = $output;
}
}
return $response;
}
You need to loop through on output to print your data. But apart from all these, your code is widely open for SQL injection. Please be careful and do changes for that. Also you don't need to create tbody again and again in loop. You can do that first time only which I have changed in above code as well.
Hope it helps you.

PHP if statement - Resource id issue

I have some code below which retrieves data from a table named "tally_point"
What I am trying to is retrieve a value from a column named 'tpt_id'
On another table, there is a table named "tally_point_type", which has has the primary key 'tpt_id' as well.
What I am trying to do is get the 'tpt_name' value to print from the tally_point_type row. At the moment I can get the "Order Details" link to work but the $tpt_name value prints out a Resource id# value.
I knwo Im close but can't quite figure out how to get this to work.
<?php
$pointstype = $row['tpt_id'];
$type = '<td align="center">';
if($pointstype > '0') {
$query = "SELECT tpt_name
FROM tally_point_type
WHERE'" . $row['tpt_id'] . "'=$pointstype";
$tpt_name = mysql_query($query);
$type .='<strong>' . $tpt_name . '</strong></td></tr>';
}
else {
$type .='<strong>Order Details</strong></td></tr>';
}
echo $type;
?>
Full code here:
<?php # index.php
require_once ('./includes/config.inc.php');
$page_title = 'Title';
include ('includes/header.html');
if (!isset($_SESSION['admin_int_id'])) {
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
// Check for a trailing slash.
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1); // Chop off the slash.
}
$url .= '/login.php';
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) )
{ // Accessed through view_users.php
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) )
{ // Form has been submitted.
$id = $_POST['id'];
} else { // No valid ID, kill the script.
echo '<h1 id="mainhead">Page Error</h1>
<p class="error">This page has been accessed in error.</p><p><br /><br /></p>';
include ('./includes/header.html');
exit();
}
require_once ('/database.php'); // Connect to the db.
$display = 1000;
if (isset($_GET['np'])) { // Already been determined.
$num_pages = $_GET['np'];
} else { // Need to determine.
$query = "SELECT COUNT(*) FROM tally_point, users WHERE tally_point.users_id = users.users_id ORDER BY tally_points_entry_date DESC";
$result = #mysql_query ($query);
$row = #mysql_fetch_array ($result, MYSQL_NUM);
$num_records = $row[0];
if ($num_records > $display) { // More than 1 page.
$num_pages = ceil($num_records/$display);
} else {
$num_pages = 1;
}
}
if (isset($_GET['s'])) {
$start = $_GET['s'];
} else {
$start = 0;
}
$link1 = "{$_SERVER['PHP_SELF']}?sort=lna";
$link2 = "{$_SERVER['PHP_SELF']}?sort=fna";
$link3 = "{$_SERVER['PHP_SELF']}?sort=dra";
if (isset($_GET['sort'])) {
switch ($_GET['sort']) {
case 'lna':
$order_by = 'tally_points_in ASC';
$link1 = "{$_SERVER['PHP_SELF']}?sort=lnd";
break;
case 'lnd':
$order_by = 'tally_points_in DESC';
$link1 = "{$_SERVER['PHP_SELF']}?sort=lna";
break;
case 'fna':
$order_by = 'total ASC';
$link2 = "{$_SERVER['PHP_SELF']}?sort=fnd";
break;
case 'fnd':
$order_by = 'total DESC';
$link2 = "{$_SERVER['PHP_SELF']}?sort=fna";
break;
case 'dra':
$order_by = 'tally_points_entry_date ASC';
$link3 = "{$_SERVER['PHP_SELF']}?sort=drd";
break;
case 'drd':
$order_by = 'tally_points_entry_date DESC';
$link3 = "{$_SERVER['PHP_SELF']}?sort=dra";
break;
default:
$order_by = 'tally_points_entry_date DESC';
break;
}
$sort = $_GET['sort'];
} else { // Use the default sorting order.
$order_by = 'tally_points_entry_date DESC';
$sort = 'dra';
}
$query = "SELECT ta.tally_points_in, ta.order_id, ta.total, ta.tpt_id , DATE_FORMAT(ta.tally_points_entry_date, '%d-%m-%Y') AS dr, ta.users_id
FROM tally_point AS ta
WHERE ta.users_id=$id
ORDER BY
".$order_by." LIMIT ".$start.", ".$display;
$result = #mysql_query ($query); // Run the query.
echo '
<table width="500" cellspacing="1" cellpadding="7">
<tr class="top">
<td align="left"><b>Date</b></td>
<td align="center"><b>Credit</b></td>
<td align="center"><b>Debit</b></td>
<td align="center"><b>Description</b></td>
</tr>
';
$bg = '#ffffff'; // Set the background color.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$pointsitem = $row['order_id'];
$pointstype = $row['tpt_id'];
$bg = ($bg=='#eaeced' ? '#ffffff' : '#eaeced'); // Switch the background color.
//$entries = floor($row['ltd_entry_amount']/200);
echo '<tr bgcolor="' . $bg . '">';
echo '<td align="left">' . $row['dr'] . '</td>';
echo '<td align="center"><strong>' . $row['tally_points_in'] . '</strong></td> ';
echo '<td align="center">' . $row['total'] . '</td>';
$type = '<td align="center">';
if($pointstype > '0') {
$query = "SELECT tpt_name
FROM tally_point_type
WHERE'" . $row['tpt_id'] . "'=$pointstype"; //THIS ALSO SEEMS WRONG column name should have backticks if you're trying to escape it and maybe value should be quoted? Also these values are the same, no?
$result = mysql_query($query);
$tpt_name = mysql_fetch_assoc($result);
$type .='<strong>' . $tpt_name['tpt_name'] . '</strong></td></tr>';
} else {
$type .='<strong>Order Details</strong></td></tr>';
}
echo $type;
}
echo '</table>';
mysql_free_result ($result); // Free up the resources.
mysql_close(); // Close the database connection.
if ($num_pages > 1) {
echo '<br /><p>';
$current_page = ($start/$display) + 1;
if ($current_page != 1) {
echo '<a href="view_points_2.php?s=' . ($start - $display) . '&np=' .
$num_pages . '&sort=' . $sort .'">Previous</a> ';
}
for ($i = 1; $i <= $num_pages; $i++) {
if ($i != $current_page) {
echo '<a href="view_points_2.php?s=' . (($display * ($i - 1))) .
'&np=' . $num_pages . '&sort=' . $sort .'">' . $i . '</a> ';
} else {
echo $i . ' ';
}
}
if ($current_page != $num_pages) {
echo '<a href="view_points_2.php?s=' . ($start + $display) . '&np=' .
$num_pages . '&sort=' . $sort .'">Next</a> ';
}
echo '</p>';
}
include ('./includes/footer.html'); // Include the HTML footer.
?>
You need to fetch the result.
<?php
$pointstype = $row['tpt_id'];
$type = '<td align="center">';
if($pointstype > '0') {
$query = "SELECT tpt_name
FROM tally_point_type
WHERE'" . $row['tpt_id'] . "'=$pointstype"; //THIS ALSO SEEMS WRONG column name should have backticks if you're trying to escape it and maybe value should be quoted? Also these values are the same, no?
$result = mysql_query($query);
$tpt_name = mysql_fetch_assoc($result);
$type .='<strong>' . $tpt_name['tpt_name'] . '</strong></td></tr>';
} else {
$type .='<strong>Order Details</strong></td></tr>';
}
echo $type;
?>
Also see notes in the comment of your query, consider switching drivers to mysqli or PDO, and I'm not sure about where the data you're using is coming from but might be open to a SQL injection. How can I prevent SQL injection in PHP?
Here's the manual link for future reference http://php.net/manual/en/function.mysql-query.php. See example #2.
You need to fetch the result:
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$tpt_name = $row['tpt_name'];

PHP and select in loop

I have a PHP page where its querying data from the database and putting it in a table. The first column is where I would like the user to assign a person to that row. I was able to do that successfully (the select in a loop) but now I'm having a problem when its getting pushed out to the other page.
Below is the first page:
$sql = "SELECT * FROM meetingDump WHERE Meeting_ID IN ($Series)";
$rs=odbc_exec($conn,$sql);
while($row = odbc_fetch_array($rs))
{
$ID = odbc_result($rs,"ID");
$Meeting_ID = odbc_result($rs,"Meeting_ID");
$Title = odbc_result($rs,"Title");
$StartTime = odbc_result($rs,"StartTime");
$EndTime = odbc_result($rs,"EndTime");
$Organizer = odbc_result($rs,"Organizer");
echo '<tr>
<td>';
{
$box1 = array();
$result1 = "SELECT FullName FROM User";
$rs1=odbc_exec($connu,$result1);
while($row = odbc_fetch_array($rs1)) { $box1[] = $row; }
}
/* Generate select box contents */
$AssignedTo = '<select name="AssignedTo[]" onchange="autoSubmit()">';
$AssignedTo .= '<option selected="selected">---< Select Engineer >---</option>';
if (!empty($box1)) {
foreach ($box1 as $k => $v) {
$AssignedTo .= '<option value="'.$v['FullName'].'">'.$v['FullName'].'</option>';
}
}
$AssignedTo .= '</select>';
/* Output */
echo $AssignedTo;
echo '
</td>
<input name="AssignedID[]" type="hidden" value="' . $ID . '" />
<td>' . $Meeting_ID . '</td>
<td>' . $Title . '</td>
<td>' . $StartTime . '</td>
<td>' . $EndTime . '</td>
<td>' . $Organizer . '</td>';
}
Now for the second page I currently have:
foreach($_POST['AssignedTo'] as $AssignedTo)
{
echo '<br>' . $AssignedTo;
}
That gets me all the selected names, which is perfect, but I'm trying to correlate the assignedTo field with the meeting_id field.
Any ideas?
UPDATE:
The comment from AeroX helped me figure it out!
$AssignedID = $_POST['AssignedID'];
$AssignedTo = $_POST['AssignedTo'];
foreach ($AssignedID as $Key => $value)
{
echo $AssignedID[$Key] .' '. $AssignedTo[$Key];
echo '<br>';
}
In your example, because of the way the POST variables $_POST['AssignedID'] and $_POST['AssignedTo'] will be populated you can just pull the Value from each Array where they both have matching Keys. This will then give you the related records.
Something like the below should work for you:
$AssignedID = $_POST['AssignedID'];
$AssignedTo = $_POST['AssignedTo'];
foreach(array_keys($AssignedID) as $Key)
{
echo $AssignedID[$Key];
echo $AssignedTo[$Key];
}

How do I output my data in a threaded way based on parent ID?

I have a forum that students are posting in. If the student responds to the main post, the postId is set to 0. If a student replies to another student's post, the postId is set to the replyId of the student's original post.
I am trying to write some PHP that will essentially create a new table for each post, with the exception of if a postid is set to a reply Id, then create a new row in that table.
I have the SQL laid out in SQLFiddle which can be found here:
http://sqlfiddle.com/#!2/611e2d/5
Using this example, what I'm looking for is replyid one to be put in a new html table, with response ID 3 in a new row underneath that. Then with ReplyId 2, would create a new html table.
This is just a basic threaded forum view of responses.
Thank you!
[code]
$i = 0;
$aR = 0;
$currentPost = '';
if(mysql_num_rows($getResponses) > 0)
{
while($respData = mysql_fetch_array($getResponses))
{
if(($respData['postId'] != $currentPost))
{
if($i!=0)
{
echo '</table><br /><br />';
}
echo '<table width = "875px" cellspacing = "0" cellpadding = "0" border = "0">';
$i=0;
}
$currentPost = $respData['postId'];
$color_A = 'class="altRow1"';
$color_B = 'class="altRow2"';
$altRowColor = ($aR % 2) ? $color_A : $color_B;
$studentName = getStudents($respData['userId']);
$studentName = explode(" ", $studentName);
$studentFirstName = $studentName[0];
echo '<tr ' . $altRowColor . '>
<td align="center" width = "225px" class="forumTopic"><img src="images/'.getStudentPics($respData['userId']).'.png" /><br />Posted By ' . getStudents($respData['userId']) . '<br />on '.date("m/d/Y h:i a", strtotime($respData['responseDate'])) . '</td>
<td width = "650px" class="forumTopic">' . $respData['replyText'] . '</td>
</tr>
<tr ' . $altRowColor . '>
<td class="forumTopic" colspan = "2" align="center"><span class="topicLinkStyle">Reply to '.$studentFirstName .'</span></td>
</tr>';
$i++;
$aR++;
}
echo '</table><br /><br />';
}
Here is a very simple example you can then make your own CSS to format the HTML anyway you want you can even use that link I posted on your comment as example.
The buildTree will order the replies properly in a tree manner for easy later usage and the printTree will print it recursively.
<?php
// Your database info
$db_host = '';
$db_user = '';
$db_pass = '';
$db_name = '';
if (!isset($_GET['topic_id']))
{
die('No topic id was given.');
}
$con = new PDO("mysql:host={$db_host};dbname={$db_name}", $db_user, $db_pass);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT replyId,
topicId,
postId,
replyText,
responseDate,
userId
FROM forumResponses
WHERE topicId = ?
ORDER BY replyId";
$result = $con->prepare($sql);
$result->bindParam(1, $_GET['topic_id'], PDO::PARAM_INT);
$result->execute();
if ($result->rowCount() == 0)
{
die('No messages found...');
}
$threads = array();
while($row = $result->fetchALL(PDO::FETCH_ASSOC))
{
$threads = $row;
}
$data = buildTree($threads);
$con = NULL;
function buildTree($ar, $pid = NULL) {
$op = array();
foreach($ar as $item)
{
if($item['postId'] == $pid)
{
$op[$item['replyId']] = array(
'replyText' => $item['replyText'],
'userId' => $item['userId'],
'responseDate' => $item['responseDate'],
'parentId' => $item['postId']
);
// using recursion
$children = buildTree($ar, $item['replyId']);
if($children)
{
$op[$item['replyId']]['children'] = $children;
}
}
}
return $op;
}
function printTree($ar)
{
foreach ($ar as $reply)
{
?>
<li>
<div>
<header>userId <?php echo $reply['userId']; ?> - <?php echo $reply['responseDate']; ?></header>
<?php echo $reply['replyText']; ?>
</div>
<?php
if (isset($reply['children']) && count($reply['children']) > 0)
{
echo " <ul>\n";
printTree($reply['children']);
echo " </ul>\n";
}
echo " </li>\n";
}
}
?>
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Threaded Comments Block</title>
</head>
<body>
<div>
<h1>Reading Topic <?php echo $_GET['topic_id']; ?></h1>
<div>
<ul>
<?php
printTree($data);
?>
</ul>
</div>
</div>
</body>
</html>
NOTE: The above code is merely to show you an example of how store the result in a threaded manner as well as to print it, you will have to make your own out of this example.
I think it will be better to reconstruct the table for that..hmm here is my suggestion
Table Post (suggested main table for responses of a topic)
Fields:
postId, topicId(topic where this post belongs), responseId(this will be the postId of the post if this post is a reply, set to 0 if main post),

Categories