Page 1 of 1

PHP Tutorial: Blog (Including Commenting) [part 04]

Posted: Tue Apr 16, 2013 2:28 pm
by Anchimayen
Hello i'm very nooby to php and followed the serie about writting a blog code,
but at part [4] we tried to use blog_post.php at around 10:23 and this gave me the following error pop-up:

"Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\blog\core\inc\posts.inc.php on line 42"

So i've been searching for answers on the form but non of these helpt me this time. (And the echo mysql_error(); didn't give any result except for the statement that i didn' t have a database selected :? )

So, to be sure i have include all my edited pages.

I hope someone could help me. :)

(Sorry if there are grammatical & spelling errors in this post, but English isn't my native tongue.)


init.inc.php
[syntax=php]<?php

mysql_connect("127.0.0.1","","");
mysql_select_db("blog");

include("inc/posts.inc.php");
include("inc/comments.inc.php");
?>[/syntax]

post.inc.php
[syntax=php]<?php

// checks if the given post_id is in the table.
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;
}
}

// fetches a summery of all the blog 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;
}

// fetches a single post from table.
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;
}

// adds a new blog entry.
function add_post($name, $title,$body){
$name = mysql_real_escape_string(htmlentites($name));
$title = mysql_real_escape_string(htmlentites($title));
$body = mysql_real_escape_string(nl2br(htmlentites($body)));

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

?>
[/syntax]

comment.inc.php
[syntax=php]<?php
// fetches all of the comments for a given 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;
}
// adds a comment.
function add_comment($pid, $user, $body){
if (valid_pid($pid) === false){
return false;
}

$pid = (int)$pid;
$user = mysql_real_escape_string(htmlentites($user));
$body = mysql_real_escape_string(nl2br(htmlentites($body)));

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

return true;
}
?>[/syntax]

Re: PHP Tutorial: Blog (Including Commenting) [part 04]

Posted: Tue Apr 16, 2013 9:12 pm
by Anchimayen
Nevermind people, found the problem myself :) I spelled the server username wrong. xD

Re: PHP Tutorial: Blog (Including Commenting) [part 04]

Posted: Thu Apr 18, 2013 11:36 am
by Anchimayen
Hello people, i'm back. I finished the series succesfull. But now i have a question
in the video the date format at the read_blog page is shown as yyyy-mm-dd, but i want it shows up like this: dd/mm/yyyy or dd-mm-yyyy.
So is there a way to change the format?

hope you guys can help me, already thanks in advance! :)

Greetings,
Anchimayen

Re: PHP Tutorial: Blog (Including Commenting) [part 04]

Posted: Thu Apr 18, 2013 6:43 pm
by Temor
Yes. This is done using the date() function to format the Unix timecode.
[syntax=php]echo date("d/m/y",$date);[/syntax]
this would echo the day/month/year in two digit numeric values.
( 18/04/13 )
[syntax=php]date("D/M/Y",$date);[/syntax]
this would echo the day/month in text and year in 4 digits.
( Thu/Apr/2013 )


You can read about more ways of formatting here: http://php.net/manual/en/function.date.php

Re: PHP Tutorial: Blog (Including Commenting) [part 04]

Posted: Wed Apr 24, 2013 8:31 pm
by Anchimayen
Thanks for the help so far you guys are the best! :D
I have another question. (i hope it's not getting annoying)

I've tried to connect a tinyMCE script with the blog post file.
It worked kinda but now i'm unable to post, the information seems to be incapable to be send to the database.
Is there a way to connect this script properly?

My blog_post.php file:
[syntax=php]<?php
include('core/init.inc.php');
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link href="style/blogstyle.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
// General options
mode : "textareas",
theme : "advanced",
plugins : "autolink,lists,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

// Theme options
theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
theme_advanced_resizing : true,

// Skin options
skin : "o2k7",
skin_variant : "silver",

// Example content CSS (should be your site CSS)
content_css : "css/example.css",

// Drop lists for link/image/media/template dialogs
template_external_list_url : "js/template_list.js",
external_link_list_url : "js/link_list.js",
external_image_list_url : "js/image_list.js",
media_external_list_url : "js/media_list.js",
});
</script>

</head>

