Сценарий дня рождения мужчины. Многоуровневое меню на PHP и MySQL Рождения мужчине search item php i

Лучший способ удержать пользователя на сайте, это позволить ему найти, то что он ищет. Если вы делаете для этого удобную систему, то уровень предпочтения вашего сайта будет расти и пользователь обязательно вернётся для того, чтобы найти то, что его интересует.

Я вам покажу как создать простую, но эффективную по функционалу, поисковую форму, которая будет использоваться для поиска статей на сайте. Результаты будут появляться на странице без никаких перезагрузок, что несомненно является лучшим способом подачи информации.

Я создам 2 файла: search.php, который будет содержать HTML и JavaScript. Второй файл, do_search.php будет содержать PHP код. Приступим к созданию первого файла:

PHP, jQuery search demo $(function() { $(".search_button").click(function() { // получаем то, что написал пользователь var searchString = $("#search_box").val(); // формируем строку запроса var data = "search="+ searchString; // если searchString не пустая if(searchString) { // делаем ajax запрос $.ajax({ type: "POST", url: "do_search.php", data: data, beforeSend: function(html) { // запустится до вызова запроса $("#results").html(""); $("#searchresults").show(); $(".word").html(searchString); }, success: function(html){ // запустится после получения результатов $("#results").show(); $("#results").append(html); } }); } return false; }); }); Попробуйте ввести слово ajax
Результаты для

В этом файле мы создали обычную HTML форму, которая посылает POST запрос в бэк энд - файлу do_search.php.

PHP код содержит комментарии, по которым вы с лёгкостью сможете понять работу скрипта. Если в базе данных нашлись совпадения, вы показываете их вашему пользователю, выделяя жирным те слова, которые искал пользователь.

Придадим всему этому немного CSS:

Body{ font-family:Arial, Helvetica, sans-serif; } *{ margin:0;padding:0; } #container { margin: 0 auto; width: 600px; } a { color:#DF3D82; text-decoration:none } a:hover { color:#DF3D82; text-decoration:underline; } ul.update { list-style:none;font-size:1.1em; margin-top:10px } ul.update li{ height:30px; border-bottom:#dedede solid 1px; text-align:left;} ul.update li:first-child{ border-top:#dedede solid 1px; height:30px; text-align:left; } #flash { margin-top:20px; text-align:left; } #searchresults { text-align:left; margin-top:20px; display:none; font-family:Arial, Helvetica, sans-serif; font-size:16px; color:#000; } .word { font-weight:bold; color:#000000; } #search_box { padding:4px; border:solid 1px #666666; width:300px; height:30px; font-size:18px;-moz-border-radius: 6px;-webkit-border-radius: 6px; } .search_button { border:#000000 solid 1px; padding: 6px; color:#000; font-weight:bold; font-size:16px;-moz-border-radius: 6px;-webkit-border-radius: 6px; } .found { font-weight: bold; font-style: italic; color: #ff0000; } h2 { margin-right: 70px; }

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

Updated on April 30, 2016

I"m going to show you how to create simple search using PHP and MySQL. You"ll learn:

  • How to use GET and POST methods
  • Connect to database
  • Communicate with database
  • Find matching database entries with given word or phrase
  • Display results
Preparation

You should have Apache, MySQL and PHP installed and running of course (you can use for different platforms or WAMP for windows, MAMP for mac) or a web server/hosting that supports PHP and MySQL databases.

Let"s create database, table and fill it with some entries we can use for search:

  • Go to phpMyAdmin, if you have server on your computer you can access it at http://localhost/phpmyadmin/
  • Create database, I called mine tutorial_search
  • Create table I used 3 fields, I called mine articles.
  • Configuration for 1st field. Name: id, type: INT, check AUTO_INCREMENT, index: primary

INT means it"s integer
AUTO_INCREMENT means that new entries will have other(higher) number than previous
Index: primary means that it"s unique key used to identify row

  • 2nd field: Name: title, type: VARCHAR, length: 225

VARCHAR means it string of text, maximum 225 characters(it is required to specify maximum length), use it for titles, names, addresses
length means it can"t be longer than 225 characters(you can set it to lower number if you want)

  • 3rd field: Name: text, type: TEXT

TEXT means it"s long string, it"s not necessary to specify length, use it for long text.

  • Fill the table with some random articles(you can find them on news websites, for example: CNN, BBC, etc.). Click insert on the top menu and copy text to a specific fields. Leave "id" field empty. Insert at least three.

It should look something like this:

  • Create a folder in your server directory and two files: index.php and search.php (actually we can do all this just with one file, but let"s use two, it will be easier)
  • Fill them with default html markup, doctype, head, etc.

Search

  • Create a form with search field and submit button in index.php, you can use GET or POST method, set action to search.php. I used "query" as name for text field

GET - means your information will be stored in url (http://localhost/tutorial_search/search.php?query=yourQuery )
POST - means your information won"t be displayed it is used for passwords, private information, much more secure than GET

Ok, let"s get started with php.

  • Open search.php
  • Start php ()
  • Connect to a database(read comments in following code)