my links are not redirecting properly - php

after running a search in my database the results show up in form of a link so that they redirect me to a particular page...for example when i search for a category business it shows that category but when i click on it it redirects me to the contents of another category..when i checked my url and i noticed its like
http://mysite/forum%20part%20two/view_category.php?cid=1
instead of
http://mysite/forum%20part%20two/view_category.php?cid=2
this my search code
if(isset($_POST['search'])){ //form submitted, clicked Submit Search
$query = strip_tags(mysql_real_escape_string($_POST['query'])); //try to prevent sql injections
if(!$query){ //not enterered a query
echo 'You must enter a search query!';
}else{
//EDIT THIS ----------------------------------
$table = 'categories'; //the table you want to search
$row = 'category_title'; //the row in which you want to search
//EDIT THIS ----------------------------------
$sql = mysql_query("SELECT * FROM `".$table."` WHERE `".$row."` LIKE '%".$query."%'"); //search query
if($sql){ //no errors
if(mysql_num_rows($sql) == 0){ //No results found.
echo 'No results were found for <strong>'.$query.'</strong>';
}else{ //one or more results have been found
echo 'We have found <strong>'.mysql_num_rows($sql).'</strong> for <strong>'.$query.'</strong>.<br><br>
<table>
<tbody>
<tr>
<td><strong>category_title</strong></td>
</tr>';
while($r = mysql_fetch_array($sql)){ //get data of every user where their category_title is like the $query string
$category_title = $r["category_title"];
//lets put the part they searched in bold.
$category_title = str_ireplace($query, '<strong>'.$query.'</strong>', $category_title);
//lets put the part they searched in bold.
echo '<td>'.$category_title."<a href='view_category.php?cid=".$id."' class='cat_links'>".$category_title." - <font size='-1'>".$description."</font></a></td>
</tr>'";
}
echo '</tbody></table>';
}
}else{
echo 'Sorry, an MySQL error occurred:<br><br>'.mysql_error(); //an error occurred, so echo it
}
}
}
my view_category.php code is this
<?php
// Connect to the database
include_once("connect.php");
// Function that will count how many replies each topic has
function topic_replies($cid, $tid) {
$sql = "SELECT count(*) AS topic_replies FROM posts WHERE category_id='".$cid."' AND topic_id='".$tid."'";
$res = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($res);
return $row['topic_replies'] - 1;
}
// Function that will convert a user id into their username
function getusername($uid) {
$sql = "SELECT username FROM users WHERE id='".$uid."' LIMIT 1";
$res = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($res);
return $row['username'];
}
// Function that will convert the datetime string from the database into a user-friendly format
function convertdate($date) {
$date = strtotime($date);
return date("M j, Y g:ia", $date);
}
// Assign local variables
$cid = $_GET['cid'];
// Check to see if the person accessing this page is logged in
if (isset($_SESSION['username'])) {
$logged = " | <a href='create_topic.php?cid=".$cid."'>Click Here To Create A Topic</a>";
} else {
$logged = " | Please log in to create topics in this forum.";
}
// Query that checks to see if the category specified in the $cid variable actually exists in the database
$sql = "SELECT id FROM categories WHERE id='".$cid."' LIMIT 1";
// Execute the SELECT query
$res = mysql_query($sql) or die(mysql_error());
// Check if the category exists
if (mysql_num_rows($res) == 1) {
// Select the topics that are associated with this category id and order by the topic_reply_date
$sql2 = "SELECT * FROM topics WHERE category_id='".$cid."' ORDER BY topic_reply_date DESC";
// Execute the SELECT query
$res2 = mysql_query($sql2) or die(mysql_error());
// Check to see if there are topics in the category
if (mysql_num_rows($res2) > 0) {
// Appending table data to the $topics variable for output on the page
$topics = "<table width='100%' style='border-collapse: collapse;'>";
$topics .= "<tr><td colspan='4'><a href='index.php'>Return To Forum Index</a>".$logged."<hr /></td></tr>";
$topics .= "<tr style='background-color: #dddddd;'><td>Topic Title</td><td width='65' align='center'>Last User</td><td width='65' align='center'>Replies</td><td width='65' align='center'>Views</td></tr>";
$topic = "<tr><td colspan='4'><hr /></td></tr>";
// Fetching topic data from the database
while ($row = mysql_fetch_assoc($res2)) {
// Assign local variables from the database data
$tid = $row['id'];
$title = $row['topic_title'];
$views = $row['topic_views'];
$date = $row['topic_date'];
$creator = $row['topic_creator'];
// Check to see if the topic has every been replied to
if ($row['topic_last_user'] == "") { $last_user = "N/A"; } else { $last_user = getusername($row['topic_last_user']); }
// Append the actual topic data to the $topics variable
$topics .= "<tr><td><a href='view_topic.php?cid=".$cid."&tid=".$tid."'>".$title."</a><br /><span class='post_info'>Posted by: ".getusername($creator)." on ".convertdate($date)."</span></td><td align='center'>".$last_user."</td><td align='center'>".topic_replies($cid, $tid)."</td><td align='center'>".$views."</td></tr>";
$topics .= "<tr><td colspan='4'><hr /></td></tr>";
}
$topics .= "</table>";
// Displaying the $topics variable on the page
echo $topics;
} else {
// If there are no topics
echo "<a href='index.php'>Return To Forum Index</a><hr />";
echo "<p>There are no topics in this category yet.".$logged."</p>";
}
} else {
// If the category does not exist
echo "<a href='index.php'>Return To Forum Index</a><hr />";
echo "<p>You are trying to view a category that does not exist yet.";
}
?>
sorry for pasting alot of code

