Jump to content

News With Comments


jamesjmann

Recommended Posts

Got this script here:

http://www.codewalkers.com/c/a/Database-Articles/PHPMySQL-News-with-Comments/6/

 

Everything works, and I mean EVERYTHING. The problem is, when the form gets submitted, the database isn't being queried/updated/whatever. It worked at first, but after I started customizing/modifying it, it quit working.

 

Here's my modified script:

<?php
//**********************************//
//**********************************//
/*******user config variables********/
/* max number of news items to show */
//**********************************//
//**********************************//
$max_items = 5; 

//***********************//
//***********************//
//***********************//
//make database connection//
//***********************//
//***********************//
//***********************//
$db = mysql_connect ('my hostname','my username','my password');
mysql_select_db ('my database name',$db);


//If not all of the news articles are being displayed...
function displayNews($all = 0) {

/* bring in two variables
* $db is our database connection
* $max_items is the maximum number
* of news items we want to display */
    global $db, $max_items;
    
/* query for news items */
    if ($all == 0) {

/* this query is for up to $max_items; only five news articles will be displayed */
        $query = "SELECT id,title,body," . 
                 "DATE_FORMAT(date, '%m-%d-%Y') as date " . 
                 "FROM news ORDER BY id DESC LIMIT $max_items";
    } else {


/* this query will get all news; $max_items will be false */
        $query = "SELECT id,title,body," . 
                 "DATE_FORMAT(date, '%Y-%m-%d') as date " .
                 "FROM news ORDER BY id DESC";
    }


    $result = mysql_query ($query);
    while ($row = mysql_fetch_assoc ($result)) {
        
/* place table row data in 
* easier to use variables.
* Here we also make sure no
* HTML tags, other than the
* ones we want are displayed */
	$date = $row['date'];        
        $title = htmlentities ($row['title']);
        $news = nl2br (strip_tags ($row['body'], '<a><b><i><u>'));
	$url = $row['id'];

/* display the data (news) */
        echo "<table border=\"0\" width=\"100%\"><tr><td><strong><h2><a href=\"{$_SERVER['PHP_SELF']}" .
             "?action=show&id={$row['id']}\">$title</a></h2></strong> <em>posted on $date</em> | by <strong>DJ Smiley</strong></td></tr>\n";
        echo "<tr><td>";
	echo stripslashes(substr($news, 0, 500));
	echo "...<a href=\"{$_SERVER['PHP_SELF']}" .
             "?action=show&id={$row['id']}\">read more</a></td></tr>\n";
        
/* get number of comments from database */
        $comment_query = "SELECT count(*) FROM comments " .
                         "WHERE news_id={$row['id']}";
        $comment_result = mysql_query ($comment_query);
        $comment_row = mysql_fetch_row($comment_result);
        
/* display number of comments with link; add twitter, facebook, digg, and share widgets; and add email sharing widget */
	echo "</table>\n<table width=\"100%\" border=\"0\">
	<tr>
	<td width=\"6%\"><a href=\"{$_SERVER['PHP_SELF']}" .
	"?action=show&id={$row['id']}\"><img src=\"images/Icons/Comment/2.png\" width=\"20\" height=\"20\" class=\"fltlft2\"/></a>$comment_row[0]</td>
	<td width=\"13%\"><!-- FreeTellaFriend BEGIN -->
	<a href=\"http://www.freetellafriend.com/tell/\" onclick=\"window.open('http://www.freetellafriend.com/tell/?option=email&heading=Tell+A+Friend&bg=14&url=http%3A%2F%2Fhttp://www.djsmiley.net/index.php?action=show&id={$row['id']}', 'freetellafriend', 'scrollbars=1,menubar=0,width=435,height=500,resizable=1,toolbar=0,location=0,status=0,left='+(screen.width-435)/2+',top='+(screen.height-500)/3);return false;\"><img alt=\"Tell a Friend\" src=\"http://serv1.freetellafriend.com/s14.png\" border=\"0\" /></a>
	<!-- FreeTellaFriend END --></td>
	<td width=\"81%\"><span class=\"st_twitter_hcount\" st_url=\"http://www.djsmiley.net/index.php?action=show&id={$row['id']}\" displayText=\"Tweet\" st_title=\"{$row['title']}\"></span><span class=\"st_facebook_hcount\" st_url=\"http://www.djsmiley.net/index.php?action=show&id={$row['id']}\" displayText=\"Share\" st_title=\"{$row['title']}\"></span><span class=\"st_email_hcount\" st_url=\"http://www.djsmiley.net/index.php?action=show&id={$row['id']}\" displayText=\"Email\"></span><span class=\"st_sharethis_hcount\" st_url=\"http://www.djsmiley.net/index.php?action=show&id={$row['id']}\" displayText=\"Share\"></span></td>
	</tr>
	</table><br>";
       
    }
    
/* if we aren't displaying all news, 
* then give a link to do so */
    if ($all == 0) {
        echo "<br><div style=\"border-radius: 10px; border: solid 2px #E5E5E5; padding: 10px; margin: 5px; background: #F6F6F6;\"></p><a href=\"{$_SERVER['PHP_SELF']}" .
             "?action=all\">View All Articles</a></p></div>";
    }
}

