Comment posting code in php

This is an example

The header above will say ‘This is an example’.

‘C’ style comments end at the first */ encountered. Make sure you don’t nest ‘C’ style comments. It is easy to make this mistake if you are trying to comment out a large block of code.

User Contributed Notes 12 notes

Notes can come in all sorts of shapes and sizes. They vary, and their uses are completely up to the person writing the code. However, I try to keep things consistent in my code that way it’s easy for the next person to read. So something like this might help.

/* Title Here Notice the First Letters are Capitalized */

# Option 1
# Option 2
# Option 3

/*
* This is a detailed explanation
* of something that should require
* several paragraphs of information.
*/

// This is a single line quote.
?>

A nice way to toggle the commenting of blocks of code can be done by mixing the two comment styles:
//*
if ( $foo ) echo $bar ;
>
// */
sort ( $morecode );
?>

Now by taking out one / on the first line..

/*
if ($foo) echo $bar;
>
// */
sort ( $morecode );
?>
..the block is suddenly commented out.
This works because a /* .. */ overrides //. You can even «flip» two blocks, like this:
//*
if ( $foo ) echo $bar ;
>
/*/
if ($bar) echo $foo;
>
// */
?>
vs
/*
if ($foo) echo $bar;
>
/*/
if ( $bar ) echo $foo ;
>
// */
?>

As of php 8, single line comments starting exactly with «#[» have a special meaning: they are treated as «attributes», and they must respect the expected syntax. See: https://www.php.net/manual/en/language.attributes.php

So the following code throws an error in php 8+, while it is perfectly valid in php #[~~my super cool comment~~~]
?>

To be safe, just always use «//» comments instead of «#». Maybe in the future there will be other special meanings for the «#» comments, who knows.

It is worth mentioning that, HTML comments have no meaning in PHP parser. So,

WILL execute some_function() and echo result inside HTML comment.

