PHP topic viewing and replying script - php

I'm working on a small board/forum. I have topic posting done; it's visible in the database and all that jazz. Now I'm working on retrieving the topic list and so that when you click a topic you can view it. That's working fine, except that when I click on it the page goes blank and nothing is being shown. I know the issue is that I can't get the id of the post I clicked on because it's in the if-else statement with a while loop. Here is my code now.
<?php
require('init.php');
$get_threads = mysql_query("SELECT * FROM GOT ORDER BY time");
if (!isset($_GET['view_thread'])) {
$get_threads = mysql_query("SELECT * FROM GOT ORDER BY time");
while ($select_threads = mysql_fetch_assoc($get_threads)) {
$title = $select_threads['title'];
$time = $select_threads['time'];
$user = $select_threads['user'];
$id = $select_threads['id'];
$form = '<center>
<form method="get" action="">
<input type="submit" name="view_thread" id="view_thread" value="'.$title.'" />
<input type="hidden" name="thread_id" id="thread_id" value="'.$id.'" />
</form>
</center>';
echo '<div id="post_info">'.$form.'<hr>Posted by: <b>'.$user.'</b> '.$time.'</div>';
}
} else {
$get_posts = mysql_query("SELECT * FROM GOT WHERE id='$id'");
$select_posts = mysql_fetch_assoc($get_posts);
$content = $select_posts['content'];
echo $content;
}
?>
I need to get that $id so I can grab the post and later all the replies from the database. I'm new to php so I'm probably missing something. Thanks for any help!

first: your parameter is named "thread_id", so your query should be
$get_posts = mysql_query("SELECT * FROM GOT WHERE id='$thread_id'");
BUT i strongly suggest to
go for POST instead of GET
use mysql_real_escape to avoid SQL injection

Related

PHP and MYSQLI Check if user ID is present and if not create it

I have been looking for 3 weeks on the Internet for an answer to this question and cannot find anything that even comes close or in handy. I have a Database Table that i need to have checked. If a Users_ID is present in that table, I would like my code to display an update.php link in my form action="" tag and if the Users_ID is not present in that db table, then i would like to have an Insertdb.php page to be linked in the form instead of an update.php page. Here is what I have:
PHP Code:
<?php
session_start();
error_reporting(E_ALL);
include_once("dbconnect.php");
$users_id = $_SESSION['user_id'];
$sql = "SELECT * FROM dbtable WHERE uid=$users_id";
if($results = $con->query($sql)) {
while($display = $results->fetch_array(MYSQLI_ASSOC)) {
$uid = $display['uid'];
if($display['uid']==""){
$pagelink = "insertintodb.php";
}else{
$pagelink = "updatedb.php";
}
}
$results->close();
}
?>
And my HTML section looks like this:
HTML Code:
<form action="<?php echo $pagelink; ?>" method="POST">
<input type="text" value="" placeholder="Insert Value" name="something" />
<input type="submit" value="Submit Data" name="submit_data_to_db" />
</form>
How would I go about doing this? My current method Posted above is what I'm currently using, however its displaying only <form action="" method="POST"> when i check it against the pages view-source. Please help me anyway you can. Any and all help would be greatly appreciated. Thank you
you usually use num_rows method:
<?php
session_start();
error_reporting(E_ALL);
include_once("dbconnect.php");
$users_id = $_SESSION['user_id'];
$sql = "SELECT * FROM dbtable WHERE uid=$users_id";
if($results = $con->query($sql)) {
if($results->num_rows() > 0){
$pagelink = "insertintodb.php";
}else{
$pagelink = "updatedb.php";
}
}
$results->close();
}
?>
I see you use $con but I see nowhere you have declared it.
Can you confirm that actually exists? It is possible your script is halting its execution at that point.
Also a few things I would implement in there:
1. When you use variables that come from external sources (like your forms), or even other variables really, always care for SQL injection;
2. Your if & else can be reduced to just an if (when you find an ID). To all others case, you wish a default behaviour that is your else. So something like this:
$pageLink = "insertintodb.php";
if (!empty($display['uid'])) {
$pageLink = "updatedb.php"
}

