Retrieving Mysql data and print in specific order - php

I got a problem that driving me crazy for last 4 or 5 days.I'm building a facebook style posting system,where users can post on their timeline and friends of that user can comment on every specific post.I'm actually having problem to print that correctly in php.Your help would be greatly appreciated.Thanks a lot in advance for your time.
The 'status' table that I created for all the post contain following values
id osid author type data postdate
1 1 helal a Hi... 2014-08-20
2 1 Abdul b Hey.. 2014-08-20
3 1 helal b Good.. "
4 4 helal a Hello.. "
5 4 Irin b Hi... "
so,basically,all new posts are having type 'a' and all replies are having type 'b'.And also,all separate conversation(post and replies) is having same 'osid',so that user can see separate conversation on separate div with a comment box attached to each post(followed by conversation)
I coded the following code,but it's not giving me expected result.
$sql="SELECT * FROM status WHERE type='a'";
$query=mysqli_query($connect_dude,$sql);
$numrow=mysqli_num_rows($query);
if($numrow>0){
while($row=mysqli_fetch_assoc($query)){
$id=$row["id"];
$osid=$row["osid"];
$name=$row["author"];
$data=$row["data"];
$date=$row["postdate"];
$query_replies = mysqli_query($connect_dude, "SELECT * FROM status WHERE type='b' AND osid='$id' ");
$replynumrows = mysqli_num_rows($query_replies);
if($replynumrows > 0){
while ($row2 = mysqli_fetch_assoc($query_replies) ) {
$statusreplyid = $row2["id"];
$statusreplyosid = $row2["osid"];
$replyauthor = $row2["author"];
$replydata = $row2["data"];
$replydata = nl2br($replydata);
$replypostdate = $row2["postdate"];
$replydata = str_replace("&","&",$replydata);
$replydata = stripslashes($replydata);
$status_replies .= '<div id="reply_'.$statusreplyid.'" class="reply_boxes"><div><b>Reply by '.$replyauthor.' '.$replypostdate.':</b><br />'.$replydata.'</div></div>';
}
}
$statuslist .= '<div id="status_'.$id.'" class="status_boxes"><div><b>Posted by '.$name.' '.$date.':</b> '.$statusDeleteButton.' <br />'.$data.'</div>'.$status_replies.'</div>';
if($logged == $username){
$statuslist .= '<form id="posting1" action="user.php?u='.$logged.'" method="post" enctype="multipart/form-data"><textarea id="replytext" name="replytext" class="replytext" placeholder="write a comment here '.$osid.'"></textarea><input id="hel1" name="hel1" type="hidden" value="'.$osid.'"><input type="submit" id="replyBtn" name="replyBtn" value="reply"></form>';
}
}
$postbox="<form id='posting' action='user.php?u=$logged' method='post' enctype='multipart/form-data'><input id='hid' name='hid' type='hidden' value='<?php echo $iid;?>' ><textarea id='taxi' name='taxi' rows='15' cols='40' placeholder='Say something to your Buddies'></textarea></br><input id='hel' name='hel' type='submit' value='post'></form>";
}
}
and I have used echoed '$statuslist' on html part.
It keeps compounding all replies within all the post.
Desired form of result,let say
For post no 1
helal:Hi...
Abdul:hello...
helal:Good....
"then the comment box(reply text area)"
For post no 2
helal:Hello...
Irin:Hi...
"then the comment box(reply text area)"
so on and so forth within separate divs for separate conversation

I'd say you need to reset $status_replies in the outer loop. Add:
$status_replies = '';
anywhere between the two while lines.

Related

Correctly reply to comment using textbox array

