Hello so i am doing this school assigment where i have make a comment system corresponding to the post ID and i know that it looping three times but i gave it the post id. And i know that the postID is changeing all the time. i just have no idea how to fix this bug any ideas?
<?php require_once("menu.php");
$connection = connectToMySQL();
$selectPostQuery = "SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC";
$result = mysqli_query($connection,$selectPostQuery)
or die("Error in the query: ". mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result))
{
$postid = $row['ID'];
if (!empty($_POST['comment']) ) #To insert new comments in the database
{
$comment = $_POST['comment'];
$userid = $_SESSION['userID'];
$insertCommentQuery = "INSERT INTO `tblcomments` (`Content`,`UserID`,`PostID`,`Timestamp`) VALUES ('$comment','$userid','$postid',CURRENT_TIMESTAMP)";
$resultComment = mysqli_query($connection, $insertCommentQuery)
or die("Error in the query: ". mysqli_error($connection));
}
echo "<div class=\"wrapper\">";
echo "<div class=\"titlecontainer\">";
echo "<h1>$row[Title]</h1>";
echo "</div>";
echo "<div class=\"textcontainer\">";
echo "<span>$row[Content]</span>";
echo "</div>";
if (!empty($row['ImagePath'])) #This will check if there is an path in the textfield
{
?>
<div class="imagecontainer">
<img src="images/<?php echo "$row[ImagePath]"; ?>">
</div>
<?php
}
echo "<div class=\"timestampcontainer\">";
echo "<b>Date posted :</b>$row[TimeStamp] ";
echo "<b>Author :</b> Admin";
echo "</div>";
#Selecting comments corresponding to the post
$selectCommentQuery = "SELECT * FROM `tblcomments` LEFT JOIN `tblusers` ON tblcomments.userID = tblusers.ID WHERE tblcomments.PostID ='$postid'";
$commentResult = mysqli_query($connection,$selectCommentQuery)
or die ("Error in the query: ". mysqli_error($connection));
while ($commentRow = mysqli_fetch_assoc($commentResult))
{
echo "<div class=\"commentcontainer\">";
echo "<div class=\"commentusername\"><h1>Username :$commentRow[Username]</h1></div>";
echo "<div class=\"commentcontent\">$commentRow[Content]</div>";
echo "<div class=\"commenttimestamp\">$commentRow[Timestamp]</div>";
echo "</div>";
}
if (!empty($_SESSION['userID']) )
{
echo "<form method=\"POST\" action=\"\" class=\"post-frm\">";
echo "<label>New Comment</label>";
echo "<textarea id=\"comment\" name=\"comment\"> </textarea>";
echo "<input id=\"submit\" type=\"submit\" name =\"submit\" class=\"button\"/>" ;
echo "</form>";
}
echo "</div>";
echo "<br /> <br /><br />";
}
require_once("footer.php") ?>
Well, that's exactly what your script does. It queries all posts, loops through them, and then performs an insert for all of them. To fix this, store the id of the post in the comment form. When you post the form, insert just a single comment and use the id in the form.
That could look something like this:
<?php
if (array_key_exists('postid', $_POST))
{
$postid = $_POST['postid'];
$comment = $_POST['comment'];
// Perform a single insert here, and use $postid and $comment.
}
// Then, start rendering the page:
require_once(menu.php);
$connection = connectToMySQL();
$selectPostQuery = SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC;
$result = mysqli_query($connection,$selectPostQuery)
or die(Error in the query: . mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result))
{
$postid = $row['ID'];
// Render the post itself here.
?>
<div class="wrapper">;
<div class="titlecontainer">;
<h1><?=$row['Title']?></h1>;
</div>;
<div class="textcontainer">;
<span><?=$row['Content']?></span>;
</div>;
<?php
// Render a comment form for each post (is that what you did?)
if (!empty($_SESSION['userID']) )
{?>
<form method=POST action= class=post-frm>
<label>New Comment</label>
<textarea id=comment name=comment></textarea>
<input type=hidden name=postid value=<?=$postid?>/>
<input id=submit type=submit name =submit class=button/>
</form>
<?}
}
Most of your code is the same, only the processing of the post data is now done before the loop.
Otherwise, I just fixed some small syntactic things (and maybe introduced new ones, I haven't tested it).
Also, I took the HTML out of echoes. It's a matter of taste, of course, but experience has taught me that big chunks of HTML in echo statements isn't very readable or maintainable. Rather just close the PHP tags, output the raw HTML and echo only the variables in it. You can use the short notation for that: <?= $value ?>, which basically means <?php echo $value ?>.
Related
I am using the following code to display certain rows from my database table:
<?php
$searchtype=$_POST['searchtype'];
$searchterm=$_POST['searchterm'];
$searchterm= trim($searchterm);
if (!$searchtype || !$searchterm)
{
echo 'Error';
exit;
}
if (!get_magic_quotes_gpc())
{
$searchtype = addslashes($searchtype);
$searchterm = addslashes($searchterm);
}
$db = include "connect2db.php";
$query = "select * from notes where ".$searchtype." like '%".$searchterm."%'";
$result = $db->query($query);
$num_results = $result->num_rows;
echo '<p>Number of rows found: '.$num_results.'</p>';
for ($i=0; $i <$num_results; $i++)
{
$row = $result->fetch_assoc();
echo '<i>';
echo stripslashes($row['date']);
echo '</i><br /> ';
echo '<b>';
echo stripslashes($row['notetitle']);
echo '</b><br /> ';
echo stripslashes($row['note']);
echo '<br /><br /> ';
echo '</p>';
}
$result->free();
$db->close();
?>
Now I would like to display an edit-link for each row displayed, that can open a new page in which it is possible to edit a specific row. I already have the code that lets you edit the row:
<?php
if ($_REQUEST['save']=="Save") { // is data submitted?
// create variables
$noteid = $_REQUEST['noteid'];
$coursename = $_REQUEST['coursename'];
$notetitle = $_REQUEST['notetitle'];
$note = $_REQUEST['note'];
$query = "UPDATE notes SET ";
$query .= "coursename='$coursename', ";
$query .= "notetitle='$notetitle', ";
$query .= "note='$note' ";
$query .= "WHERE noteid='$noteid'";
$result = $db->query($query);
} elseif ($_REQUEST['delete']=="Delete") { // is data to be removed?
$noteid = $_REQUEST['noteid'];
$query="DELETE FROM notes WHERE noteid='$noteid'";
$result = $db->query($query);
}
?>
<div class="formular">
<div class="row1">
<p>Id</p>
<p>Notetitle</p>
<p>Note</p>
</div>
<?php
$query = "SELECT * FROM notes ORDER BY noteid DESC";
$result = $db->query($query);
while ($row = mysqli_fetch_array($result)) {
echo "<form ".$_SERVER['PHP_SELF']." name='edit-form' method='post' class='row1'>\n";
echo "<p class='align_top padding_top'>".$row['noteid']."<input type='hidden' name='noteid' value='".$row['noteid']."' /></p>\n";
echo "<p class='align_top'><input type='text' name='notetitle' value='".$row['notetitle']."' /></p>\n";
echo "<p><textarea name='note' rows='10' cols='50'>".$row['note']."</textarea></p>\n";
echo "<p><input type='submit' name='save' value='Save' /></p>";
echo "<p><input type='submit' name='delete' value='Delete' /></p>";
echo "</form>\n";
}
echo '</div>';
$result->free();
$db->close();
?>
What I am struggling with is how to display an edit-link for each row that lets you open a page where you can edit/delete the content of only that row.
I hope someone can help, I am very new at this.
Thank you!
Add a button next to each row that opens an edit page (or modal) with the id inside, example: <button onclick="edit('randomId')">Edit RandomId </button>
You could implement something different that accepts the unique id of that specific row and open a new page or modal with it.
This form is a search form which allows the user to search for an event using the Venue and category fields which are scripted as dropdown boxes and the Price and event title as user input text boxes, as shown via the code if a keyword is entered which matches the fields on the database it should output all the related information for that event if any matches have been made on either search fields, the tickboxes allow the user to identify what criteria they would like to search with, if the tickbox field hasn't been checked then the SQL enquiry will not search for keywords with that corresponding field.
The issue is, it all seems to work fine except no results seem to show up for the Venue and Category fields if they was solely used to search for an event. But if I choose another field everything is outputting correctly including the venue and Category field.
DATABASE: http://i.imgur.com/d4uoXtE.jpg
HTML FORM
<form name="searchform" action ="PHP/searchfunction.php" method = "post" >
<h2>Event Search:</h2>
Use the Check Boxes to indicate which fields you watch to search with
<br /><br />
<h2>Search by Venue:</h2>
<?php
echo "<select name = 'venueName'>";
$queryresult2 = mysql_query($sql2) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult2)) {
echo "\n";
$venueID = $row['venueID'];
$venueName = $row['venueName'];
echo "<option value ='$venueName'";
echo ">$venueName</option>";
}# when the option selected matches the queryresult it will echo this
echo "</select>";
echo" <input type='checkbox' name='S_venueName'>";
mysql_free_result($queryresult2);
mysql_close($conn);
?>
<br /><br />
<h2>Search by Category:</h2>
<?php
include 'PHP/database_conn.php';
$sql3 ="SELECT catID, catDesc
FROM te_category";
echo "<select name = 'catdesc'>";
$queryresult3 = mysql_query($sql3) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult3)) {
echo "\n";
$catID = $row['catID'];
$catDesc = $row['catDesc'];
echo "<option value = '$catDesc'";
echo ">$catDesc </option>";
}
echo "</select>";
mysql_free_result($queryresult3);
mysql_close($conn);
?>
<input type="checkbox" name="S_catDes">
<br /><br />
<h2>Search By Price</h2>
<input type="text" name="S_price" />
<input type="checkbox" name="S_CheckPrice">
<br /><br />
<h2>Search By Event title</h2>
<input type="text" name="S_EventT" />
<input type="checkbox" name="S_EventTitle">
<br /><br />
<input name="update" type="submit" id="update" value="Search">
</form>
PHP CODE THAT DEALS WITH PROCESSING THE FORM DATA
<?php
include 'database_conn.php';
$venuename = $_POST['venueName']; //this is an integer
$catdesc = $_POST['catdesc']; //this is a string
$Price = $_POST['S_price'];
$EventT = $_POST['S_EventT'];
#the IF statements state if the tickbox is checked then search with these enquires
if (isset($_POST['S_VenueName'])) {
$sql = "SELECT * FROM te_venue WHERE venueName= '$venuename'";
}
if (isset($_POST['S_catDes'])) {
$sql = "SELECT * FROM te_category WHERE catID= '$catdesc'";
}
if (isset($_POST['S_CheckPrice'])) {
$sql = "SELECT * FROM te_events WHERE (eventPrice LIKE '%$Price%')";
}
if (isset($_POST['S_EventTitle'])) {
$sql = "SELECT * FROM te_events WHERE (eventTitle LIKE '%$EventT%')";
}
$queryresult = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult))
{
echo "Event Title: "; echo $row['eventTitle'];
echo "<br />";
echo "Event Description: "; echo $row['eventDescription'];
echo "<br />";
echo "Event Venue "; echo "$venuename";
echo "<br />";
echo "Event Category "; echo "$catdesc";
echo "<br />";
echo "Event Start Date "; echo $row['eventStartDate'];
echo "<br />";
echo "Event End Date "; echo $row['eventEndDate'];
echo "<br />";
echo "Event Price "; echo $row['eventPrice'];
echo "<br /><br />";
}
mysql_free_result($queryresult);
mysql_close($conn);
?>
Try using atleast MySQLi instead of deprecated MySQL. You can try this:
database_conn.php:
<?php
/* ESTABLISH YOUR CONNECTION. REPLACE THE NECESSARY DATA BELOW */
$con=mysqli_connect("YourHost","YourUsername","YourPassword","YourDatabase");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
?>
HTML Form:
<html>
<body>
<?php
include 'PHP/database_conn.php';
$sql2="SELECT venueID, venueName FROM te_venue"; /* PLEASE REPLACE THE NECESSARY DATA */
echo "<select name = 'venueName'>";
$queryresult2 = mysqli_query($con,$sql2);
while($row = mysqli_fetch_array($queryresult2)) {
echo "\n";
$venueID = mysqli_real_escape_string($con,$row['venueID']);
$venueName = mysqli_real_escape_string($con,$row['venueName']);
echo "<option value ='$venueName'>";
echo $venueName."</option>";
} /* when the option selected matches the queryresult it will echo this ?? */
echo "</select>";
echo "<input type='checkbox' name='S_venueName'>";
?>
<br><br>
<h2>Search by Category:</h2>
<?php
$sql3 ="SELECT catID, catDesc FROM te_category";
echo "<select name = 'catdesc'>";
$queryresult3 = mysqli_query($con,$sql3);
while($row = mysqli_fetch_array($queryresult3)) {
echo "\n";
$catID = mysqli_real_escape_string($con,$row['catID']);
$catDesc = mysqli_real_escape_string($con,$row['catDesc']);
echo "<option value = '$catDesc'>";
echo $catDesc."</option>";
}
echo "</select>";
?>
<input type="checkbox" name="S_catDes">
<br><br>
<h2>Search By Price</h2>
<input type="text" name="S_price" />
<input type="checkbox" name="S_CheckPrice">
<br><br>
<h2>Search By Event title</h2>
<input type="text" name="S_EventT" />
<input type="checkbox" name="S_EventTitle">
<br><br>
<input name="update" type="submit" id="update" value="Search">
</form>
</body>
</html>
PHP:
<?php
include 'database_conn.php';
$venuename = mysqli_real_escape_string($con,$_POST['venueName']); /* this is an integer */
$catdesc = mysqli_real_escape_string($con,$_POST['catdesc']); /* this is a string */
$Price = mysqli_real_escape_string($con,$_POST['S_price']);
$EventT = mysqli_real_escape_string($con,$_POST['S_EventT']);
/* SHOULD PRACTICE USING ESCAPE_STRING TO PREVENT SOME OF SQL INJECTIONS */
/* the IF statements state if the tickbox is checked then search with these enquires */
if (isset($_POST['S_VenueName'])) {
$sql = "SELECT * FROM te_venue WHERE venueName= '$venuename'";
}
if (isset($_POST['S_catDes'])) {
$sql = "SELECT * FROM te_category WHERE catID= '$catdesc'";
}
if (isset($_POST['S_CheckPrice'])) {
$sql = "SELECT * FROM te_events WHERE (eventPrice LIKE '%$Price%')";
}
if (isset($_POST['S_EventTitle'])) {
$sql = "SELECT * FROM te_events WHERE (eventTitle LIKE '%$EventT%')";
}
$queryresult = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($queryresult))
{
echo "Event Title: "; echo $row['eventTitle'];
echo "<br />";
echo "Event Description: "; echo $row['eventDescription'];
echo "<br />";
echo "Event Venue "; echo "$venuename";
echo "<br />";
echo "Event Category "; echo "$catdesc";
echo "<br />";
echo "Event Start Date "; echo $row['eventStartDate'];
echo "<br />";
echo "Event End Date "; echo $row['eventEndDate'];
echo "<br />";
echo "Event Price "; echo $row['eventPrice'];
echo "<br /><br />";
}
mysqli_close($conn);
?>
What if user checks all the check box? What would happen is, the last condition will be used. The first three conditions will be overwritten by the last condition.
If you use ELSE IF in those conditions, the first condition will be implemented.
My advice is to use radio button instead of check box and hope you gets the idea along the way.
Have you tried printing out your $sql query for debugging?
Try <input type="checkbox" name="S_catDes" value="checked">.
From memory checkboxes need a value field but I could be wrong. Hope this helps.
I have tried this code:
<?php
$sql="SELECT id, comment FROM comments
ORDER BY comments.id DESC";
$result = mysql_query($sql) or trigger_error ( mysql_error ( ));
while($row = mysql_fetch_array($result))
{
echo "<div>";
echo $row['comment'];
echo "</br>";
// Answer to comment
echo "<a id='href".$row['id']."' href='#'> Answer </a>";
echo "<div>";
echo "Your answer is: ";
echo "<span id='answerdone'";
echo "</span>";
echo "</div>";
}
?>
<script>
$('#href".$row['id']."').click(function() {
$(this).empty().next.append(<div> <input type='text' value='' name='answer'
id='".$row['id']."'
<input type='submit' value='Answer' />
</div>);
});
var input = document.getElementById('".$row['id']."'),
placeholder = document.getElementById('answerdone');
input.onsubmit = function() {
placeholder.innerHTML = input.value
}
</script>
In order to make a form appear in each result of a MySQL query and what is written in this form to be written on the same page, after "Your answer is: ". Unfortunately, this isn't working and I don't know why. In addition I want what is written after "Your answer is: " to be inserted as an additional column, in the comments table.
How do I do that and what is wrong?
You are mixing php and javascript variables.
For example:
echo "<a id='href".$row['id']."' href='#'> Answer </a>";
will appear as:
<a id='href1' href='#'> Answer </a>";
So you can't find this element with javascript:
$('#href".$row['id']."').click(function() {
It has to be something like
$('#href1').click(function() {
You should probably have a look at your javascript-console. There you get the right error-description.
I'm trying to create a user profile page. The user selects whose profile he wants to view based on a search. By clicking a "view profile" button the page should then go to profile.php where it displays the user's profile.
For now, I'm just trying to test it out and only display the user's name. Here's the code I have.
My problem is that I don't know how to pass "$userID" to profile.php which will then be used to look up that user's information. Since the value is in a while loop, I'm not sure how to select for once instance of this loop.
function findUsers($friend){
$search = mysql_query("Select * from users where username='$friend'");
$userLocation = mysql_query("select * from userinfo where username='$friend'");
$locationResult = mysql_fetch_array($userLocation);
$locationResultArray = $locationResult['userlocation'];
$locationExplode = explode("~","$locationResultArray");
//table column names
echo "<table>";
echo "<tr><td>";
echo "Username";
echo "</td><td>";
echo "Location";
echo "</td></td><tr><td>";
while($result = mysql_fetch_array($search)) //loop to display search
{
$userID = $result['userid']; //can I pass this value to the function since it's possible that there is more than 1 userID from the while loop?
echo $result['username'];
echo "</td><td>";
echo $locationExplode['0'];
echo ", ";
echo $locationExplode['1'];
echo "</td><td>";
?>
<form method="post" action="profile.php">
<?
echo "<input type='submit' name='profile' value='View User's Info'";
echo "</td><td>";
?>
</form>
<form method="post" action="profile.php">
<?
echo "<input type='submit' name='addfriend' value='Add Friend' />"; //code still needs to be written for this input.
echo "</td></tr>";
}
echo "</table>";
if(isset($_POST['profile'])){
$viewProfile->displayProfile($userID); //This is where I'm not sure if it's taking the correct userID.
}
}
}
?>
...and the page to display the profile
<?
include_once 'infoprocesses.php';
$user = new dbProcessing();
Class viewProfile{
function displayProfile($username){ //display profile pulls the user's name from the databse
echo $username; //used to test if value is being sent...nothing is being displayed
?>
<h2><?php $user->username($username);?>'s Information</h2>
<?
}
}
?>
Normally, I will make it as a link with the friend's userid passed as GET variable.
Something like this
echo "<a href='profile.php?userid=" . $result['userid'] . "'>". $result['username'] ."</a>";
For your current design, your options are:
set the action to
<form method="post" action="profile.php?userid=<?php echo $result['userid']; ?>">
or
make a hidden input field with the friend's userid.
<input type='hidden' name='userid' value='<?php echo $result['userid']; ?>' />
The first method is passing as POST variable, then you can retrieve from $_POST['userid'] while in the second method, you will retrieve from $_GET['userid'] variable.
while($result = mysql_fetch_array($search)) //loop to display search
{
echo $result['username'];
echo "</td><td>";
echo $locationExplode['0'];
echo ", ";
echo $locationExplode['1'];
echo "</td><td>";
echo 'View User's Info';
}
echo "</table>";
}
and in the profile.php just
$userid = $_GET['id'];
I would like to apologize if the duplicate of this question exist. i tried to find and could find anything here that could solve my problem..
I am using a form to get the input and update it in the mysql database, and then retrieve the records in the html form, and have defined the code for deleting the records individually through hyperlinks. however i want to do more, i want to use the checkboxes to delete the multiple records.
my code goes like this.
<?php
//include connection string
include('connection.php');
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post"/>
Username : <input type="text" name="user"/><br />
Password : <input type="password" name="pass"/><br />
<input type="submit" name="submit" value="Send"/>
</form>
<?php
// query to insert into database
if(isset($_POST['user']) && isset($_POST['pass'])) {
$user = empty($_POST['user']) ? die(mysql_error()) : mysql_escape_string($_POST['user']);
$pass = empty($_POST['pass']) ? die(mysql_error()) : sha1(mysql_escape_string($_POST['pass']));
$query = "INSERT INTO users(name, pass) VALUES ('$user', '$pass')";
$result = mysql_query($query) or die(mysql_error());
}
if(isset($_GET['id'])) {
//query to delete the records
$query = "DELETE FROM users WHERE id = " . intval($_GET['id']);
$result = mysql_query($query);
}
//query to retrieve records
$query = "SELECT * FROM users";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ) {
echo "<table cellpadding=10 border=1>";
while ($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "<td>delete";
echo "</tr>";
}
echo "</table>";
}
?>
i would like you to know that i am a newbie to programming world and i am not so sure of how exactly html checkbox work and how do i use it to delete the multiple records. i want to know what extra code do i have to write for it, and i would appreciate a lot if someone explains me that extra code in brief..
thank you..
This is probably a good time for another form:
<?php
// query to insert into database ...
// ... etc...
if(isset($_POST["formDeleteSelected"])) {
//query to delete the records
$query = "DELETE FROM users WHERE id IN (" . implode(", ",$_POST["rowid"]) . ")";
$result = mysql_query($query);
header("Location: mycode.php"); // just so 'refresh' doesn't try to run delete again
exit();
}
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<?php
//query to retrieve records
$query = "SELECT * FROM users";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ) {
echo "<table cellpadding=10 border=1>";
while ($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td><input type="checkbox" name="rowid[]" value=\"" . $row[0] . "\" /></td>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "</tr>";
}
echo "</table>";
}
?>
<input type="submit" name="formDeleteSelected" text="Delete Selected" />
</form>
Or something like that (I haven't actually tried that code so there may be a typo). Also note that you should make sure to sanitize any form/get inputs for SQL Injection (plenty of information on that in other Stack Overflow questions).
First of all you need a checkbox and the id you want to delete:
<input id="delete" type="checkbox" name="delete" /><label for="delete">Delete user</label>
<input type="hidden" name="user_id" value="12345" />
You can then test if the checkbox has been set and then manually set the GET parameter to reuse your existing code:
if(isset($_POST['delete'])){
$_GET['id'] = $_POST['user_id'];
}
That's not the most elegant solution but a really simple one that should work with your code.
try an SQL query with a list of IDs
... WHERE id=$sentIds[0] OR id=$sentIds[1] OR ...
or use a set operation
... WHERE id IN ($i1,$i2 ... );
You sure have to send ids in the form for this to work, but You know that ;)