PHP.SU

Программирование на PHP, MySQL и другие веб-технологии
PHP.SU Портал     На главную страницу форума Главная     Помощь Помощь     Поиск Поиск     Поиск Яндекс Поиск Яндекс     Вакансии  Пользователи Пользователи

Страниц (7): « 1 2 3 4 5 6 [7]

> Найдено сообщений: 96
gigs Отправлено: 25 Апреля, 2012 - 17:17:01 • Тема: Повторяются комментарии на страницах • Форум: Вопросы новичков

Ответов: 15
Просмотров: 543
так в чем проблема ?
gigs Отправлено: 25 Апреля, 2012 - 17:10:30 • Тема: Повторяются комментарии на страницах • Форум: Вопросы новичков

Ответов: 15
Просмотров: 543
это типа проверяет id страницы чтобы комментарии не повторялись на всех страницах, но почемуто оно сейчас вобще ничего не отсылает
gigs Отправлено: 25 Апреля, 2012 - 17:00:39 • Тема: Повторяются комментарии на страницах • Форум: Вопросы новичков

Ответов: 15
Просмотров: 543
Таблица называется comments
gigs Отправлено: 25 Апреля, 2012 - 16:27:55 • Тема: Повторяются комментарии на страницах • Форум: Вопросы новичков

Ответов: 15
Просмотров: 543
Неужели никто не знает как мне помочь, я уже все выклал вот только не знаю чего там еще не хватает.
gigs Отправлено: 24 Апреля, 2012 - 23:01:29 • Тема: Повторяются комментарии на страницах • Форум: Вопросы новичков

Ответов: 15
Просмотров: 543
(Добавление)
gigs пишет:
ну а как это сделать, если нужно то я могу выложить код формы коментариев я там почти все сделал вот только не знаю где у меня ошибка.

Вот сам код уже исправленый, только типерь когда нажимаеш отправить то страница перезагружается и все, а комментарий не добавляется ни в базу ни на странице, вот я не могу понять почему ?

demo.php - здесь находится форма добавления комментариев
PHP:
скопировать код в буфер обмена
  1. <?PHP
  2.  
  3. // Error reporting:
  4. error_reporting(E_ALL^E_NOTICE);
  5.  
  6. include "connect.php";
  7. include "comment.class.php";
  8.  
  9.  
  10. /*
  11. /       Select all the comments and populate the $comments array with objects
  12. */
  13.  
  14. $comments = array();
  15. $result = mysql_query("SELECT * FROM comments where PageID = '" . $pageID . "' ORDER BY id ASC");
  16. $pageID = (isset($_GET['id'])) ? (int)$_GET['id'] : 'none';
  17.  
  18. while($row = mysql_fetch_assoc($result))
  19. {
  20.         $comments[] = new Comment($row);
  21. }
  22.  
  23. ?>
  24.  
  25.  
  26.  
  27. <link rel="stylesheet" type="text/css" href="styles.css" />
  28.  
  29.  
  30.  
  31.  
  32.  
  33.  
  34.  
  35. <div id="main">
  36.  
  37. <?PHP
  38.  
  39. /*
  40. /       Вывод комментариев один за другим:
  41. */
  42.  
  43. foreach($comments as $c){
  44.         echo $c->markup();
  45. }
  46.  
  47. ?>
  48.  
  49. <div id="addCommentContainer">
  50.         <p>Добавить комментарий</p>
  51.         <form id="addCommentForm" method="post" action="">
  52.         <div>
  53.                 <label for="name">Имя</label>
  54.                 <input type="text" name="name" id="name" />
  55.            
  56.             <label for="email">Email</label>
  57.             <input type="text" name="email" id="email" />
  58.            
  59.             <input type="hidden" name="page id" value="<? echo (isset($_GET['id'])) ? $_GET['id'] : 'none' ; ?>" />
  60.            
  61.             <label for="body">Содержание комментария</label>
  62.             <textarea name="body" id="body" cols="20" rows="5"></textarea>
  63.            
  64.             <input type="submit" id="submit" value="Отправить" />
  65.         </div>
  66.     </form>
  67. </div>
  68.  
  69. </div>
  70.  
  71. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
  72. <script type="text/javascript" src="script.js"></script>
  73.  
  74.  


