Постраничная навигация на PHP

Here, we discuss how to use PHP to work with variables submitted with a form.

Many website applications rely on HTML forms so that users can perform their tasks. For example, most Content Management Systems allow users to provide content for a website by entering the content into a textarea form field, then clicking a "Save" button. When the user clicks the Save button, the form is submitted to the action page. The action page is normally specified with the action attribute of the form tag.

If you"re not familar with HTML forms, see the HTML forms section of the HTML tutorial , then return to this page.

Once a form has been submitted, the form fields are made available to the action page as a special type of variable. You, as the programmer, can read these form variables by using the appropriate syntax for form variables. Form variables are stored as an array . We will be covering arrays later, but for now all you need to know is how to read each form variable.

Forms can be submitted using one of two methods: get or post . By default, a form will be submitted using the "get" method. This results in each form variable being passed via the URL. If you decide to use the "post" method, you specify this using the method attribute (method="post") of the form tag.

The Get Method

If you use the get method, your action page can access each form field using $_GET["variableName"] (where "variableName" is the name of the form field).

Example

Form page

Stack editor Unstack editor



Action page (php_action_page1.php):

Here, the action page outputs the contents of the form variables that were passed from the form.

PHP Form Variables Example First Name:
Last Name:

Back

Проблема реализации постраничной навигации часто встает перед начинающими PHP-программистами. К разбиению объёмного текста на отдельные страницы прибегают во многих Web-приложениях от гостевых книг и форумов до различных каталогов. Давайте
решим эту проблему.
Итак, что нам требуется для реализации постраничной навигации? Для примера возьмем гостевую книгу, содержащую несколько сотен сообщений, в которой требуется выводить на страницу Х сообщений.
Рассмотрим задачу более конкретно. Сообщения пользователей хранятся в базе данных post со следующей структурой:

  • id – номер сообщения,
  • text – тело сообщения,
  • name – имя автора,
  • time – время создания.

В итоге нам надо получить вывод Х сообщений на страницу, а также организовать удобную навигацию, например, такую:

>>

где 4 - текущая станица. Для того чтобы отслеживать текущую страницу, будем использовать параметр page , передаваемый через URL. К примеру:

Www.myserver.com/index.php?page=X.

Здесь X - номер станицы (для примера, пусть Х будет равно 25).

Теперь, после этого небольшого введения, можно приступать к непосредственной реализации.

На этом первая часть закончена. Двумерный массив postrow хранит все поля таблицы post, необходимые для отображения станицы. Вот пример как можно организовать вывод сообщений.

Теперь надо организовать навигацию. Формируем составляющие будущей навигации.
Коды стрелки «в начало» и «назад» поместим в одну переменную, также поступим и со стрелками «в конец» и «вперед».

to force a space and a line feed to be output, or you can put an explicit line feed in the last echo/print from within your PHP block.

Note : A Note on Text Editors

There are many text editors and Integrated Development Environments (IDEs) that you can use to create, edit and manage PHP files. A partial list of these tools is maintained at » PHP Editors List . If you wish to recommend an editor, please visit the above page and ask the page maintainer to add the editor to the list. Having an editor with syntax highlighting can be helpful.

Note : A Note on Word Processors

Word processors such as StarOffice Writer, Microsoft Word and Abiword are not optimal for editing PHP files. If you wish to use one for this test script, you must ensure that you save the file as plain text or PHP will not be able to read and execute the script.

Note : A Note on Windows Notepad

If you are writing your PHP scripts using Windows Notepad, you will need to ensure that your files are saved with the .php extension. (Notepad adds a .txt extension to files automatically unless you take one of the following steps to prevent it.) When you save the file and are prompted to provide a name for the file, place the filename in quotes (i.e. " hello.php "). Alternatively, you can click on the "Text Documents" drop-down menu in the "Save" dialog box and change the setting to "All Files". You can then enter your filename without quotes.

Now that you have successfully created a working PHP script, it is time to create the most famous PHP script! Make a call to the phpinfo() function and you will see a lot of useful information about your system and setup such as available predefined variables , loaded PHP modules, and configuration settings. Take some time and review this important information.

Example #2 Get system information from PHP