echo '<td>'.$category_title."<a href='view_category.php?cid=".$id."' class='cat_links'>".$category_title." - <font size='-1'>".$description."</font></a></td>
</tr>'";
That variable $id is not being obtained from anywhere, thats probably why. Please fetch its value from your query result near this
$category_title = $r["category_title"];
Probably id would be
$id = $r["id"];

Related

Error ERR_EMPTY_RESPONSE when display image

I have this code has been working for few months without any problem. Now this page does not work and the problem from php code but I dont know where
<?php
$query = "SELECT * FROM offerimage order by name";
$result = mysqli_query($connection, $query);
if ($result->num_rows > 0) {
echo "<table>";
while($row = $result->fetch_assoc()) {
echo "<tr>";
$image = '<img src="data:image/jpeg;base64,'.base64_encode($row['image'] ).'" height="100" width="100"/>';
//echo '<br></br>';
echo $image;
echo '<br></br>';
echo "</tr>";
}
} else {
echo "</table>";
}
?>
I GET THIS ERROR
"ERR_EMPTY_RESPONSE"
Why don't you output something when the query returns no rows, since that's probably the cause?
Also you should have the images inside a <td> element.
Edited to show row-by-row retrieval of images. Assumes the database table offerimage has a unique integer ID (like an AUTO_INCREMENT column) named id, change queries to match the actual table definition.
<?php
// get array of offerimage IDs ordered by name
$query = "SELECT id FROM offerimage order by name";
$result = mysqli_query($connection, $query);
$ids = [];
while ($row = $result->fetch_assoc()) {
$ids[] = (int)$row['id'];
}
if (count($ids) > 0) {
// display each image
echo '<table>';
foreach ($ids as $id) {
$query = "SELECT image FROM offerimage WHERE id = {$id}";
$result = mysqli_query($connection, $query);
$row = $result->fetch_assoc();
echo "<tr><td>";
echo '<img src="data:image/jpeg;base64,'.base64_encode($row['image'] ).'" height="100" width="100"/>';
echo "</td></tr>";
mysqli_free_result($result);
}
echo "</table>";
} else {
echo "<p>No offers found.</p>";
}
Other suggestions: Don't use SELECT * if you only need one column. Use SELECT image instead.
Check for errors when making the database connection (you don't show that code) and from the query, use error_log() or send to the browser so you can see if something went wrong there.
I solve it by save images in folder and then save image location in DB.

When I display this page the PHP part of the code is not working. It will not display the topics

Code will not display topics from database. I just get a blank pages.
Any solutions?
The pages loads but it will not display any thing. They want me to add more context but it breaks it so here you go.
<?php
//Database stuff.
include_once("connect.php");
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}else{
mysqli_select_db($conn,"2159928_db");
}
$tid = '';
$cid = $_GET['cid'];
$tid = $_GET['tid'];
$sql = "SELECT * FROM topics WHERE category_id='".$cid."' AND id='".$tid."' LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1){
echo "<table width ='75%'>";
if (isset($_SESSION['uid'])) {
//echo "<form action ='post_reply.php?cid=".$cid." &tid =".$tid. "' method = 'post'>
//<input type = 'submit' name = 'submit' value = 'Reply'/>";
//echo "<tr><td colspan ='2'><center><input type='submit' value='Reply' onClick = 'window.open = 'post_reply.php?cid=".$cid." &tid =".$tid."' />";
echo "<tr><td colspan ='2'><center><input type='submit' value='Reply' onClick='window.open(\"post_reply.php?cid=$cid&tid=$tid\")' />";
} else {
echo "<tr><td colspan = '2'><p><center> Please login to reply to topics.</p></td></tr>";
}
//Trying to display this. Doesn't even display border box.
while ($row = mysqli_fetch_assoc($result)) {
$sql2 = "SELECT * FROM posts WHERE category_id='".$cid."' AND topic_id='".$tid. "'";
$result2 = mysqli_query($conn, $sql2);
while ($row2 = mysqli_fetch_assoc($result2)){
echo "<tr><td valign ='top' style = 'border: 5px solid #ffffff;'><div style = 'min-height: 125px;'>".$row['topic_title']."<br/>
by ".$row2['post_username']. " - " .$row2['post_date']. "<hr/>".$row2['post_content']."</div></td>";
}
//This part not relevant.
$old_views = $row['topic_views'];
$new_views = $old_views + 1;
$sql3 = "UPDATE topics SET topic_views='".$new_views."' WHERE category_id='".$cid."' AND id ='".$tid."' LIMIT 1";
$result3 = mysqli_query($conn, $sql3);
}
echo "</table>";
} else {
echo "<p>This topic does not exist.</p>";
}
?>
Try echo-ing out your $sql to see if the query is correct.
If query is correct. Try var_dump to see if there are any results.