connect.php - связь с базой
PHP:
скопировать код в буфер обмена
  1.  
  2. <?PHP
  3.  
  4. /* Database config */
  5.  
  6. $db_host        = 'localhost';
  7. $db_user        = 'свое';
  8. $db_pass        = 'свое';
  9. $db_database        = 'свое';
  10.  
  11. /* End config */
  12.  
  13.  
  14. $link = @mysql_connect($db_host,$db_user,$db_pass) or die('Unable to establish a DB connection');
  15.  
  16. mysql_query("SET NAMES 'utf8'");
  17. mysql_select_db($db_database,$link);
  18.  
  19. ?>


comment.class.php - Вывод комментариев и генерация html кода комментария.Проверка формы на заполнение всех полей, а так же правильности заполнения email и обновление комментариев на странице.
PHP:
скопировать код в буфер обмена
  1. <?PHP
  2.  
  3. class Comment
  4. {
  5.         private $data = array();
  6.        
  7.         public function __construct($row)
  8.         {
  9.                 /*
  10.                 /       The constructor
  11.                 */
  12.                
  13.                 $this->data = $row;
  14.         }
  15.        
  16.         public function markup()
  17.         {
  18.                 /*
  19.                 /       This method outputs the XHTML markup of the comment
  20.                 */
  21.                
  22.                 // Setting up an alias, so we don't have to write $this->data every time:
  23.                 $d = &$this->data;
  24.                
  25.                 $link_open = '';
  26.                 $link_close = '';
  27.                
  28.                 if($d['url']){
  29.                        
  30.                         // If the person has entered a URL when adding a comment,
  31.                         // define opening and closing hyperlink tags
  32.                        
  33.                         $link_open = '<a href="'.$d['url'].'">';
  34.                         $link_close =  '</a>';
  35.                 }
  36.                
  37.                 // Converting the time to a UNIX timestamp:
  38.                 $d['dt'] = strtotime($d['dt']);
  39.                
  40.                 // Needed for the default gravatar image:
  41.                 $url = 'http://'.dirname($_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]).'/img/default_avatar.gif';
  42.                
  43.                 return '
  44.                
  45.                         <div class="comment">
  46.                                
  47.                                
  48.                                 <div class="name">'.$link_open.$d['name'].$link_close.'</div>
  49.                                 <div class="date" title="Added at '.date('H:i \o\n d M Y',$d['dt']).'">'.date('d M Y',$d['dt']).'</div>
  50.                                 <p>'.$d['body'].'</p>
  51.                         </div>
  52.                 ';
  53.         }
  54.         /*Здесь доработано*/
  55.         public static function validate(&$arr)
  56.         {
  57.                 /*
  58.                 /       This method is used to validate the data sent via AJAX.
  59.                 /
  60.                 /       It return true/false depending on whether the data is valid, and populates
  61.                 /       the $arr array passed as a paremter (notice the ampersand above) with
  62.                 /       either the valid input data, or the error messages.
  63.                 */
  64.                
  65.                 $errors = array();
  66.                 $data   = array();
  67.                
  68.                  if($arr['page id'] == 'none' || !is_numeric($arr['page id']) || !($data['page id'] = (int)$arr['page id']))
  69.         {
  70.             $errors['email'] = 'wrong page id';
  71.         }
  72.        
  73.        
  74.                 // Using the filter_input function introduced in PHP 5.2.0
  75.                
  76.                 if(!($data['email'] = filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)))
  77.                 {
  78.                         $errors['email'] = 'Please enter a valid Email.';
  79.                 }
  80.                
  81.                 if(!($data['url'] = filter_input(INPUT_POST,'url',FILTER_VALIDATE_URL)))
  82.                 {
  83.                         // If the URL field was not populated with a valid URL,
  84.                         // act as if no URL was entered at all:
  85.                        
  86.                         $url = '';
  87.                 }
  88.                
  89.                 // Using the filter with a custom callback function:
  90.                
  91.                 if(!($data['body'] = filter_input(INPUT_POST,'body',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
  92.                 {
  93.                         $errors['body'] = 'Please enter a comment body.';
  94.                 }
  95.                
  96.                 if(!($data['name'] = filter_input(INPUT_POST,'name',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
  97.                 {
  98.                         $errors['name'] = 'Please enter a name.';
  99.                 }
  100.                
  101.                 if(!empty($errors)){
  102.                        
  103.                         // If there are errors, copy the $errors array to $arr:
  104.                        
  105.                         $arr = $errors;
  106.                         return false;
  107.                 }
  108.                
  109.                 // If the data is valid, sanitize all the data and copy it to $arr:
  110.                
  111.                 foreach($data as $k=>$v){
  112.                         $arr[$k] = mysql_real_escape_string($v);
  113.                 }
  114.                
  115.                 // Ensure that the email is lower case:
  116.                
  117.                 $arr['email'] = strtolower(trim($arr['email']));
  118.                
  119.                 return true;
  120.                
  121.         }
  122.  
  123.         private static function validate_text($str)
  124.         {
  125.                 /*
  126.                 /       This method is used internally as a FILTER_CALLBACK
  127.                 */
  128.                
  129.                 if(mb_strlen($str,'utf8')<1)
  130.                         return false;
  131.                
  132.                 // Encode all html special characters (<, >, ", & .. etc) and convert
  133.                 // the new line characters to <br> tags:
  134.                
  135.                 $str = nl2br(htmlspecialchars($str));
  136.                
  137.                 // Remove the new line characters that are left
  138.                 $str = str_replace(array(chr(10),chr(13)),'',$str);
  139.                
  140.                 return $str;
  141.         }
  142.  
  143. }
  144.  
  145. ?>


submit.php - обработка формы
PHP:
скопировать код в буфер обмена
  1. <?PHP
  2.  
  3. // Error reporting:
  4. error_reporting(E_ALL^E_NOTICE);
  5.  
  6. include "connect.php";
  7. include "comment.class.php";
  8.  
  9. /*
  10. /       This array is going to be populated with either
  11. /       the data that was sent to the script, or the
  12. /       error messages.
  13. /*/
  14.  
  15. $arr = array();
  16. $validates = Comment::validate($arr);
  17.  
  18. if($validates)
  19. {
  20.         /* Everything is OK, insert to database: */
  21.        
  22.         mysql_query("   INSERT INTO comments(name,email,body)
  23.                                         VALUES (
  24.                                                 '".$arr['name']."',                                            
  25.                                                 '".$arr['email']."',
  26.                                                 '".$arr['body']."'
  27.                                                 '".$arr['page id']."'
  28.                                         )");
  29.        
  30.         $arr['dt'] = date('r',time());
  31.         $arr['id'] = mysql_insert_id();
  32.        
  33.         /*
  34.         /       The data in $arr is escaped for the mysql query,
  35.         /       but we need the unescaped variables, so we apply,
  36.         /       stripslashes to all the elements in the array:
  37.         /*/
  38.        
  39.         $arr = array_map('stripslashes',$arr);
  40.        
  41.         $insertedComment = new Comment($arr);
  42.  
  43.         /* Outputting the markup of the just-inserted comment: */
  44.  
  45.         echo json_encode(array('status'=>1,'html'=>$insertedComment->markup()));
  46.  
  47. }
  48. else
  49. {
  50.         /* Outputtng the error messages */
  51.         echo '{"status":0,"errors":'.json_encode($arr).'}';
  52. }
  53.  
  54. ?>


еще там есть файлы jquery.min.js и script.js если нужно могу тоже выложить.
gigs Отправлено: 24 Апреля, 2012 - 22:46:56 • Тема: Повторяются комментарии на страницах • Форум: Вопросы новичков

Ответов: 15
Просмотров: 543
Помогите пожалуйста, в интернете нашел неплохую форму комментариев для сайта и установил себе на свой сайт но возникла такая проблема, эта форма у меня стоит почти на каждой странице и когда я ввожу какой то комментарий на одной странице то при переходе на другую страницу он там тоже появляется, я хочу сделать так чтобы на каждой странице были свои так сказать уникальные комментарии, чтоб один и тот же комментарий не повторялся на других страницах, ну как на всех нормальных сайтах, как мне это сделать ? или это нужно под каждую страницу создавать свою базу данных ?

Страниц (7): « 1 2 3 4 5 6 [7]
Powered by PHP  Powered By MySQL  Powered by Nginx  Valid CSS  RSS

 
Powered by ExBB FM 1.0 RC1. InvisionExBB