Comments in PHP can be used for several purposes, a very interesting one being that you can generate API documentation directly from them by using PHPDocumentor (http://www.phpdoc.org/).

Therefor one has to use a JavaDoc-like comment syntax (conforms to the DocBook DTD), example:
/**
* The second * here opens the DocBook commentblock, which could later on

* in your development cycle save you a lot of time by preventing you having to rewrite

* major documentation parts to generate some usable form of documentation.
*/
?>
Some basic html-like formatting is supported with this (ie
tags) to create something of a layout.

MSpreij (8-May-2005) says /* .. */ overrides //
Anonymous (26-Jan-2006) says // overrides /* .. */

Actually, both are correct. Once a comment is opened, *everything* is ignored until the end of the comment (or the end of the php block) is reached.

Thus, if a comment is opened with:
// then /* and */ are «overridden» until after end-of-line
/* then // is «overridden» until after */

Be careful when commenting out regular expressions.

E.g. the following causes a parser error.

I do prefer using # as regexp delimiter anyway so it won’t hurt me 😉

Comments do NOT take up processing power.

So, for all the people who argue that comments are undesired because they take up processing power now have no reason to comment 😉

// Control
echo microtime (), «
» ; // 0.25163600 1292450508
echo microtime (), «
» ; // 0.25186000 1292450508

// Test
echo microtime (), «
» ; // 0.25189700 1292450508
# TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST
# .. Above comment repeated 18809 times ..
echo microtime (), «
» ; // 0.25192100 1292450508

?>

They take up about the same amount of time (about meaning on a repeated testing, sometimes the difference between the control and the test was negative and sometimes positive).

it’s perhaps not obvious to some, but the following code will cause a parse error! the ?> in //?> is not treated as commented text, this is a result of having to handle code on one line such as

if( 1 == 1 )
// ?>
>
?>

i discovered this «anomally» when i commented out a line of code containing a regex which itself contained ?>, with the // style comment.
e.g. //preg_match(‘/^(?>c|b)at$/’, ‘cat’, $matches);
will cause an error while commented! using /**/ style comments provides a solution. i don’t know about # style comments, i don’t ever personally use them.

a trick I have used in all languages to temporarily block out large sections (usually for test/debug/new-feature purposes), is to set (or define) a var at the top, and use that to conditionally comment the blocks; an added benefit over if(0) (samuli’s comment from nov’05) is that u can have several versions or tests running at once, and u dont require cleanup later if u want to keep the blocks in: just reset the var.

personally, I use this more to conditionally include code for new feature testing, than to block it out. but hey, to each their own 🙂

this is also the only safe way I know of to easily nest comments in any language, and great for multi-file use, if the conditional variables are placed in an include 🙂

for example, placed at top of file:

and then deeper inside the file:

print( «This code is included since we are testing version 3» );
>
?>

print( «This code is ‘commented’ out» );
>
?>

In php there are 3 types of comments
1.single line c++ style comment(//)
2.single line Unix shell stype comment(#)
3.multi line c style comment(/*/)

single or multi line comment comes to the end of the line or come first to the current block of php code.

HTML code will be printed after //. > or #. >
closing tag breaks the php mode and return to html mode.

different comments in different tags:
===================================

Standard tag: single line c++ style comment

The header above will break php mode and return html mode and show ‘Standard tag:single line c++ style comment’

Standard tag: single line unix shell style comment

The header above will break php mode and return html mode and show ‘Standard tag:single line unix shell style comment’

Standard tag: multi line c style comment

The header above will break php mode and return html mode and show ‘Standard tag:multi line c style comment’

short echo tag: single line c++ style comment

The header above will break php mode show a unexpected syntex error’

short echo tag: single line c++ style comment

The header above will break php mode show a unexpected syntex error’

short echo tag: multiple line c style comment

The header above will break php mode show a unexpected syntex error’

Short tag: single line c++ style comment

The header above will break php mode and return html mode and show ‘Short tag:single line c++ style comment’

Short tag: single line unix shell style comment

The header above will break php mode and return html mode and show ‘Short tag:single line unix shell style comment’

Short tag: multi line c style comment

The header above will break php mode and return html mode and show ‘Short tag:multi line c style comment’

Script tag: single line c++ style comment

The header above will break php mode and return html mode and show ‘Script tag:single line c++ style comment’

Script tag: multi line c style comment

The header above will break php mode and return html mode and show ‘Script tag:multi line c style comment’

Script tag: single line unix shell style comment

The header above will not break php mode

Источник

Как сделать комментирование на сайте

Как сделать комментирование на сайте

Очень часто у меня спрашивают, как сделать комментирование на сайте на PHP. Я решил не объяснять на пальцах каждому, а просто написать статью, в которой показать, как делается комментирование на сайте с использованием PHP и MySQL.

Мы сейчас будем разбирать PHP-код для создания комментирования на сайте, где имеется множество страниц, на каждой из которых свои комментарии. Например, таким образом, реализовано у меня. Это самый популярный вариант, когда у каждой страницы (статьи, поста и прочего) свой набор комментариев.

Первым делом, создаём таблицу в базе данных (пусть она называется comments), где будут храниться комментарии со следующими полями:

  • id — уникальный идентификатор.
  • page_id — хранится идентификатор той страницы, на которой находится данный комментарий.
  • name — имя того, кто оставил комментарий.
  • text_comment — текст комментария.

После создания таблицы, давайте создадим HTML-форму, которую нужно будет размещать на каждой странице, где Вы хотите разрешить добавление комментариев:

Единственная особенность данного HTML-кода — это input hidden. В value должен находиться уникальный идентификатор текущей страницы (статьи или поста).

Теперь займёмся обработкой формы. Для этого создаём файл comment.php с таким кодом:

/* Принимаем данные из формы */
$name = $_POST[«name»];
$page_id = $_POST[«page_id»];
$text_comment = $_POST[«text_comment»];
$name = htmlspecialchars($name);// Преобразуем спецсимволы в HTML-сущности
$text_comment = htmlspecialchars($text_comment);// Преобразуем спецсимволы в HTML-сущности
$mysqli = new mysqli(«localhost», «root», «», «db»);// Подключается к базе данных
$mysqli->query(«INSERT INTO `comments` (`name`, `page_id`, `text_comment`) VALUES (‘$name’, ‘$page_id’, ‘$text_comment’)»);// Добавляем комментарий в таблицу
header(«Location: «.$_SERVER[«HTTP_REFERER»]);// Делаем реридект обратно
?>

И, наконец, последняя стадия — это вывод комментариев на странице:

$page_id = 150;// Уникальный идентификатор страницы (статьи или поста)
$mysqli = new mysqli(«localhost», «root», «», «db»);// Подключается к базе данных
$result_set = $mysqli->query(«SELECT * FROM `comments` WHERE `page_id`=’$page_id'»); //Вытаскиваем все комментарии для данной страницы
while ($row = $result_set->fetch_assoc()) print_r($row); //Вывод комментариев
echo «
«;
>
?>

Вот и всё. Безусловно, это лишь база, необходимая для создания возможности комментирования на сайте. Здесь самое минимальное, что придётся сделать — это оформить внешний вид комментариев. Также надо обязательно проверить поступившие данные из формы. Также можно добавить дополнительные поля (например, e-mail ещё запрашивать).

Но всё это уже детали, а комментирование на PHP уже сделано.

Чтобы понять весь алгоритм и, главное, научиться самостоятельно создавать подобные скрипты, обязательно изучите PHP и MySQL, и в этом Вам поможет мой Видеокурс «PHP и MySQL с Нуля до Гуру«: http://srs.myrusakov.ru/php

Создано 01.02.2012 14:47:38

  • Михаил Русаков
  • Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

    Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 159 ):

    не понял с пунктом «вывод комментариев на странице» это создаётся ещё один php файл?? или все в одном? и ещё один вопрос, создал форму, как у вас и пхп файл, как нажимаю в форме кнопку отправить пишет вот такое: query(«INSERT INTO `comments` (`name`, `page_id`, `text_comment`) VALUES (‘$name’, ‘$page_id’, ‘$text_comment’)»);// Добавляем комментарий в таблицу header(«Location: «.$_SERVER[«HTTP_REFERER»]);// Делаем реридект обратно ?>

    Вы либо невнимательно читаете, либо Вам ещё просто рано про это вообще читать. Вы основы точно знаете? Теперь по вопросам: 1. Вывод комментариев на той же странице, где форма. 2. Как он может такое писать? Только если, конечно, Вы не открываете через file:///Z:\home. Если так, то забудьте про эту статью. С такой проблемой новички сталкиваются в первый день обучения PHP.

    Евгений вы для начала разберите алгоритм создания комментариев. Всё создаётся на одной или двух страницах. Допустим если на двух то: text.php //это файл для формы и вивода комментов update_comment.php //это фаил обработчик Вот и всё!

    сорри поспешил, ушел дальше разбираться

    Спасибо Михаил всё это знал только вот не знал как id страницы отправить спасибо!!

    Салам! Михайил У меня вывод комментариев на странице не выходить. В базе MySQL данные есть но на странице нету!

    Тысяча причин, все перечислить невозможно. Могу лишь назвать парочку: по-другому названы поля в таблице, соответственно, неверный запрос. Либо ещё файл не обрабатывает PHP вообще, либо он имеет расширение html, либо запускается неправильно (допустим, просто открывается через двойной клик в браузере).

    Михаил, а идентификатор страницы, обычная строка или с Auto_increment

    Это уникальный номер страницы (число). А какой он, неважно, главное, чтобы число и уникальный.

    Источник

    Читайте также:  Python combobox все значения
    Оцените статью