php Mysql Error unknown id - php

I'm trying to make a blog in PHP/MySQL and have got 2 tables
posts (id int(6),cat_id int(3),title varchar(255),contents text)
categories (cat_id int(11),name varchar(24)).
I am getting an error - 'Unknown column 'id' in 'where clause'' when I try to run edit function.
<?php
include_once('resources/init.php');
$post=get_posts($_GET['id']);
if(isset($_POST['title'],$_POST['contents'],$_POST['category']))
{
$title=trim($_POST['title']);
$contents=trim($_POST['contents']);
edit_post($_GET['id'],$title,$contents,$_POST['category']);
header("Location:index.php?id=$post[0]['posts.id']");
die();
}
?>
Here is the edit function -
function edit_post($id,$title,$contents,$category)
{
$id=(int)$id;
$title=mysql_real_escape_string($title);
$category=(int)$category;
$contents=mysql_real_escape_string($contents);
mysql_query("UPDATE posts SET cat_id= {$category},
title='{$title}',
contents='{$contents}'
WHERE id={$id}");
}
You might need to refer get_posts function-
function get_posts($id=null,$cat_id=null){
$posts=array();
$query=("SELECT posts.id AS post_id, categories.cat_id AS category_id,
title, contents,
categories.name AS name
FROM posts
INNER JOIN categories ON categories.cat_id = posts.cat_id");
if (isset($id)) {
$id=(int)$id;
$query .= " WHERE posts.id={$id}";
}
if(isset($cat_id)) {
$cat_id=(int)$cat_id;
$query .=" WHERE categories.cat_id={$cat_id}";
}
$query .= " ORDER BY posts.id DESC";
$query = mysql_query($query);
while($row=mysql_fetch_assoc($query)) {
$posts[]=$row;
}
return $posts;
}
I have referred the solutions provided for this type of error on the site but it wasn't helpful for my case. Please help.

check if Id is set in your url, try this approach
include_once('resources/init.php');
if(isset($_GET['id'],$_POST['title'],$_POST['contents'],$_POST['category']))
{
$post=get_posts($_GET['id']);
$title=trim($_POST['title']);
$contents=trim($_POST['contents']);
edit_post($_GET['id'],$title,$contents,$_POST['category']);
$id = $post[0]['posts.id'];
echo $id;
header("Location:index.php?id=".$id);
die();
}

You shouldn't run your first script directly, it should be runned with form submit with id input inside.

Related

COUNT() Function Does Not Return Number Of Rows

I'm working on a blogging system website. In this blogging system, I have two tables. One is called blogs which simply contains the information of a blog (such as blog_title, blog_author, blog_category).
And the other one is called categories which only contains the blog_category names of blog posts.
Now I have made a page where users can see the blog categories and the number of blog posts within that custom category name.
So here is how it looks like:
And this is the code behind of that:
foreach($catShow as $cat){
echo "
<tr>
<td>".$cat['table_id']."</td>
<td>".$cat['cat_title']."</td>
<td>".$cat['cat_id']."</td>
<td>".num_cats($cat['cat_id'])."</td>
<td></td>
</tr>";
}
So the function num_cats() basically counts the number of blog posts at blogs table which has the same blog category id (cat_id):
function num_cats($id){
$num_cats = "SELECT COUNT(*) FROM blogs WHERE blog_category = '$id'";
$run_num = mysqli_query($GLOBALS['con2'],$num_cats);
$return = '';
if (!$run_num) {
die(mysqli_error($GLOBALS['con2']));
}
$numCat = mysqli_num_rows($run_num);
$return .= "
$numCat
";
return $return;
}
But now the problem is, the result is incorrect. I mean the table only shows 1 result for each category however some of them have more than one item at the blogs table.
So what is wrong with this code, can you please help me with that!
"SELECT COUNT() FROM blogs WHERE blog_category = '$id'"
will return one row. So $numCat becomes 1.
You need to fetch your query result and get the value from COUNT()
function num_cats($id){
$num_cats = "SELECT COUNT(*) AS count FROM blogs WHERE blog_category = '$id'";
if ($result = mysqli_query($GLOBALS['con2'], $num_cats)) {
$row = mysqli_fetch_assoc($result);
return $row['count'];
} else {
die(mysqli_error($GLOBALS['con2']));
}
}
Use join for better performance
$sql = "Select table_id,cat_title,bc.cat_id,count(b.category_id) as total_post from blog b inner join blog_category bc on b.blog_category_id=bc.blog_category_id group by b.category_id";
$result = mysqli_query($GLOBALS['con2'],$sql);
while($cat = $result->mysqli_fetch_row()){
echo "
<tr>
<td>".$cat['table_id']."</td>
<td>".$cat['cat_title']."</td>
<td>".$cat['cat_id']."</td>
<td>".$cat['total_post']."</td>
<td></td>
</tr>";
}
COUNT will give number of blog_category in your database. so in the result have only one recode with category count.
but you calling mysqli_num_rows this again. so, result will be 1 always.
just remove mysqli_num_rows($run_num); and update query with result col name,
SELECT COUNT(*) AS `total` FROM blogs WHERE blog_category = '$id'
then call
$row = mysqli_fetch_object($run_num);
$numCat = $row->total;

Why while loop in function only return 1 row data?

I'm doing a function(), and I want to show all the data when I call the function in the foreach loop.
Suddenly while the function is not working, it only returns the first row of data, but in the database has 2 rows of data.
Below is my code:
function getComments($conn,$postId){
$commentSql = " SELECT comments.id, comments.user_id, comments.user_desc, comments.timestamp, user.firstname, user.lastname
FROM comments
INNER JOIN user
ON user.id = comments.user_id
WHERE post_id = ? ";
if($commentStmt = $conn->prepare($commentSql)){
$commentStmt->bind_param("i", $postId);
$commentStmt->execute();
$commentStmt->bind_result($commentId, $userId, $userComment, $comment_timestamp, $user_firstname, $user_lastname);
while ($commentStmt->fetch()) {
echo "user dec: $userComment comment id: $commentId";
}
$commentStmt->close();
}else{
return "error preparing sql";
}
}
When I call function in for each loop:
echo getComments($conn,$post_id);
Table comments:
My Current output showing 1-row data only:
WHERE post_id = ? ";
you are passing a post id which is different in two comments. One is with id 6 another is with 9.

How to get a session value from a second table?

I have two tables for the users; a login table and the user profile table.
I want to compare a value from 'userprofiletable' to another value from another table called posts. If the value is equal, it shows a list.
I have the following code. The problem is that it is not comparing the value in the posts table with the value of the session from user profile table.
Could someone help me please?
<?php
$limit = '5';
$dbreq = 'SELECT * FROM `posts` ORDER BY `pos` DESC';
$dbdata = mysql_query($dbreq);
while($dbval = mysql_fetch_array($dbdata))
{
if (($dbval['city'] == $_SESSION['student_city'])) { //checks for last 4 accomodation
if ($limit >= '1') {
echo '<tr><td>'.$dbval['title'].'</td></tr>';
$limit = $limit -'1';
}
}
}
?>
I also want to get the value of userprofiletable and post it in the posts table. For example, when somebody make a new post.
Your post is a bit unclear, but I think this is what you want:
<?php
$userid = 11542;//Sample uid. You will have to figure this out and set it.
$limit = 5;
$dbreq = "SELECT * FROM `posts` WHERE `userid`=".$userid." ORDER BY `pos` DESC LIMIT=".$limit.";";
$dbdata = mysql_query($dbreq);
while($dbval = mysql_fetch_array($dbdata))
{
if (($dbval['city'] == $_SESSION['student_city'])) { //checks for last 4 accomodation
echo '<tr><td>'.$dbval['title'].'</td></tr>';
}
}
?>
The question is not clear, but there could be two answers:
To reproduce your code, you can do in ONE sql query:
$dbreq = 'SELECT *
FROM `posts`
WHERE city="'.mysql_real_escape_string($_SESSION['student_city']).'"
ORDER BY `pos` DESC
LIMIT 4';
If, however, there are two tables, then you need "LEFT JOIN" linking the posts table to the userprofile table
$dbreq = 'SELECT p.*, u.*
FROM posts p
LEFT JOIN userprofiletable up ON p.UserID=up.UserID
WHERE up.city="'.mysql_real_escape_string($_SESSION['student_city']).'"
ORDER BY p.pos DESC
LIMIT 4';
(UserID in the table above is the name of the field in the posts table and userprofiletable that links the two.)

PHP MYSQL showing posts with comments

I dont know where to start let me make it simple...
I have 2 tables posts and comments, posts consisting 2 fields: id and post_name and comments consisting of 3 fields: id, comment and post_id. I have some posts with few comments on those.
How can I display all posts with the related comments using while loop?
Thanks in advance....
SELECT `p`.`post_name`, `c`.`comment`
FROM `posts` AS `p`
JOIN `comments` AS `c` ON(`p`.`id` = `c`.`post_id`)
GROUP BY `p`.`id`;
This will give you a resultset where each row contains a comment and the name of the post that goes with that comment.
You'll need a nested loop to accomplish what you are looking for. Here's a sample that should help get you started.
$posts_result = mysql_query("SELECT your, columns FROM poststable");
if(mysql_num_rows($posts_result) > 0){
$comments_result = mysql_query("SELECT comments FROM commentstable WHERE comments.post_id = $post_id");
while($post = mysql_fetch_array($posts_result){
// print post details
if(mysql_num_rows($comments_result) > 0){
while($comment = mysql_fetch_array($comments_result)) {
// print comment details
}
} else {
// print comments default for when there are no comments
}
} // End posts while
} else {
// print no posts found
}
Run query
select * from posts p, comments c where p.id=c.post_id group by p.id;
and iterate over the results and display them as you want.
This should get you started:
$sql = 'SELECT c.*, p.post_name FROM posts p INNER JOIN comments c ON p.id = c.post_id ORDER BY p.id DESC, c.post_id DESC';
$result = mysql_query($sql);
$previous_post = 0;
while ($data = mysql_fetch_assoc($result)) {
if ($previous_post != $data['post_id']) {
echo '<h1>' . $data['post_name'] . '</h1>';
$previous_post = $data['post_id'];
}
echo '<p>' . $data['comment'] . '</p>';
}

PHP, SQL newbie help

I have the following table:
Comments
--------
id PK
cid
content
uid
comment
If the content is image /i want it to print ?imgID=$cid and get the data from the row title from the table images and if it's a thread I want it to print ?threadID=$cid and get the title from the table threads and so on. How should I do this?
<h3>Latest comments</h3>
<?php
$rs = mysql_query("
SELECT *
FROM comments
LEFT JOIN threads
ON threads.id = comments.cid
WHERE comments.uid = $id
");
while ($row = mysql_fetch_assoc($rs)) {
echo $row['title'];
}
while ($row = mysql_fetch_assoc($rs)) {
if($row['content'] == "image") {
echo "?imgID={$cid}";
$title = mysql_fetch_assoc(mysql_query("SELECT title from images WHERE id = '$cid'");
} elseif ($row['content'] == "thread") {
echo "?threadID={$cid}";
$title = $row['title']; // Will only work as long as there is no title field in comments, oherwise use threads.title
}
}
echo $title;
There you go. The curly brackets around the $cid aren't strictly nessecary, but they help avoid issues where if you are trying to print text afterwards, and it reads the variable name as something else.
$q="SELECT c.id, c.cid, c.content, c.uid, c.comment,
COALESCE(t.title,i.title) AS the_title
FROM comments c LEFT JOIN threads t ON (c.cid=t.id AND c.content='thread')
LEFT JOIN images i ON (c.cid=i.id AND c.content='image');
The above combines your two queries together and puts the title attribute in one column.

Categories