Описание мужчины search item php i. Создаем кастомный тип записи (Custom Post Type) с кастомными категориями (Custom Taxonomy)

Основные задачи:

  • реализовать поиск таким образом, чтобы после ввода поискового запроса в строку, ниже этой строки появились результаты поиска
  • запрос на получение результата должен происходить только после окончания ввода поискового запроса

Окей, поехали!

Примерная вёрстка самого блока с поисковой строкой и div-ником, куда будем добавлять результаты поиска:

Т.к. поиск доступен в шапке сайта, добавим соответствующие скрипты поиска и стилизации результатов:

//подрубаем поиск: $APPLICATION->AddHeadScript("/search/ajax_search.js"); $APPLICATION->AddHeadScript("/search/jquery.mCustomScrollbar.js"); $APPLICATION->SetAdditionalCSS(SITE_TEMPLATE_PATH . "/css/ajax_search.css"); $APPLICATION->SetAdditionalCSS(SITE_TEMPLATE_PATH . "/css/jquery.mCustomScrollbar.min.css");

Теперь посмотрим, что лежит в нашем ajax_search.js:

Function get_result (){ //очищаем результаты поиска $("#search_result").html(""); //пока не получили результаты поиска - отобразим прелоадер $("#search_result").append(""); $.ajax({ type: "POST", url: "/search/ajax_search.php", data: "q="+q, dataType: "json", success: function(json){ //очистим прелоадер $("#search_result").html(""); $("#search_result").append(""); //добавляем каждый элемент массива json внутрь div-ника с class="live-search" (вёрстку можете использовать свою) $.each(json, function(index, element) { $("#search_result").find(".live-search").append(""+element.TITLE+""+element.BODY_FORMATED+""); //console.log (element.BODY_FORMATED); }); //стилизуем скроллинг $(".live-search").mCustomScrollbar({ scrollInertia: 500 }); } }); } var timer = 0; var q = ""; $(document).ready(function() { $("#q").keyup(function() { q = this.value; clearTimeout(timer); timer = setTimeout(get_result, 1000); }); $("#reset_live_search").click(function() { $("#search_result").html(""); }); });

keyup функция осуществляем вызов функции get_result(), которая собственно и заполняет div-ник с id=»search_result» по аяксу.

mCustomScrollbar — это просто вызов стилизации (можете отключить).

Данные от /search/ajax_search.php мы получаем в формате JSON.

С JS составляющей всё понятно, теперь посмотрим, что происходит в ajax_search.php:

В данном случае поиск осуществляется методом Search Битриксового класса CSearch. В PARAM2 пишем в каком инфоблоке ищем. Результаты поиска запихиваем в массив $result. Обратите внимание, что в $res[‘ITEM_ID’] может быть как элемент, так и раздел. В зависимости от того, что нашли, в $result_item[‘BODY_FORMATED’] пихаем либо название раздела, либо кусок текста из найдённого элемента инфоблока.

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)