Ответов: 15 Просмотров: 543
|
(Добавление)
gigs пишет:ну а как это сделать, если нужно то я могу выложить код формы коментариев я там почти все сделал вот только не знаю где у меня ошибка.
Вот сам код уже исправленый, только типерь когда нажимаеш отправить то страница перезагружается и все, а комментарий не добавляется ни в базу ни на странице, вот я не могу понять почему ?
demo.php - здесь находится форма добавления комментариев
PHP:
скопировать код в буфер обмена
<?PHP // Error reporting: include "connect.php"; include "comment.class.php"; /* / Select all the comments and populate the $comments array with objects */ $result = mysql_query("SELECT * FROM comments where PageID = '" . $pageID . "' ORDER BY id ASC"); $pageID = (isset($_GET['id'])) ? (int )$_GET['id'] : 'none'; { $comments[] = new Comment($row); } ?> <link rel="stylesheet" type="text/css" href="styles.css" /> <div id="main"> <?PHP /* / Вывод комментариев один за другим: */ foreach($comments as $c){ echo $c->markup(); } ?> <div id="addCommentContainer"> <p>Добавить комментарий</p> <form id="addCommentForm" method="post" action=""> <div> <label for="name">Имя</label> <input type="text" name="name" id="name" /> <label for="email">Email</label> <input type="text" name="email" id="email" /> <input type="hidden" name="page id" value=" <? echo (isset($_GET['id'])) ? $_GET['id'] : 'none' ; ?>" /> <label for="body">Содержание комментария</label> <textarea name="body" id="body" cols="20" rows="5"></textarea> <input type="submit" id="submit" value="Отправить" /> </div> </form> </div> </div> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="script.js"></script>
connect.php - связь с базой
PHP:
скопировать код в буфер обмена
<?PHP /* Database config */ $db_host = 'localhost'; $db_user = 'свое'; $db_pass = 'свое'; $db_database = 'свое'; /* End config */ $link = @mysql_connect($db_host,$db_user,$db_pass) or die('Unable to establish a DB connection'); ?>
comment.class.php - Вывод комментариев и генерация html кода комментария.Проверка формы на заполнение всех полей, а так же правильности заполнения email и обновление комментариев на странице.
PHP:
скопировать код в буфер обмена
<?PHP class Comment { public function __construct($row) { /* / The constructor */ $this->data = $row; } public function markup() { /* / This method outputs the XHTML markup of the comment */ // Setting up an alias, so we don't have to write $this->data every time: $d = &$this->data; $link_open = ''; $link_close = ''; if($d['url']){ // If the person has entered a URL when adding a comment, // define opening and closing hyperlink tags $link_open = '<a href="'.$d['url'].'">'; $link_close = '</a>'; } // Converting the time to a UNIX timestamp: // Needed for the default gravatar image: $url = 'http://'.dirname($_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]).'/img/default_avatar.gif'; return ' <div class="comment"> <div class="name">'.$link_open.$d['name'].$link_close.'</div> <div class="date" title="Added at '.date('H:i \o\n d M Y',$d['dt']).'">'.date('d M Y',$d['dt']).'</div> <p>'.$d['body'].'</p> </div> '; } /*Здесь доработано*/ public static function validate(&$arr) { /* / This method is used to validate the data sent via AJAX. / / It return true/false depending on whether the data is valid, and populates / the $arr array passed as a paremter (notice the ampersand above) with / either the valid input data, or the error messages. */ if($arr['page id'] == 'none' || !is_numeric($arr['page id']) || !($data['page id'] = (int )$arr['page id'])) { $errors['email'] = 'wrong page id'; } // Using the filter_input function introduced in PHP 5.2.0 if(!($data['email'] = filter_input(INPUT_POST ,'email',FILTER_VALIDATE_EMAIL ))) { $errors['email'] = 'Please enter a valid Email.'; } if(!($data['url'] = filter_input(INPUT_POST ,'url',FILTER_VALIDATE_URL ))) { // If the URL field was not populated with a valid URL, // act as if no URL was entered at all: $url = ''; } // Using the filter with a custom callback function: if(!($data['body'] = filter_input(INPUT_POST ,'body',FILTER_CALLBACK ,array('options'=>'Comment::validate_text')))) { $errors['body'] = 'Please enter a comment body.'; } if(!($data['name'] = filter_input(INPUT_POST ,'name',FILTER_CALLBACK ,array('options'=>'Comment::validate_text')))) { $errors['name'] = 'Please enter a name.'; } // If there are errors, copy the $errors array to $arr: $arr = $errors; return false; } // If the data is valid, sanitize all the data and copy it to $arr: foreach($data as $k=>$v){ } // Ensure that the email is lower case: return true; } private static function validate_text($str) { /* / This method is used internally as a FILTER_CALLBACK */ return false; // Encode all html special characters (<, >, ", & .. etc) and convert // the new line characters to <br> tags: // Remove the new line characters that are left return $str; } } ?>
submit.php - обработка формы
PHP:
скопировать код в буфер обмена
<?PHP // Error reporting: include "connect.php"; include "comment.class.php"; /* / This array is going to be populated with either / the data that was sent to the script, or the / error messages. /*/ $validates = Comment::validate($arr); if($validates) { /* Everything is OK, insert to database: */ VALUES ( '".$arr['name']."', '".$arr['email']."', '".$arr['body']."' '".$arr['page id']."' )"); /* / The data in $arr is escaped for the mysql query, / but we need the unescaped variables, so we apply, / stripslashes to all the elements in the array: /*/ $insertedComment = new Comment($arr); /* Outputting the markup of the just-inserted comment: */ } else { /* Outputtng the error messages */ } ?>
еще там есть файлы jquery.min.js и script.js если нужно могу тоже выложить. |