insert from sql data record in the table to another table

i have two tables
students table
csci01members table
I will put the student record in the csci01members, my code doesn't have a syntax error.
But it always get's stuck in "The user is already a member". EVEN if he's not ,I already got the code of adding the record.
but i need an error trapping so that if the user is
already in the csci01members table. it can't add the record or
he cannot view the members of csci01 so that the member already will not be seen
in the list of adding into table.
<?php
$errors="";
if(isset($_GET['add']))
{
$con = mysql_connect("localhost","root","");
if(!$con)
{ die("could not connect to server".mysql_error()); }
mysql_select_db("login", $con);
if (empty($errors)){
$check = mysql_query("SELECT * from csci01members");
$check_count = mysql_num_rows($check);
if ($check_count == 1) {
die (" The user is already a member.");
}
}
$result = mysql_query("SELECT * from students where username='$_GET[add]'");
$result_count = mysql_num_rows($result);
if ($result_count == 0) {
echo "<font color=red><br /> The user doesn't exists.</font>";
}
else
{
while($row = mysql_fetch_array($result))
{
echo "Student Number: $row[username]<br>Name: $row[namelast]
, $row[namefirst]<br><br> was added to the group<br><br>";
$sn = $row['username'];
$nl = $row['namelast'];
$nf = $row['namefirst'];
$nm = $row['namemi'];
mysql_query("INSERT INTO csci01members (username, namelast, namefirst, namemi)
VALUES ('$sn', '$nl', '$nf', '$nm')");
mysql_close($con);
}
}
}
$con = mysql_connect("localhost","root","");
if(!$con)
{ die("could not connect to server".mysql_error());}
mysql_select_db("login", $con);
$sql="Select * from students";
$sql_result=mysql_query($sql)
or exit("Sql Error".mysql_error());
$sql_num=mysql_num_rows($sql_result);
if($row = mysql_num_rows($sql_result) == 0)
{
echo "There are no registered student yet<br><br>";
$name=$row["username"];
$class=$row["namelast"] .$row["namefirst"];
$accept = "<a href='?add=$row[username]'> </a>";
}
else
{
echo "<table border = 0 width=\"200%\">";
echo "<tr>";
echo "<td width = '20%' > <b><center>USN</center></b></td>
<td width = '60%'><b><center>Name</center></b></td>
<td width = '10%'><b><center>Action</center></b></td>";
echo "</tr>";
while($sql_row=mysql_fetch_array($sql_result))
{
$name=$sql_row["username"];
$class=$sql_row["namelast"] . ', '.$sql_row["namefirst"];
$accept = "<a href='?add=$sql_row[username]'>[Add]</a>";
echo "<td >".$name."</td>";
echo "<td>".$class."</td>";
echo "<td>".$accept."</td></tr>";
}
}
echo "</table>";
mysql_close();
?>
Your "count_check" count all rows in table, you needs count rows with added username
if (empty($errors)){
$check = mysql_query("SELECT * from csci01members WHERE username = '".mysql_real_escape_string($_GET['add'])."'");
$check_count = mysql_num_rows($check);
if ($check_count == 1) {
die (" The user is already a member.");
}
}
And for add identificator better use numeric id. Username may contain special symbols like space or something else, and when you will pass them by url, them being encoded

PHP code not working in IE8

I've got a baffling IE8 PHP problem. The code below works fine in chrome and FF but not IE8. The form is submitting, errors are displayed if no search term or check-boxes selected, and if both db searches fail the No Actors and No Movies found echo's are both displayed. But if either one of the searches is successful nothing is displayed, not even the Actors/Movies found echo which has me stumped.
Here's the code:
<?php
if($_POST[submitbutton]){
$search = trim(mysql_real_escape_string($_POST[search]));
if(!$search){
echo "Please enter a search term!";
}else if(!$_POST['checkbox']){
echo "Please select at least one database to search!";
}else{
//search names
if(in_array("actors", $_POST['checkbox'])){
$query = mysql_query("SELECT name_id, realname, mainalias FROM names WHERE realname LIKE '%$search%' OR mainalias LIKE '%$search%'");
if(mysql_num_rows($query)==0){
echo "<h2>No Actors by that name found!</h2>", "<p>";
}else{
echo "<h2>Actors Found:</h2>";
while ($record = mysql_fetch_assoc($query)){
$realname = $record['realname'];
$name_id = $record['name_id'];
echo "<a href='index.php?page=name&id=$name_id'>", $realname, "</a><hr>";
}
}
}
//search titles
if(in_array("movies", $_POST['checkbox'])){
$query = mysql_query("SELECT title_id, title FROM titles WHERE title LIKE '%$search%'");
if(mysql_num_rows($query)==0){
echo "<h2>No Movies by that name found!</h2>", "<p>";
}else{
echo "<h2>Movies Found:</h2>";
while ($record = mysql_fetch_assoc($query)){
$title = $record['title'];
$title_id = $record['title_id'];
echo "<a href='index.php?page=title&id=$title_id'>", $title, "</a><br>";
echo "<hr>";
}
}
}
}
} //end post submitbutton
?>
Should
$search = trim(mysql_real_escape_string($_POST[search]));
be
$search = trim(mysql_real_escape_string($_POST['search']));
I don't know if that has anything to do with your problem, but it jumper out at me.
<?php
if(isset($_POST['submitbutton'], $_POST['search'])){ //use isset for check exists vars
$search = trim(mysql_real_escape_string($_POST['search'])); // ['POST vars']
if(!$search){
echo "Please enter a search term!";
}else if(!isset($_POST['checkbox'])){
echo "Please select at least one database to search!";
}else{
//search names
if(in_array("actors", $_POST['checkbox'])){
$query = mysql_query("SELECT name_id, realname, mainalias FROM names WHERE realname LIKE '%$search%' OR mainalias LIKE '%$search%'");
if(mysql_num_rows($query)==0){
echo "<h2>No Actors by that name found!</h2>", "<p>";
}else{
echo "<h2>Actors Found:</h2>";
while ($record = mysql_fetch_assoc($query)){
$realname = $record['realname'];
$name_id = $record['name_id'];
echo "<a href='index.php?page=name&id=$name_id'>", $realname, "</a><hr>";
}
}
}
//search titles
if(in_array("movies", $_POST['checkbox'])){
$query = mysql_query("SELECT title_id, title FROM titles WHERE title LIKE '%$search%'");
if(mysql_num_rows($query)==0){
echo "<h2>No Movies by that name found!</h2>", "<p>";
}else{
echo "<h2>Movies Found:</h2>";
while ($record = mysql_fetch_assoc($query)){
$title = $record['title'];
$title_id = $record['title_id'];
echo "<a href='index.php?page=title&id=$title_id'>", $title, "</a><br>";
echo "<hr>";
}
}
}
}
} //end post submitbutton
?>

MYSQL select comments, limit 3, 'click to see all' and display on same page. PHP

I have some code which retrieves user comments from my database:
$comments = mysql_query("SELECT * FROM comments WHERE ref = '$theID'LIMIT 0, 3;")
or die(mysql_error());
while ($rowC = mysql_fetch_array($comments)) {
echo "<p>On " .$rowC['date']. ", ";
echo $rowC['username']. " said: <br/>";
echo $rowC['comment'];
echo "</p><hr/>";
}
if (mysql_num_rows($comments) == 0) {
echo "<p>(No comments have been made yet)</p>";
}
Comments are stored with a unique user reference in the database, and retrieved where they match the user id, this is called at the top of the page:
$theID = $_GET['id'];
What I am trying to do is limit the comments shown, and if there are more than 3, show a 'click to see more' type button or link which displays all the user comments on the same page in the same way as above.
UPDATE, i am now using this, Trying to implement Johan's suggestion, but still cant get it to display more when link is clicked:
$comments = mysql_query("SELECT * FROM comments WHERE ref = '$theID' LIMIT 0, 4") or die(mysql_error());
while ($rowC = mysql_fetch_array($comments)) {
echo "<p>On " .$rowC['date']. ", ";
$username = htmlspecialchars($rowC['username']). " said: <br/>";
echo $username;
$comment = htmlspecialchars($rowC['comment']);
echo $comment;
echo "</p><hr/>";
}
$num_rows = mysql_num_rows($result);
if ($num_rows > 3) {
$query = "SELECT * FROM comments WHERE ref = '$theID' LIMIT 4, 20";
} echo "<p><a href=''>click to see more</a></p>";
if (mysql_num_rows($comments) == 0) {
echo "<p>(No comments have been made yet)</p>";
}
Try this:
<?
if($_GET['allcomments'] == 1 && preg_match("/([0-9]+)/", $_GET['id'])){
$comments = mysql_query("SELECT * FROM comments WHERE ref = '".$_GET['id']."'") or die(mysql_error());
for($c=0; ($rowC = mysql_fetch_array($comments)) !== FALSE; $c++) {
echo "<p>On " .$rowC['date']. ", ";
echo htmlentities($rowC['username']). " said: <br/>";
echo htmlentities($rowC['comment']);
echo "</p><hr/>";
}
}else{
$comments = mysql_query("SELECT * FROM comments WHERE ref = '$theID' LIMIT 0, 4;" ) or die(mysql_error());
for($c=0; ($rowC = mysql_fetch_array($comments)) !== FALSE; $c++) {
echo "<p>On " .$rowC['date']. ", ";
echo htmlentities($rowC['username']). " said: <br/>";
echo htmlentities($rowC['comment']);
echo "</p><hr/>";
if($c == 3){
echo "<p><a href='?allcomments=1&id=$theID'>click to see more</a></p>";
break;
}
}
if (!$c) {
echo "<p>(No comments have been made yet)</p>";
}
}
?>
I consider that $theID variable contains only digits from 0 to 9. If not, change the regular expression (preg_match).
Yikes: You have a couple of error/issues.
SQL-injection
$theID = $_GET['id'];
Fix this to
$theID = mysql_real_escape_string($_GET['id']);
To get rid of a gaping SQL-injection hole.
See: How does the SQL injection from the "Bobby Tables" XKCD comic work?
XSS vulnerability
Replace this code:
echo $rowC['username']. " said: <br/>";
echo $rowC['comment'];
With this
$username = htmlspecialchars($rowC['username']). " said: <br/>";
echo $username;
$comment = htmlspecialchars($rowC['comment']);
echo $comment;
See: Do htmlspecialchars and mysql_real_escape_string keep my PHP code safe from injection?
And: When is it Best to Sanitize User Input?
Error in code
Change this:
$comments = mysql_query("SELECT * FROM comments WHERE ref = '$theID'LIMIT 0, 3;")
To this
$comments = mysql_query("SELECT * FROM comments WHERE ref = '$theID' LIMIT 0, 3")
Back to the question
if you change the query to:
SELECT * FROM comments WHERE ref = '$theID' LIMIT 0, 4"
Then you can check the number of results returned. If it's 4 then display the more... button.
Use this query to get 20 more results
$num_rows = mysql_num_rows($result);
if $num_rows > 3 {
$query = "SELECT * FROM comments WHERE ref = '$theID' LIMIT 4, 20";
...

Categories