How do I make a list with links?

Im making a list with names and links to full info about them. So, I've got simple search engine, which searching by the names or specific numbers. I use $_SESSION to get id of the people. The problem is, when there are more than 1 name and Im moving to the page of specific person appears the page of the last person in the list!
So, code of the search engine is:
if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9_a-z A-Z]#i","",$searchq);
$query = mysql_query("SELECT * FROM contract WHERE name LIKE '%$searchq%' OR student_code LIKE '%$searchq%'") or die("could not search");
$count = mysql_num_rows($query);
if($count == 0){
$output = 'There was no such results!';
}
else{
while($row = mysql_fetch_array($query)){
$name = $row['name'];
$student_code = $row['student_code'];
$_SESSION['users_id'] = $row['users_id'];
$output = '<table border ="1"><tr><td>'.$name.' '.$student_code.'
</td>
<td>
<form action="cont.php" method="post">
<label>Look at the contract:</label>
<input type="submit" name="submit" value=">>">
</form>
</td>
</tr>
</table><br \>
And another script in the page file:
$users_id = $_SESSION['users_id'];
$result = mysql_query("SELECT * FROM contract WHERE users_id = $users_id");
while($myrow = mysql_fetch_array($result)){
$output1 =
The way I understood your question is that you have two pages. One page that does the search, and another page that show the "more info" about a specific result.
What you're basically doing in the search is this:
Let's assume you have three results that got Id 1,4,7.
This is what's going to happen in your while loop
Set $name $student_code and $_SESSION['user_id'] ($_SESSION['user_id'] is now 1)
Prepare the first result
Set $name $student_code and $_SESSION['user_id'] ($_SESSION['user_id'] is now 4)
Prepare the second result
Set $name $student_code and $_SESSION['user_id'] ($_SESSION['user_id'] is now 7)
Prepare the third result
As you can see you're always overwriting the session key and therefore only the last one will be available when you get to the "cont.php" page (where I'm guessing the other code is?)
One simple solution would be to bake the id into the form and send it along in the request to the cont.php page. Something like this:
<form action="cont.php" method="post">
<label>Look at the contract:</label>
<input type="submit" name="submit" value=">>">
<input type="hidden" name="user_id" value="' . $row['users_id'] . '">
</form>
And then in the cont.php you simply change this:
$users_id = $_SESSION['users_id'];
to this
$users_id = $_POST['users_id'];
Hope that helps :)

PHP - Rendering dynamic web page through web browser

I am new to php and programming,, I have been following a tutorial but I've ran into a problem when trying to display the products onto a web page, This is the code am testing
<?php
if (isset($_GET['id'])) {
include "storescripts/connect_to_mysql.php";
$id = preg_replace('#[^0-9]#i', '', $_GET['id']);
$sql = mysql_query("SELECT * FROM products WHERE id='$id' LIMIT 1");
$productCount = mysql_num_rows($sql);
if ($productCount > 0) {
while($row = mysql_fetch_array($sql)){
$product_name = $row["product_name"];
$price = $row["price"];
$details = $row["details"];
$category = $row["category"];
$subcategory = $row["subcategory"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
}
} else {
echo "That item does not exist.";
exit();
}
} else {
echo "Data to render this page is missing.";
exit();
}
mysql_close();
?>
When I try to view the page through my browser I get the message "Data to render this page is missing"
I understand that it''s something to do with
if (isset($_GET['id'])) {
And am assuming maybe it's something to do with the 'id' But I cant work out how to fix it. Any pointers and help would be appreciated, sorry if this seems basic but like I said I am new and cant work this problem out. I've been trying all day
Thanks
Obviously, $_GET['id'] isn't set. If your link was something like http://www.example.com/index.php?id=32, it would be set.
Second, do not use GET/POST variables in queries without sanitising them!
And third, don't use mysql_query in the first place, but PDO or mysqli instead
When you see $_GET it's looking for a parameter in the URL. So:
http://localhost/yourphpscript.php?id=123
...is what it's expecting. Some ID must be defined in the URL.
You could try this code:
<?php
if (isset($_GET['id'])){ //Someone submitted a form or just prepended parameter to link
include "storescripts/connect_to_mysql.php"; //Include script with mysql connection
$id = preg_replace('#[^0-9]#i', '', $_GET['id']); //Sanitize input - remove everything besides numbers
$result = mysql_query("SELECT * FROM products WHERE id='$id' LIMIT 1"); //Execute query. Only 1 product because of LIMIT 1
if (mysql_num_rows($result)==1){ //If the product is found
$product = mysql_fetch_assoc($result) ; //Take the product
foreach ($product as $property => $value){ //Go through each property of product
echo "<div> {$property} : {$value} </div>" ;
}
}
} else {?>
<form method="get" action="<?php $_SERVER['PHP_SELF'] ; ?>">
<input type="text" name="id" />
<input type="submit" value="Submit product ID"/>
</form>
<?php
}
?>
Just ask if you have any questions.
learn to track your id. sanitize and check the url sending the id for correct value passed and again in the begining check the value as in
<?php
echo $_GET['id'];
?>
use this to know what it is your id value

php & mysql query - cannot return the variable I need from MySQL

update: There must be a minor syntax error in some accompanying validation for $_GET variable. I rewrote everything carefully and the script now works. Thank you all!
I've spent more than 5 hours trying to find what's wrong with my code.
1st page: a db query retrieves some vimeo videos from the db and presents each one of them with an "edit" link which dynamically gets the video's id (vimeo 8-digit id). To do this, I just call the following function:
function edit_portfolio_videos() {
global $connection;
$query = "SELECT * FROM portfolio_videos ORDER BY video_id ASC";
$portfolio_videos_set = mysql_query($query, $connection);
confirm_query($portfolio_videos_set);
while ($portfolio_video = mysql_fetch_array($portfolio_videos_set)) {
echo "<iframe src=\"http://player.vimeo.com/video/";
echo $portfolio_video['video_code'];
echo "?title=0&byline=0&portrait=0&color=ffffff\" width=\"400\" height=\"230\" frameborder=\"0\" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe><br />";
echo "Edit this Video";
}
}
2nd page: This is the page where each video will be edited by the administrator. Example URL would be something like "http://www.my_website.com/edit_portfolio_video.php?videocode=34956540". On this page, I use the following function to get the array from the previous page's script:
function get_selected_video_by_id($video_code) {
global $connection;
$query = "SELECT * FROM portfolio_videos ";
$query .= "WHERE video_code = '$video_code' ";
$query .= "LIMIT 1";
$videos_set = mysql_query($query, $connection);
confirm_query($videos_set);
if ($video = mysql_fetch_array($videos_set)) {
return $video;
} else { $video = NULL; }
}
and then...
$selected_video = get_selected_video_by_id($_GET['videocode']);
in order to put every kind of data related to the selected video in the edit form:
<form action="edit_portfolio_video.php?videoid=<?php echo $selected_video['video_code']; ?>" method="post">
<input type="text" name="video_title" value="<?php echo $selected_video['video_title']; ?>" />
</p>
<p>Video Code (vimeo):<br />
<input type="text" name="video_code" value="<?php echo $selected_video['video_code']; ?>" />
</p>
<p>Video Description:<br/>
<textarea name="video_description" rows="5" cols="70"><?php echo $selected_video['video_description']; ?></textarea>
</p>
<p>
<input type="submit" name="submit" value="Save Video" />
</p>
</form>
But the form's fields don't get populated, as there seems to be a problem with the $video variable I'm trying to get (returned from get_selected_video_by_id function). The video code is stored as "INT" (length: 11) in the database and is printed as string in the 2nd page's URL. I've tried to write the function's query in many ways but I can't get it to work.
I'd appreciate some help on this, thank you all.
Note: The confirm_query function does this simple job:
function confirm_query($result_set) {
if (!$result_set) {
die("Database query failed: " . mysql_error());
}
}
I think you should try this instead for your get_selected_video_by_id SQL query.
$query = "SELECT * FROM portfolio_videos WHERE video_code = ".$video_code;
Of course watch out for SQL injection in your parameters, and also, as someone already suggested please consider using PDO or MySQLi.
Your Form seems strange:
you are using a POST mode to pass a GET value (edit_portfolio_video.php?videoid=...etc...).
But this shouldn't be the problem.
In this line:
$selected_video = get_selected_video_by_id($_GET['videocode']);
are you sure the GET parameter you are passing is videocode? Or is it videoid?

Loop results executing twice

I creating a simple site with PHP where the users can submit blogs and other users (who are logged in) can post comments on them. I have made a link called "comments" below each blog that when clicked will show / hide all the comments relevant to the specific blog (also if the user is logged in, it will show a form field in which they can submit new comments). So basically each blog will have multiple comments. I have done two different codes for this but they both have the same problem that each comment appears twice (everything else works fine). Could anyone point out why?
mysql_select_db ("ooze");
$result = mysql_query ("select * from blog") or die(mysql_error());
$i = 1;
while($row = mysql_fetch_array($result))
{
echo "<h1>$row[title]</h1>";
echo "<p class ='second'>$row[blog_content]</p> ";
echo "<p class='meta'>Posted by .... • $row[date] • Comments<div id='something$i' style='display: none;'>";
$i++;
$a = $row["ID"];
$result2 = mysql_query ("select * from blog, blogcomment where $a=blogID") or die(mysql_error());
while($sub = mysql_fetch_array($result2))
{
echo "<p class='third' >$sub[commentdate] • $sub[username]</p><p>said:</p> <p>$sub[comment]</p>";
}
if ( isset ($_SESSION["gatekeeper"]))
{
echo '<form method="post" name="result_'.$row["ID"].'" action="postcomment.php"><input name="ID" type = "hidden" value = "'.$row["ID"].'" /><input name="comment" id="comment" type="text" style="margin-left:20px;"/><input type="submit" value="Add comment" /></form>';
}
else
{
echo '<p class="third">Signup to post a comment</p>';
}
echo "</div>";
}
mysql_close($conn);
//second version of inner loop://
if ( isset ($_SESSION["gatekeeper"]))
{
while($sub = mysql_fetch_array($result2))
{
echo "<p class='third' >$sub[commentdate] • $sub[username] said:</p> <p>$sub[comment]</p>";
}
echo '<form method="post" name="result_'.$row["ID"].'" action="postcomment.php"><input name="ID" type = "hidden" value = "'.$row["ID"].'" /><input name="comment" id="comment" type="text" style="margin-left:20px;"/><input type="submit" value="Add comment" /></form>';
}
else
{
while($sub = mysql_fetch_array($result2))
{
echo "<p class='third' >$sub[commentdate] • $sub[username] said:</p> <p>$sub[comment]</p>";
}
echo '<p class="third">Signup to post a comment</p>';
}
echo "</div>";
}
mysql_close($conn);
Your problem lies in this query from the first example.
$result2 = mysql_query ("select * from blog, blogcomment where $a=blogID")
You have already queried the blog table so there is no need to query it again. Simply changing this to
$result2 = mysql_query ("select * from blogcomment where $a=blogID")
should solve the problem.
However there are many things you need to think about.
Why are you re-inventing the wheel? There are plenty of good blog applications out there. You'd be better off using one of them.
It's not recommended to use the mysql_ family of functions any more. Go away and learn mysqli_ or better still PDO.
You should learn about separation of concerns. At the very least you should make sure your data access/business logic is separate from your display logic. MVC is very common in PHP.
You should also learn about JOINs. Even in this simple inline script you have a query within a loop which is not very efficient. You can combine your queries into one (as you've tried with the inner query). The difference is the one query should be outside your main loop.

Categories