//function for displaying only one item
function displayOneItem($id) {
    global $db;
    
/* query for item */
    $query = "SELECT * FROM news WHERE id=$id";
    $result = mysql_query ($query);
$row = mysql_fetch_assoc($result);

/* easier to read variables and 
* striping out tags */
    $title = htmlentities ($row['title']);
    $news = nl2br (strip_tags ($row['body'], '<a><b><i><u>'));
    
/* if we get no results back, error out */
    if (mysql_num_rows ($result) == 0) {
        echo "This news article does not exist!\n";
        return;
    }
    
    echo "<TABLE border=\"0\" width=\"100%\">\n";


    
/* displays individual article user visits */    
	echo "<tr><td><strong><h2><a href=\"{$_SERVER['PHP_SELF']}" .
	 "?action=show&id={$row['id']}\">$title</a></h2></strong> <em>posted on $date</em> | by <strong>DJ Smiley</strong></td></tr>\n";
        echo "<tr><td>";
	echo stripslashes($news);
	echo "</td></tr>\n";
	echo "</table>\n";
	echo "<br>\n";
	echo ("</table>\n<table width=\"100%\" border=\"0\">
  <tr>
    <td width=\"6%\"><a href=\"{$_SERVER['PHP_SELF']}" .
							"?action=show&id={$row['id']}\"><img src=\"images/Icons/Comment/2.png\" width=\"20\" height=\"20\" class=\"fltlft2\"/></a>$comment_row[0]</td>
    <td width=\"13%\"><!-- FreeTellaFriend BEGIN -->
<a href=\"http://www.freetellafriend.com/tell/\" onclick=\"window.open('http://www.freetellafriend.com/tell/?option=email&heading=Tell+A+Friend&bg=14&url=http%3A%2F%2Fhttp://www.djsmiley.net/index.php?action=show&id={$row['id']}', 'freetellafriend', 'scrollbars=1,menubar=0,width=435,height=500,resizable=1,toolbar=0,location=0,status=0,left='+(screen.width-435)/2+',top='+(screen.height-500)/3);return false;\"><img alt=\"Tell a Friend\" src=\"http://serv1.freetellafriend.com/s14.png\" border=\"0\" /></a>
<!-- FreeTellaFriend END --></td>
    <td width=\"81%\"><span class=\"st_twitter_hcount\" st_url=\"http://www.djsmiley.net/index.php?action=show&id={$row['id']}\" displayText=\"Tweet\"></span><span class=\"st_facebook_hcount\" st_url=\"http://www.djsmiley.net/index.php?action=show&id={$row['id']}\" displayText=\"Share\"></span><span class=\"st_email_hcount\" st_url=\"http://www.djsmiley.net/index.php?action=show&id={$row['id']}\" displayText=\"Email\"></span><span class=\"st_sharethis_hcount\" st_url=\"http://www.djsmiley.net/index.php?action=show&id={$row['id']}\" displayText=\"Share\"></span></td>
  </tr>
</table>");
    
/* now show the comments */
    displayComments($id);
}

function displayComments($id) {

/* bring db connection variable into scope */
    global $db;
    
/* query for comments */
    $query = "SELECT * FROM comments WHERE news_id=$id";
    $result = mysql_query ($query);
echo "<h2>Comments</h2>";
    
/* display the all the comments */
    while ($row = mysql_fetch_assoc ($result)) {
        
//sets variables
	$comment = strip_tags ($row['comment'], '<a><b&><i><u>');
        $comment = nl2br ($comment);
        $name = htmlentities ($row['name']);
	$time = ($row['time']);

	echo "<div style=\"border-radius: 10px; border: solid 2px #E5E5E5; padding: 10px; margin: 5px; background: #F6F6F6;\"><p><table border=\"0\" width=\"100%\"><tr><td><strong>$name</strong> says:</td></tr></table>
	<table><tr><td><img src=\"images/Icons/People/Anonymous 2.png\" alt=\"\" width=\"50\" height=\"50\"/></td><td>$comment</td></tr></table><table><tr><td>added on $time</td></tr></table></p></div>";
    }
    
/* add a form where users can enter new comments */
    echo "<form action=\"{$_SERVER['PHP_SELF']}" .
		 "?action=addcomment&id=$id\" method=post>
		 <h2>Comment</h2><table width=\"37%\" border=\"0\">
  <tr>
	<td width=\12%\">Name:</td>
	<td width=\"88%\"><label>
	  <input type=\"text\" name=\"name\" id=\"name\" class=\"commentBoxforms\">
	</label></td>
  </tr>
  <tr>
	<td>Comment:</td>
	<td><label>
	  <textarea name=\"comment\" id=\"comment\" cols=\"45\" rows=\"5\" class=\"commentField1\"></textarea>
	</label></td>
  </tr>
  <tr>
	<td> </td>
	<td><label>
	  <input type=\"submit\" name=\"submit\" id=\"submit\" value=\"Comment\" class=\"Button1\">
	</label></td>
  </tr>
</table>
</form>\n";
     
}

function addComment($id) {
    global $db;
    
    /* insert the comment */
    $query = "INSERT INTO comments " .
           "VALUES('',$id,'{$_POST['name']}'," .
             "'{$_POST['comment']}')";
    mysql_query($query);
    
    echo "Your comment has been posted!<br>\n";
    echo "<a href=\"{$_SERVER['PHP_SELF']}" .
         "?action=show&id=$id\">Return To Previous Page</a>\n";
}


/* this is where the script decides what do do */
switch($_GET['action']) {
    
    case 'show':
        displayOneItem($_GET['id']);
        break;
    case 'all':
        displayNews(1);
        break;
    case 'addcomment':
        addComment($_GET['id']);
        break;
    default:
        displayNews();
}
?>

 

Can anyone tell me where this script is going wrong? I've literally tried EVERYTHING. I even went back to the original script and compared every single character to mine, but NO luck.

 

PLEASE HELP!

Link to comment
Share on other sites

These type of scripts piss me off.

 

You make database connections, and perform queries, and fetch, but never check to see if those work.

 

$result = mysql_query ($query);

 

Did this work?  Well no worries, we'll go try and fetch from it anyways.

 

Start with adding that code, and my guess is the problem will pop out at you.

 


$result = mysql_query ($query);
  if (!$result) {
    echo 'Error: ' . mysql_error();
  } else {
    // go ahead and try to fetch 
  }

 

 

 

Link to comment
Share on other sites

That's not my problem. My database is displaying EVERYTHING correctly, as it should. But the form doesn't work. When I complete the form and hit the submit button, I get taken to a "comment successful" page, as is supposed to happen, but the data does not get inserted into my database.

 

 

These type of scripts piss me off.

 

You make database connections, and perform queries, and fetch, but never check to see if those work.

 

$result = mysql_query ($query);

 

 

 

Did this work?  Well no worries, we'll go try and fetch from it anyways.

 

Start with adding that code, and my guess is the problem will pop out at you.

 


$result = mysql_query ($query);
  if (!$result) {
    echo 'Error: ' . mysql_error();
  } else {
    // go ahead and try to fetch 
  }

Link to comment
Share on other sites

Here is the addComment function before:

function addComment($id) {
    global $db;
    
/* insert the comment */
    $query = "INSERT INTO comments VALUES('',$id,'{$_POST['name']}','{$_POST['comment']}')";
    mysql_query($query);
    
    echo "<h1>Success!</h1>Your comment has been posted!<br><a href=\"{$_SERVER['PHP_SELF']}" .
         "?action=show&id=$id\">Return To Previous Page</a>\n";
}

 

Here's the function modified with your suggestion:

function addComment($id) {
    global $db;
    
/* insert the comment */
    $query = "INSERT INTO comments VALUES('',$id,'{$_POST['name']}','{$_POST['comment']}')";
    $result = mysql_query ($query);

if (!$result) {
    echo 'Error: ' . mysql_error();
  } else {
    echo "<h1>Success!</h1>Your comment has been posted!<br><a href=\"{$_SERVER['PHP_SELF']}" .
         "?action=show&id=$id\">Return To Previous Page</a>\n";
  } 

}

 

Now, here's the error I got when I submitted the form:

Error: Column count doesn't match value count at row 1

Link to comment
Share on other sites

How many columns does the "comments" table have?  Your script is trying to insert 4 columns, and Mysql is telling you the table doesn't have 4 columns (it may have 3 or 5 or any other number).

 

it has 5 columns.

 

the comment id itself

the id of the news article so it knows where to display each comment

the name the user inputs

the comment the user inputs

and the time of the comment

 

the second table is for the news articles

 

id

title

user

date

body

url

 

btw, here's the link to the script im talking about. perhaps you guys can try it out yourself so you can have a better understanding on what's going on here?

 

http://djsmiley.net/index.php?action=show&id=1

Link to comment
Share on other sites

So, you can rewrite your query like this, and solve your problem:

 

$query = "INSERT INTO comments (user, comment) VALUES  ('{$_POST['name']}', '{$_POST['comment']}')";

 

ok i don't know what you did, but that definitely worked! now the problem im having is the comments i post now aren't being displayed BECAUSE, they are not being assigned the news article id relative to whatever article i post on.

for example...

after testing it this popped up in my database:

id - 13

news_id - 0

name - random text i entered

comment - random text i entered

time - time i posted it

Link to comment
Share on other sites

So, you can rewrite your query like this, and solve your problem:

 

$query = "INSERT INTO comments (user, comment) VALUES  ('{$_POST['name']}', '{$_POST['comment']}')";

 

Nevermind. Putting news_id before "user" and "'$id'" before "'{$_POST['name]}'", solved that last issue. Thanks to everyone who helped!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.