PHP blog tut, post and comments fail insert [Solved]

Post here is you are having problems with any of the tutorials.
Post Reply
User avatar
wuxmedia
Posts: 11
Joined: Mon Oct 22, 2012 10:39 pm

PHP blog tut, post and comments fail insert [Solved]

Post by wuxmedia »

Hi, i've been typing this blog in for weeks now. (i'm a bit slow) :shock:

i've worked out a load of errors already - backticks, basic connection etc.
(so +1 for not releasing the code) but i'm stumped.

i keep scanning the code and watching the youtube vids, but my eyes don't seem to work anymore.

in phpmyadmin i've added some dummy data, 'get' works fine. if i type it into MySQL, no probs.

i've added some var dumps(for POST) to see if the form is picking up the data and it seems so.
adding a comment does nothing, takes me to blogread?pid=(n) but no php shows. if i hit 'enter' in the browser location bar, the post comes up but no comments(i've tested the mysql functions in mysql putting real data instead of php vars)
testing the blogpost page lets me post data according to the var dump; but never arrives in the table 8(

array(2) { ["user"]=> string(9) "title box" ["body"]=> string(20) "this is the body box" }


so hope fully i've just missed a comma or something. heres the rest, for your perusal

thanks in advance 8)

i did change the page names. and the html's a bit basic.

Comments;
[syntax=php]<?php
// gets comments for a blog post

function get_comments($pid){

$pid = (int)$pid;

$sql = "SELECT
`comment_body` AS `body`,
`comment_user` AS `user`,
DATE_FORMAT(`comment_date`, '%d/%m%Y %H:%i:%s') AS `date`
FROM `comments`
WHERE `post_id` = {$pid}";


$comments = mysql_query($sql);

$return = array();
while (($row = mysql_fetch_assoc($comments)) !== false){
$return[] = $row;
}

return $return;
}


function add_comment($pid, $user, $body){
if (valid_pid($pid) === false){
return false;
}

$pid = (int)$pid;
$user = mysql_real_escape_string(htmlentities($user));
$body = mysql_real_escape_string(nl2lb(htmlentities($body)));

mysql_query("INSERT INTO `comments` (`post_id`, `comment_user`, `comment_body`, `comment_date`) VALUES ({$pid}, '{$user}', '{$body}', NOW())");
echo mysql_error();
return true;

}

?>

[/syntax]


posts;
[syntax=php]<?php

// checks for a valid post
function valid_pid($pid){

$pid = (int)$pid;
$total = mysql_query("SELECT COUNT(`post_id`) FROM `posts` WHERE `post_id` = {$pid}");
$total = mysql_result($total, 0);

if ($total != 1) {
return false;

}else{
return true;
}
}

// get summary of all posts
function get_posts(){

$sql = "SELECT
`posts`.`post_id` AS `id`,
`posts`.`post_title` AS `title`,
LEFT(`posts`.`post_body`, 512) AS `preview` ,
`posts`.`post_user` AS `user`,
DATE_FORMAT(`posts`.`post_date` , '%d,%m,%Y %H:%i:%s') AS `date` ,
`comments`.`total_comments`,
DATE_FORMAT(`comments`.`last_comment` , '%d,%m,%Y %H:%i:%s') AS `last_comment`
FROM `posts`

LEFT JOIN (
SELECT
`post_id` ,
COUNT(`comment_id`) AS `total_comments`,
MAX(`comment_date`) AS `last_comment`
FROM `comments`
GROUP BY `post_id`
) AS `comments`
ON `posts`.`post_id` = `comments`.`post_id`
ORDER BY `posts`.`post_date` DESC";

$posts = mysql_query($sql);

$rows = array();
while (($row = mysql_fetch_assoc($posts)) !== false){
$rows[] = array(
'id' => $row['id'],
'title' => $row['title'],
'preview' => $row['preview'],
'user' => $row['user'],
'date' => $row['date'],
'total_comments' => ($row['total_comments'] === null) ? 0 : $row['total_comments'],
'last_comment' => ($row['last_comment'] === null) ? 'never' : $row['last_comment']
);

}
return $rows;
}

//Get the post and comments
function get_post($pid){

$pid = (int)$pid;

$sql = "SELECT
`post_title` AS `title`,
`post_body` AS `body`,
`post_user` AS `user`,
`post_date` AS `date`
FROM `posts`
WHERE `post_id` = {$pid}";

$post = mysql_query($sql);
$post = mysql_fetch_assoc($post);

$post['comments'] = get_comments($pid);

return $post;

}

function add_post($name, $title, $body){


$name = mysql_real_escape_string(htmlentities(name));
$title = mysql_real_escape_string(htmlentities(title));
$body = mysql_real_escape_string(nl2br(htmlentities(body)));

mysql_query("INSERT INTO `posts` (`post_user`, `post_title`, `post_body`, `post_date`) VALUES ('{$name}', '{$title}', '{$body}', NOW())");

}
?>
[/syntax]

bloglist;
[syntax=php]
<?php
include('core/init.inc.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://ww.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>get blogged</title>
</head>
<body>
<div>

<?php
$posts = get_posts();

foreach ($posts as $post){
?>

<h2><a href="blogread.php?pid=<?php echo $post['id']; ?>"> <?php echo $post['title']; ?></a></h2>

<h4>By <?php echo $post['user']; ?> on <?php echo $post['date']; ?></h4>

<h4><?php echo $post['total_comments']; ?> comments, last comment <?php echo $post['last_comment']; ?></h4>

<hr />

<p><?php echo $post['preview']; ?></p>

<?php
}
?>

</div>

</body>

</html>
[/syntax]

blogpost;
[syntax=php]
<?php

include('core/init.inc.php');

if (isset($_POST['user'], $_POST['title'], $_POST['body'])){
add_post($_POST['user'], $_POST['title'], $_POST['body']);
header('location: bloglist.php');
die();
}

?>
<?php var_dump( $_POST );
?>

<html>
<head>
<title>Blog read</title>

</head>
<body>
<div>
<form action="" method="post">

<p>
<label for="user">Name</label>
<input type="text" name="user" id="user" />
</p>
<p>

<label for="title">Title</label>
<input type="text" name="user" id="user" /></p>
<p>
<textarea name="body" rows="20" cols="60"></textarea>
</p>
<p>
<input type="submit" value="Add Comment" />
</p>
</form>
</div>
</body>
</html>
[/syntax]

blogread;
[syntax=php]
<?php

include('core/init.inc.php');

if (isset($_GET['pid'], $_POST['user'], $_POST['body'])) {
if (add_comment($_GET['pid'], $_POST['user'], $_POST['body'])) {
header("Location: blogread.php?pid={$_GET['pid']}");
} else {
header('Location: bloglist.php');

}

die(mysql_error());
}
var_dump( $_POST );

?>
<html>
<head>
<title>Blog read</title>

</head>
<body>
<div>

<?php

if (isset($_GET['pid']) === false || valid_pid($_GET['pid']) === false){
echo 'Invalid post ID';
}else{
$post = get_post($_GET['pid']);

?>
<h2><?php echo $post['title']; ?></h2>
<h4>By <?php echo $post['user']; ?> on <?php echo $post['date']; ?> </h4>
<h4>(<?php echo count($post['comments']); ?> comments)</h4>

<hr />

<p><?php echo $post['body']; ?></p>

<hr />
<?php

foreach ($post['comments'] as $comment){
?>
<h4>By <?php echo $comment['user']; ?> on <?php echo $comment['date']; ?></h4>
<p><?php echo $comment['body']; ?></p>
<hr />
<?php
}
?>


<form action="" method="post">

<p>
<label for="user">Name</label>
<input type="text" name="user" id="user" />
</p>

<p>
<textarea name="body" rows="20" cols="60"></textarea>
</p>
<p>
<input type="submit" value="Add Comment" />
</p>
</form>

<?php
}
?>

</div>
</body>
</html>
[/syntax]

also as i'm hosting it myself - i had a look at the php.ini, but all seemed ok. not sure if i needed to mod the .htaccess file. like Jacek did.
anyway good hunting
Last edited by wuxmedia on Tue Oct 30, 2012 11:19 pm, edited 3 times in total.
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: PHP blog tut, blog post and comments failing to insert.

Post by Temor »

Try changing this part of get_comments
[syntax=php] $return = array();
while (($row = mysql_fetch_assoc($comments)) !== false){
$return[] = $row;
}[/syntax]

to this:

[syntax=php] $return = array();
while (($row = mysql_fetch_assoc($comments)) !== false){
$return['user'] = $row['user'];
$return['body'] = $row['body'];
}[/syntax]
User avatar
wuxmedia
Posts: 11
Joined: Mon Oct 22, 2012 10:39 pm

Re: PHP blog tut, blog post and comments failing to insert.

Post by wuxmedia »

^ sorry mate that returned exactly the same problem of a blank page.
i've ran all the pages through the cmd line:
$ php -e 'filename'

to see if that gets me anywhere, but it returned an 'empty' html
I'm using;
debian sid with;
PHP 5.4.4-7 (cli) (built: Aug 30 2012 11:15:38)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2012 Zend Technologies

with apache2 if that helps :)
i was using debian stable, but that returned the same blankness 8(


EDIT; btw this is the 'live' version, might explain a bit better;

http://wuxmedia.com/html/bloglist.php
also blogread.php and blogpost.php.

thanks
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: PHP blog tut, blog post and comments failing to insert.

Post by Temor »

[syntax=php]if (isset($_GET['pid'], $_POST['user'], $_POST['body'])) {
if (add_comment($_GET['pid'], $_POST['user'], $_POST['body'])) {
header("Location: blogread.php?pid={$_GET['pid']}");
} else {
header('Location: bloglist.php');

}

die(mysql_error());
}[/syntax]

remove the last die, or change it to echo instead.
Die() kills the script which prevents more code from running.
User avatar
wuxmedia
Posts: 11
Joined: Mon Oct 22, 2012 10:39 pm

Re: PHP blog tut, blog post and comments failing to insert.

Post by wuxmedia »

^ no effect. 8(

just changed the position of the var dump, [syntax=sql]
<?php

include('core/init.inc.php');
var_dump( $_POST );
if (isset($_GET['pid'], $_POST['user'], $_POST['body'])) {
if (add_comment($_GET['pid'], $_POST['user'], $_POST['body'])) {
header("Location: blogread.php?pid={$_GET['pid']}");
} else {
header('Location: bloglist.php');

}

echo(mysql_error());
}[/syntax]

this outputs that the $_post is full of data.... just not getting in between.

Thanks for debugging with me Temor 8)

did you try the live version?
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: PHP blog tut, blog post and comments failing to insert.

Post by Temor »

I did try the live version.

You could probably remove the mysql_error part entirely, seeing as you don't have any mysql errors.
You don't need the var_dump either since there's obviously nothing wrong with $_POST.

have you tried putting dummy data through add_comment to see if it adds the comment as it should?

Could I have a look at your init.inc file?
User avatar
wuxmedia
Posts: 11
Joined: Mon Oct 22, 2012 10:39 pm

Re: PHP blog tut, blog post and comments failing to insert.

Post by wuxmedia »

Temor wrote:You could probably remove the mysql_error part entirely, seeing as you don't have any mysql errors.
You don't need the var_dump either since there's obviously nothing wrong with $_POST.


Temor wrote:have you tried putting dummy data through add_comment to see if it adds the comment as it should?

Could I have a look at your init.inc file?


i've tried using the sql in phpmyadmin, replaceing the variables with actual data, using the INSERT ;
that is the result of the only 2 comments online. If thats what you mean
maybe you meant replacing the vars with data directly into the .php files?


init.inc
[syntax=php]<?php

mysql_connect("localhost", "XXX", "XXX") or die(mysql_error());
echo "Connected to MySQL<br />";
mysql_select_db("blog") or die(mysql_error());
echo "Connected to Database";


include('inc/posts.inc.php');

include('inc/comments.inc.php');

?>
[/syntax]

user and pass should be Ok, thats what the echo's are for, an early bug. 8)

this is my dir-tree, with the other files i was hoping to include this blog into;
[syntax=text]`-- wuxmedia
|-- css
| |-- wm1.css
| |-- wm2.css
| |-- wm.bak.css
| `-- wm.css
|-- html
| |-- about.php
| |-- blogbody.php
| |-- bloglist.php
| |-- blog.php
| |-- blogpost.php
| |-- blogread.php
| |-- contact.php
| |-- contacttext.php
| |-- content.php
| |-- core
| | |-- inc
| | | |-- comments.inc.php
| | | `-- posts.inc.php
| | `-- init.inc.php
| |-- cv.php
| |-- footer.php
| |-- header.php
| |-- index.php
| |-- main.php
| |-- navbar2.php
| |-- navbar.php
| |-- newblog.php
| |-- portfolio.php
| |-- porttext.php
| |-- projects.php
| |-- projtext.php
| |-- server.html
| |-- serverstatus
| `-- social.php
[/syntax]

thanks again for sticking with me. I usually bang my head hard enough and get stuff solved but this isn't going to well. 8)
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: PHP blog tut, blog post and comments failing to insert.

Post by jacek »

Everything looks right at a glance, but a very common problem is to make a typo on a variable name somewhere, by default php will hide these errors from you. So try setting your error_reporting level to E_ALL, you can do this in code like this

[syntax=php]error_reporting(E_ALL);[/syntax]
Image
User avatar
wuxmedia
Posts: 11
Joined: Mon Oct 22, 2012 10:39 pm

Re: PHP blog tut, blog post and comments failing to insert.

Post by wuxmedia »

thanks for dropping by boss. :D
I seem to have had a similar problem with a 'simpler' blog effort. as soon as i get the isset things go pear-shaped.
but, to the task in hand, adding E_All seems to have dropped this into the mix;

[syntax=text]
By
Warning: Illegal string offset 'user' in /home/***/htdocs/wuxmedia/html/blogread.php on line 49
c on
Warning: Illegal string offset 'date' in /home/***/htdocs/wuxmedia/html/blogread.php on line 49
c


Warning: Illegal string offset 'body' in /home/***/htdocs/wuxmedia/html/blogread.php on line 50
c
[/syntax]

which wasn't there before.
also It complained about nl2br not being defined...?
so i removed it and comments seem to post to the DB!! yay. but after it's not sure what to do.

again the live version here has the updated mess.
i put a var_dump($comment) in to see what it spewed out. i'm researching the errors - but i am a noob :lol:

thanks for following up.
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: PHP blog tut, blog post and comments failing to insert.

Post by jacek »

wuxmedia wrote:thanks for dropping by boss. :D

:P no problem.

I can't see where the problem is exactly, but illegal string offset happens when you try to use a string like an array, so this will cause the error too

[syntax=php]$string = 'I am a string !';

echo $string['blah'];[/syntax]
Has the code changes since the first post ? It looks like everything is defined right :?
Image
User avatar
wuxmedia
Posts: 11
Joined: Mon Oct 22, 2012 10:39 pm

Re: PHP blog tut, blog post and comments failing to insert.

Post by wuxmedia »

yes, the code had changed, i added Temors code (2nd post) I have removed it and the errors have gone :D
however i'm still at square one. :(
not sure if i'm the coding 'sort' :cry:

i'm getting to think it's a server prob.
like i said i have typed a far inferior blog in, similar effect, as soon as i get to a isset (this time for a login style page) no joy.
i had a breif look at php.ini, seems ok (post size 8M..)
still - having gone over this code a million times i'm still picking up little typos/errors. :oops:

thanks for your time.
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: PHP blog tut, blog post and comments failing to insert.

Post by jacek »

wuxmedia wrote:not sure if i'm the coding 'sort' :cry:

...
wuxmedia wrote:testing the blogpost page lets me post data according to the var dump; but never arrives in the table 8(

wuxmedia wrote:in phpmyadmin i've added some dummy data, 'get' works fine. if i type it into MySQL, no probs.

wuxmedia wrote:i've ran all the pages through the cmd line:

wuxmedia wrote:i had a breif look at php.ini, seems ok (post size 8M..)

You definitely are ! :P

Also...

[syntax=xhtml]<input type="text" name="user" id="user" /></p>[/syntax]
You have this twice and no title field ! So isset($_POST['title']) is false... mystery solved ? :D
Image
User avatar
wuxmedia
Posts: 11
Joined: Mon Oct 22, 2012 10:39 pm

Re: PHP blog tut, blog post and comments failing to insert.

Post by wuxmedia »

You :)
Goshdarnded :D
Genius :lol:

yay, bloomin copy and paste. :oops:
yes forgot to put that in, and i think its the same prob with the comments post. :roll:
all this time i was worrying about the php (new to me) and it was the flippin' html (not so new)

thanks for the kind words, i am fairly persistant, needs some more experience/intelligence to back that up.
and you haven't got a stupid voice. believe me i've listened to it enough 8)
'XSS attacks' is a toungue twister (try 'X double S attacks'?)
I feel i can try some of the other things here...

right, better css this blog to shape now. cheers 'en :D
User avatar
wuxmedia
Posts: 11
Joined: Mon Oct 22, 2012 10:39 pm

Re: PHP blog tut, post and comments fail to insert. [Solved]

Post by wuxmedia »

OK spoke too soon :(

All imputed data arrives in mysql, good.
But,
blogread refuses to display the comments. nothing - doesn't even count them. (or shows zero)
blogpost does happily list the number of comments, and last one and when.
so, assuming I've understood the logic, the .inc files should be working, just a case of the php not accessing the right array etc?

here, for prosperity is the files, i reckon, are faulty;

blogread;
[syntax=php]
<?php

include('core/init.inc.php');
if (isset($_GET['pid'], $_POST['user'], $_POST['body'])){
if (add_comment($_GET['pid'], $_POST['user'], $_POST['body'])){
header("Location: blogread.php?pid={$_GET['pid']}");
} else {
header('Location: bloglist.php');

}
die();
}


?>
<html>
<head>
<title>Blog read</title>

</head>
<body>
<div>

<?php

if (isset($_GET['pid']) === false || valid_pid($_GET['pid']) === false){
echo 'Invalid post ID';
}else{
$post = get_post($_GET['pid']);

?>
<h2><?php echo $post['title']; ?></h2>
<h4>By <?php echo $post['user']; ?> on <?php echo $post['date']; ?> (<?php echo count($post['comments']); ?> comments)</h4>

<hr />

<p><?php echo $post['body']; ?></p>

<hr />
Leave a Comment?
<?php

foreach ($post['comments'] as $comment){
?>
<h4>By <?php echo $comment['user']; ?> on <?php echo $comment['date']; ?></h4>
<p><?php echo $comment['body']; ?></p>
<hr />
<?php
}
?>
<form action="" method="post">

<p>
<label for="user">Name</label>
<input type="text" name="user" id="user" />
</p>

<p>
<textarea name="body" rows="20" cols="60"></textarea>
</p>
<p>
<input type="submit" value="Add Comment" />
</p>
</form>

<?php
}
?>

</div>
</body>
</html>[/syntax]

Comments.inc;

[syntax=php]<?php


// gets comments for a blog post

function get_comments($pid){

$pid = (int)$pid;

$sql = "SELECT
`comment_body` AS `body`,
`comment_user` AS `user`,
DATE_FORMAT(`comment_date`, '%d/%m/%Y %H:%i:%s') AS `date`
FROM `comments`
WHERE `post_id` = {$pid}";


$comments = mysql_query($sql);

$return = array();
while (($row = mysql_fetch_assoc($comments)) !== false){

}

return $return;
}


function add_comment($pid, $user, $body){
if (valid_pid($pid) === false){
return false;
}

$pid = (int)$pid;
$user = mysql_real_escape_string(htmlentities($user));
$body = mysql_real_escape_string(htmlentities($body));

mysql_query("INSERT INTO `comments` (`post_id`, `comment_user`, `comment_body`, `comment_date`) VALUES ({$pid}, '{$user}', '{$body}', NOW())");
return true;

}
and posts.inc

[syntax=php]<?php

// checks for a valid post
function valid_pid($pid){

$pid = (int)$pid;
$total = mysql_query("SELECT COUNT(`post_id`) FROM `posts` WHERE `post_id` = {$pid}");
$total = mysql_result($total, 0);

if ($total != 1) {
return false;

}else{
return true;
}
}

// get summary of all posts
function get_posts(){

$sql = "SELECT
`posts`.`post_id` AS `id`,
`posts`.`post_title` AS `title`,
LEFT(`posts`.`post_body`, 512) AS `preview` ,
`posts`.`post_user` AS `user`,
DATE_FORMAT(`posts`.`post_date` , '%d/%m/%Y %H:%i:%s') AS `date` ,
`comments`.`total_comments`,
DATE_FORMAT(`comments`.`last_comment` , '%d/%m/%Y %H:%i:%s') AS `last_comment`
FROM `posts`

LEFT JOIN (
SELECT
`post_id` ,
COUNT(`comment_id`) AS `total_comments`,
MAX(`comment_date`) AS `last_comment`
FROM `comments`
GROUP BY `post_id`
) AS `comments`
ON `posts`.`post_id` = `comments`.`post_id`
ORDER BY `posts`.`post_date` DESC";

$posts = mysql_query($sql);

$rows = array();
while (($row = mysql_fetch_assoc($posts)) !== false){
$rows[] = array(
'id' => $row['id'],
'title' => $row['title'],
'preview' => $row['preview'],
'user' => $row['user'],
'date' => $row['date'],
'total_comments' => ($row['total_comments'] === null) ? 0 : $row['total_comments'],
'last_comment' => ($row['last_comment'] === null) ? 'never' : $row['last_comment']
);

}
return $rows;
}

//Get the post and comments
function get_post($pid){

$pid = (int)$pid;

$sql = "SELECT
`post_title` AS `title`,
`post_body` AS `body`,
`post_user` AS `user`,
`post_date` AS `date`
FROM `posts`
WHERE `post_id` = {$pid}";

$post = mysql_query($sql);
$post = mysql_fetch_assoc($post);

$post['comments'] = get_comments($pid);

return $post;

}

function add_post($name, $title, $body){


$name = mysql_real_escape_string($name);
$title = mysql_real_escape_string($title);
$body = mysql_real_escape_string($body);

mysql_query("INSERT INTO `posts` (`post_user`, `post_title`, `post_body`, `post_date`) VALUES ('{$name}', '{$title}', '{$body}', NOW())");

}
?>
[/syntax]

?>
[/syntax]
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: PHP blog tut, post and comments fail insert [mostly Solv

Post by Temor »

Well, your while loop is empty.
[syntax=php] while (($row = mysql_fetch_assoc($comments)) !== false){

}[/syntax]

you need to add the values to the $return array.
[syntax=php] while (($row = mysql_fetch_assoc($comments)) !== false){
$return[] = $row;
}[/syntax]
User avatar
wuxmedia
Posts: 11
Joined: Mon Oct 22, 2012 10:39 pm

Re: PHP blog tut, post and comments fail insert [mostly Solv

Post by wuxmedia »

^ well, thats got it :oops:

looks like it functions as intended, now.
thanks guys!
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: PHP blog tut, post and comments fail insert [Solved]

Post by Temor »

Glad you solved it :)
User avatar
wuxmedia
Posts: 11
Joined: Mon Oct 22, 2012 10:39 pm

Re: PHP blog tut, post and comments fail insert [Solved]

Post by wuxmedia »

Temor wrote:Glad you solved it :)


well technically you solved it, i just typed/corrected it !!! :D
Post Reply