I'm working on a forum page. Right now what is happening, when a user submits a reply to a topic: that reply gets submitted to all the comments. I need to check to see where the array value is, compared to the topic. Like for example topic 3, and the user replies: it only replies to that topic, no others.
<form enctype="metadata/form-data" method="post">
<?php
$reply = $_POST["reply"];
$submit = $_POST["submit"];
$uID = $newRow["ID"];
$cID = $comment["comment_ID"];
$ucID = $comment["ID"];
//this is where I've been stuck.
if(isset($submit)){
foreach($reply as $myReply){
echo $myReply.'<br />';
}
}
else{
echo "No result here.";
}
?>
<div class="textInput">
<textarea name="reply[]" maxlength="255"></textarea>
</div>
<div class="submitInput">
<input type="submit" name="submit" value="reply" />
</div>
</form>
I don't have a clear image of what it is you are using exactly, but I'll make up an example which I'm sure will be of help. I'm going to assume you're using MYSQLI
Steps:
Step 1 ) Store your original post in a table (Original post will be OP from now on)
Step 2 ) Create a table for the replies to go in
Step 3 ) Create a relationship (foreign key)
Step 4 ) Get the original posts you want to be visible (or is it only one?)
Step 5 ) Get related replies
Step 6 ) Put related replies as a sub-array within the OP array.
Example:
First, get the OP. STEP 4
<?php
//In case of multiple:
$getOP = "SELECT * FROM original_posts WHERE ID IN(1,2,3)";
//In case of single:
$getOP = "SELECT * FROM original_posts WHERE ID = 1";
?>
Now, get those ID's in PHP.
<?php
//in case of multiple:
$IDArray = array();
$getOPResult= mysqli_query($con, $getOP);
foreach($getOPResult as $row){
$IDArray[] = $row['ID'];
}
//In case of single, no need for a loop
$result = $getOPResult->fetch_object();
$OPID = $result->ID;
?>
Now, follow up with the replies STEP 5
<?php
//In case of multiple
$getReplies = "SELECT * FROM table_replies WHERE OPID IN(".implode(',', $IDArray).")";
//In case of single
$getReplies = "SELECT * FROM table_replies WHERE OPID = $OPID;
?>
Now, we'll fuse the arrays. This step isn't even necessary with a single OP:
<?php
$myReplies = mysqli_query($con, $query);
$fusedArray = array();
foreach($myReplies as $row){
//put the replies into an array with the OP's ID as a key
$fusedArray[$row['OPID']] = $row;
}
?>
Last step - Rendering it all:
<?php
$html = '';
foreach($getOPresult as $OP){
//set replies array
$thisOPID = $OP['ID'];
$relatedReplies = $fusedArray[$thisOPID];
//From this point on, you can easily loop over the replies for every OP
$html .= '<div class="myPost">';
$html .= 'I'm going to output OP data here';
$html .= '<div class="myReplies">';
//Start looping over the replies and outputting it here
foreach($relatedReplies as $reply){
$html .= 'I'm rendering reply data here';
}
$html .= '</div>';
$html .= '</div>';
}
echo $html;
?>
To close
Now, this isn't extremely specific since I don't have much information, but the logic is there and this logic should suffice in most cases.
Before starting a discussion, please remember that this is just an example of structure and logics.
However you want to output your HTML is on you and so is the coding style. Whether you want to use procedural mysqli or not or how you secure it against MYSQL injection and such, are not related to this question and thus should not be discussed. I'm only trying to help OP with the logistics of it all.
Have a nice day, and I hope this helps :)
EDIT:
I'm sorry, you seem to have changed your question.
In this case, I would simply recommend you to use a hidden field in the form such as this:
<input type="hidden" name="OPID" value="$IDoftheOP"/>
Now, whenever load a topic, just fill the value of the hidden input with the ID of it. When reading out the formdata in PHP, simply read it out and that's the ID you need to couple it with.

adding or recognizing multiple textboxes or something like that in php dynamically