<body>
</p>
<form action="" method="post">
<input type="text" name="user" id="user" required="required" placeholder="Vul hier je naam in..."/>
<input type="text" name="title" id="title" placeholder="Vul hier je titel in..." required="required"/>
<textarea name="body" rows="20" cols="60" required="required" ></textarea>
<input type="submit" value="Plaats artikel" />
</form>
</body>
</html>[/syntax]

the script that I have integrated:
http://www.tinymce.com/tryit/3_x/full.php

Re: PHP Tutorial: Blog (Including Commenting) [part 04]

Posted: Fri Apr 26, 2013 7:13 pm
by ExtremeGaming
JavaScript styles will not prevent data from being entered. There must be errors in your query.

Re: PHP Tutorial: Blog (Including Commenting) [part 04]

Posted: Sat Apr 27, 2013 2:32 pm
by Anchimayen
Hmmm, seems that you're right. I'm guess that I've accidentally deleted something from the query's. Only i can't figure out what it is.

I hope someone else can see it cause i'm staring myself blind on it. :?

post.inc.php
[syntax=php]<?php
// checks if the given post_id is in the table.
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;}
}

// fetches a summery of all the blog 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) ? '"er zijn nog geen reacties"' : $row['last_comment']);
}
return $rows;
}

// fetches a single post from table.
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;
}

// adds a new blog entry.
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]

comment.inc.php
[syntax=php]<?php
// fetches all of the comments for a given 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;
}
// adds a comment.
function add_comment($pid, $user, $body){
if (valid_pid($pid) === false){
return false;
}

$pid = (int)$pid;
$user = mysql_real_escape_string(htmlentites($user));
$body = mysql_real_escape_string(nl2br(htmlentites($body)));

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

return true;
}
?>[/syntax]
init.inc.php
[syntax=php]<?php

mysql_connect('***','***','***');
mysql_select_db('blog');

include('inc/posts.inc.php');
include('inc/comments.inc.php');
?>[/syntax]
blog_read.php
[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: blog_read.php?pid={$_GET['pid']}");
}else{
header('location: blog_list.php');
}

die();
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link href="style/blogstyle.css" rel="stylesheet" type="text/css"/>
</head>

<body>
<div id="header_left">
</div>
<div id="header">
<div id="logobackground">
<div id="logo"><a href="blog_list.php" target="_self"><img src="style/images/logo.png"/></a>
</div>
</div>
<div id="navigation">
<div id="catogorieen">
</div>
</div>
<div id="header-end">
</div>
</div>
<div id="topcontent">
</div>
<div id="contentborder">
<div id="content">
<div id="main_content">
<?php
if (isset($_GET['pid']) === false || valid_pid($_GET['pid']) === false){
echo 'Onjuiste post ID.' ;
}else{
$post = get_post($_GET['pid']);
?>
<div id="text_read">
<div id="title_read">
<h1 ><?php echo $post['title']; ?></h1>
</div>
<div id="post_info">
<h4>Door <span id="naam"><?php echo $post['user']; ?></span> op: <?php echo $post['date']; ?> </h4>
<h4>(<span id="last_comment"><?php echo count($post['comments']); ?> comments</span>)</h4>
</div>


<p><?php echo $post['body']; ?></p>
</div>
<div id="comment_form">
<form action="" method="post">
<p>
<input type="text" name="user" id="user" placeholder="Vul hier je naam in..." />
</p>
<br/>
<p>
<textarea name="body" cols="60" required="required" ></textarea>
</p>
<br/>
<p>
<input type="submit" value="Plaats reactie" />
</p>
</form>
</div>
<?php
foreach ($post['comments'] as $comment){
?>
<h4>Door <?php echo $comment['user']; ?> op <?php echo $comment['date']; ?></h4>
<p><?php echo $comment ['body']; ?></p>
<?php
}
?>
<?php
}
?>
</div>
</div>
</div>


</body>
</html>[/syntax]
blog_list.php
[syntax=php]<?php
include('core/init.inc.php');
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link href="style/blogstyle.css" rel="stylesheet" type="text/css"/>
</head>
<div id="header_left">
</div>
<div id="header">
<div id="logobackground">
<div id="logo"><a href="blog_list.php" target="_self"><img src="style/images/logo.png"/></a>
</div>
</div>
<div id="navigation">
<div id="catogorieen">
</div>
</div>
<div id="header-end">
</div>
</div>
<div id="topcontent">
</div>
<div id="contentborder">
<div id="content">
<div id="main_content">
<?php