hii am amateur in php and making a website in which i am uploading an image,storing it in database(with an autoincrement variable) and displaying it on page in descending order so it may seem as latest at top and latter below it,,i need to add a textbox for comment and username(cuz i haven't made login page as m not gonna host it somewhere)
i knwo how to add it for upload image's section as only 1 image is gonna get uploaded
problem is how to display it, i have used
while ($image = mysqli_fetch_assoc($sql))
{
echo image code....
}
Now i in the div to display image i'll incorporate 2 textboxes and evertime after while loop ill display values from dB accordingly but when i want to edit the textbox after uploading more than 1 image,how to know which textbox is being edited as every textbox would have same textbox name
should i compare the image contents ?as the image iteself is stored in binary format? but that wud be a slow process i guess
plz suggest som idea or method to do so basically its like instagram(but very basic)....
First create images table:
images table
image_id | url
Then creare seperate table for images comments:
images_comments table
comment_id | image_id | user | text | date
Where:
comment_id: integer , Auto Increment
image_id: integer referring to id in images table
user: should be user id referring to separate users table, but because you do not have login system you can store user name here as varchar.
text: varchar
date: datetime
To show images + comments:
$sql = "SELECT * FROM images";
while ($image = mysqli_fetch_assoc($sql))
{
$imageUrl = $image["url"];
$imageID = $image["image_id"];
//Show image:
echo "<img src='$imageUrl ' />";
//Get comments:
$sql2 = "SELECT * FROM images_comments WHERE image_id=$imageID";
while ($comment = mysqli_fetch_assoc($sql2))
{
$text = $comment["text"];
$userName = $comment["user"];
$date = $comment["date"];
//show username and comment date
echo $userName . " " .$date . "<br>";
//Show comment text:
echo $text;
}
}
To add a comment to images
if you want a comment form under each image then in the While loop we used before add the following code:
while ($image = mysqli_fetch_assoc($sql))
{
.......... previous code goes here .........
//in the form we store imageID in hidden input field
//so that we can know to which image the form belongs
echo "<form method='post' action='page.php'>
<input type='text' name='username'/>
<textarea name='commentText'></textarea>
<input type='hidden' name='imageID' value='$imageID'/>
<input type='submit' name='submitComment' value='Submit'>
</form>";
}
then in page.php
if(isset($_POST["submitComment"]))
{
$username = $_POST["username"];
$text = $_POST["commentText"];
$imageID = $_POST["imageID"];
$date = date("Y-m-d H:i:s");
$sql = "INSERT INTO images_comments (image_id,user,text,date) VALUES
($imageID,$username,$text,$date)";
mysqli_query($con,$sql);
}

PHP MySQL maths update value in database [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
So ive got a rating system in place on a website im making. Currently each itema has a plus and minus button on either side as well as a visible rating level in this case its 3.1 for one of the items.
Im trying to programme both the plus and minus buttons in such a way that when the user presses them then the rating either increases or decreases by one.
Currently ive only implemented the minus button, however, when I click it the rating value doesnt decrease. It stays at 3.1. The page works fine and when i click on the "minus" button i get the error Call to a member function execute() on a non-object on line 67 which is the $stmt->execute()
Here is the code i have so far:
<?php
$results = $mysqli->query("SELECT * FROM programmes ORDER BY ProgrammeName ASC");
if ($results) {
$i=0;
echo '<table><tr>';
echo '<br/>';
echo '<br/>';
while($obj = $results->fetch_object())
{
echo '<td>';
echo '<div class="tvProgs">';
echo '<form method="post" id = "programmes" action="">';
echo "<input type=\"hidden\" name=\"progID\" value=\"".htmlentities($obj->ProgrammeID)."\" />";
echo '<div class="progImage"><img src="images/'.$obj->Image.'"></div>';
echo '<div class="progTitle"><h3>'.$obj->ProgrammeName.'</h3>';
echo '<div class="progRating"><h5>'.$obj->Rating.'</h5></div>';
echo '<div id = "btnMin"><input type="button" id ="minus" value ="-"/></div>';
echo '<div id = "btnPl"><input type="button" id ="plus" value ="+"/></div> ';
echo '<br/>';
echo '</form>';
echo '</div>';
echo '</td>';
$i++;
if ($i == 5) {
echo '</tr><tr>';
}
}
echo '</tr></table>';
}
if(isset($_POST['minus'])){
$newRating = 1;
$ID = $_POST['progID'];
$upsql = "UPDATE programmes SET Rating = Rating - $newRating WHERE progID='$ID'";
$stmt = $mysqli->prepare($upsql);
$stmt->execute();
}
?>
Ive kept the ID field hidden as i dont want that to be displayed on the web page. I just want to update the rating of a particular ID.
any informatino will be appreciated
Change your query from:
$upsql = "UPDATE programmes SET Rating = Rating - $newRating WHERE progID='$ID'";
To this:
$upsql = "UPDATE programmes SET Rating = Rating - $newRating WHERE ProgrammeID='$ID'";
Hope it should work..
For using _POST['some_name'] field on your form should have attribute name with value some_name
<input type="button" name="some_name" value="Some value"/>
Currently you have id="minus" which is not passed to a server. At least you should have:
<input type="button" id ="minus" name="minus" value="-" />
^ we got name here
And second thought - as your plus/minus buttons have no type="submit" I suppose your form doesn't submit, unless you have some hidden javascript.
Try setting you plus/minus buttons like:
<input type="submit" name="minus" value ="-"/>
<input type="submit" name="plus" value ="+"/>
Alternatively, you could use HTML5 number type input for your rating. Depending on the broswer you will have a little spinner that will do this task. Note that not all the broswers render this the same.
echo '<div class="progRating">
<h5><input type="number" id="rating" name="rating" value="'.$obj->Rating.'"/></h5></div>';
Then you have to update only the rating with its new value.
More info here: http://www.html5tutorial.info/html5-number.php

how to give a link to execute this

$sql=mysql_query("SELECT * FROM feedback.subject WHERE branch='cse'");
$row = mysql_fetch_assoc($sql) or die("error : $sql" .mysql_error());
$data =array();
$n=mysql_num_rows($sql);
while($row = mysql_fetch_array($sql))
{
$query_result_array[]=$row;
}
for($i=0;$i<$n;$i++)
{
$subid=$query_result_array[$i]['subid'];
$bt =$query_result_array[$i]['batch'];
$y =$query_result_array[$i]['year'];
$s = $query_result_array[$i]['semister'];
$subname=$query_result_array[$i]['subname'];
$tid = $query_result_array[$i]['tid'];
$sql2=mysql_query("SELECT * FROM teacher WHERE teacher.tid='$tid'");
$row2 =mysql_fetch_array($sql2);
$tname= $row2['tname'];
echo "<table id='table'>";
echo "<tr>";
echo "<td>".$bt."</td>";
echo "<td>CSE</td>";
echo "<td>".$y."</td>";
echo "<td>".$s."</td>";
echo "<td style='width:150px'>".$subname."</td>";
echo "<td style='width:150px'>".$row2['tname']."</td>";
echo '<form methode="get">
<input type="hidden" name="report">
<input type="submit" value="report">
</form>';
echo "</tr>";
echo "</table>";
}
function handler($x,$y){
session_regenerate_id();
$_SESSION['SUBID']=$x;
$_SESSION['TID']=$y;
echo 'report';
}
if(isset($_GET["report'$i'"]))
{
handler($query_result_array[$i]['subid'], $query_result_array[$i]['tid']);
unset ($_GET["report"]);
}
}
this results a table like
BATCH | BRANCH | YEAR | SEMISTER | SUBJECT NAME | TEACHER NAME | ACTION |
-------------------------------------------------------------------------------
9 CSE 4 1 DBMS ABC REPORT
9 CSE 4 1 WT XYZ REPORT
-------------------------------------------------------------------------------
when i click the report of a row suppose ('ABC' teacher) i want to carry the details ('ABC' and 'DBMS') to further process. but it always carrying the details of last person in the loop(here 'XYZ' and 'WT'). how to get that? is there any alternate process through i can call the handler function for a particular row which carries that particular row details.
just loop through query result array and inside of it place an if which detects when name is what you are looking for, at that moment, fetch current $query_result_array[$i] into a var that you want to carry the data further and break the loop.
If you are fetching by position in the table, you do not even need loop you just go $specific_person_data = $query_result_array[$i]...
So this now contains all of data about the person at position $i in your data table.
Update for links:
Each persons data can be passed to another page through link like this:
linkadress.php*?var1=X&var2=Y&var3=Z...*
and fetched on the other end with $_POST['var1'], $_POST['var2'] etc.
make sure not to echo or return data directly, but on every post var use strip_tags for security precaution.
Also here is article of mine on the subject of sensitive data handling and soem basic security:
http://metaphorical-lab.com/blog/?p=443

Text Injection In Display

Ok, so I'm given a list of parts like so:
PartID CatID PartName
0 1 Part 1
1 2 Part 2
2 1 Part 3
3 3 Part 4
4 2 Part 5
5 2 Part 6
I'm using PHP to pull. How can I inject a blurb of text at each change in CatID, without having to run multiple loops?
So on page, I can display it like:
"BLURB OF TEXT"
Part 1
Part 3
"BLURB OF TEXT"
Part 2
Part 5
Part 6
"BLURB OF TEXT"
Part 4
Here's the code so far. I thought about putting in an assignment to = $row["CatID"], and checking to see if the variable == CatID, but it was always ==...
while($row = sqlsrv_fetch_array($qry, SQLSRV_FETCH_ASSOC)) {
echo $row["PartName"]
}
Put the ID in a variable that is outside the loop. That way you can check the previous ID and the current one. If the current one is not the same as the last one, echo some text:
$LastID = 0;
while($row = sqlsrv_fetch_array($qry, SQLSRV_FETCH_ASSOC)) {
echo $row["PartName"];
if($row["CatID"] > $LastID)
{
// ID changed!
echo "Insert Text!";
}
$LastID = $row["CatID"];
}
This, ofcourse, is assuming that the data is sorted ascending on CatID as your result that you want is showing.
I had my logic backwards.... grr, figures I get it figured out right after I ask for help...
if($cCat == $row["catID"]){
//echo 'nothing here';
}else{
echo '<a name="' . $row["PartCategory"] . '"></a>';
echo $this->GetPartCategories();
$cCat = $row["catID"];
}
is what works, , and above the while statement is a $cCat = '';
I was trying
if(!$cCat == $row["catID"]){
echo '<a name="' . $row["PartCategory"] . '"></a>';
echo $this->GetPartCategories();
$cCat = $row["catID"];
}
which for some reason did not work.
p.s. Already have an order by in my query. It orders by the catID, partSortOrder, then partName

Categories