$posts = get_posts();

foreach ($posts as $post){
?>
<div id="title_post"><h1><a href="blog_read.php?pid=<?php echo $post['id']; ?>"><?php echo $post['title']; ?></a></h1></div>
<div id="text_vlak">
<div id="post_info">
<h4>Door <span id="naam"><?php echo $post['user']; ?></span> op: <?php echo $post['date']; ?></h4>
<h4>(<?php echo $post['total_comments']; ?> reacties, laatste reactie op: <span id="last_comment"><?php echo $post['last_comment']; ?></span>)</h4>
</div>
<p><?php echo $post['preview']; ?>... <br /><br/>... <a href="blog_read.php?pid=<?php echo $post['id']; ?>">lees meer</a></p>
</div>
<?php
}
?>
</div>
</div>
</div>

<body>
</body>
</html>[/syntax]
blog_post.php
[syntax=php]<?php
include('core/init.inc.php');
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link href="style/blogstyle.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
// General options
mode : "textareas",
theme : "advanced",
plugins : "autolink,lists,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

// Theme options
theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
theme_advanced_resizing : true,

// Skin options
skin : "o2k7",
skin_variant : "silver",

// Example content CSS (should be your site CSS)
content_css : "css/example.css",

// Drop lists for link/image/media/template dialogs
template_external_list_url : "js/template_list.js",
external_link_list_url : "js/link_list.js",
external_image_list_url : "js/image_list.js",
media_external_list_url : "js/media_list.js",
});
</script>

</head>

<body>
<form action="" method="post">
<input type="text" name="user" id="user" required="required" placeholder="Vul hier je naam in..."/>
<input type="text" name="title" id="title" placeholder="Vul hier je titel in..." required="required"/>
<textarea name="body" rows="20" cols="60" required="required" ></textarea>
<input type="submit" value="Plaats artikel" />
</form>
</body>
</html>[/syntax]

Re: PHP Tutorial: Blog (Including Commenting) [part 04]

Posted: Sat Apr 27, 2013 2:49 pm
by ExtremeGaming
If blog_post.php is exactly as you have it, there is no processing to it. You aren't calling add_post() anywhere, or validating anything.

Re: PHP Tutorial: Blog (Including Commenting) [part 04]

Posted: Sat Apr 27, 2013 8:29 pm
by Anchimayen
I've added the missing part (how silly of me to forget that). But if i delete the javascript now it works, else it won't. So there must be something in the javascript that clashes with the php script.

So here again (and now the right version) of my blog_post.php:

[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: blog_list.php');
die();
}
?>
<script type="text/javascript" src="tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
// General options
mode : "textareas",
theme : "advanced",
plugins : "autolink,lists,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

// Theme options
theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
theme_advanced_resizing : true,

// Skin options
skin : "o2k7",
skin_variant : "silver",

// Example content CSS (should be your site CSS)
content_css : "css/example.css",

// Drop lists for link/image/media/template dialogs
template_external_list_url : "js/template_list.js",
external_link_list_url : "js/link_list.js",
external_image_list_url : "js/image_list.js",
media_external_list_url : "js/media_list.js",
});
</script>

</head>

<body>
<form action="" method="post">
<input type="text" name="user" id="user" required="required" placeholder="Vul hier je naam in..."/>
<input type="text" name="title" id="title" placeholder="Vul hier je titel in..." required="required"/>
<textarea name="body" rows="20" cols="60" required="required" ></textarea>
<input type="submit" value="Plaats artikel" />
</form>
</body>
</html>[/syntax]

Re: PHP Tutorial: Blog (Including Commenting) [part 04]

Posted: Sat Apr 27, 2013 8:55 pm
by Anchimayen
Hmmm, strange now it works maybe i didn't save it before testing however i seem to get the pragraph signs in my post.
Only problem now is that it display's the html tags in normal writing like: </p>. But i geuss that's because of the js, or is it because of this part of the post.inc.php?
[syntax=php]$body = mysql_real_escape_string(nl2br(htmlentities($body)));[/syntax]