Chuyển tới nội dung
Home » Search Code In Php | Requirement Before Start

Search Code In Php | Requirement Before Start

#12. Search Data using PHP and MySQL database.

Setup Files

The following files need to be created in the htdocs folder, which are categorically located at C:/xampp/htdocs:

  • search.php: This serves as the main file for the search engine, enabling user input and result display.
  • db.php: This file contains the database connection details.
  • ajax.php: This is the primary file responsible for generating AJAX requests to the server and retrieving results.
  • script.js: Contains JavaScript functions for executing AJAX requests.
  • style.css: Provides styling for the search engine.

Creating Search Form and Related Files In this step,

We will create the following files:

Search.php

Name the file search.php while creating. This is a main file of a search engine, where the user can view the result and input data. Put the code below into it by simply pasting it.


<br /> Live Search using AJAX<br />






Example:


Emily Anderson, Liam Johnson, Sophia Martinez, Ethan Thompson, Olivia Davis




db.php

This file contains the necessary details for establishing a database connection. Create a file named “db.php” and insert the following code:

ajax.php

This file acts as the main source for generating AJAX requests to the server and retrieving the results. Make a file called “ajax.php” and put the following code in it:


'; // Fetch the results from the database. while ($Result = MySQLi_fetch_array($ExecQuery)) { ?>

  • ")'>


  • script.js

    This file contains JavaScript functions that perform AJAX requests. Add the following code to the “script.js” file you just created:


    // Retrieve the value from "ajax.php". function fill(Value) { // Assign the value to the "search" div in "search.php". $('#search').val(Value); // Hide the "display" div in "search.php". $('#display').hide(); } $(document).ready(function() { // When a key is pressed in the "Search box" of "search.php", this function will be called. $("#search").keyup(function() { // Assign the search box value to a JavaScript variable named "name". var name = $('#search').val(); // Validate if "name" is empty. if (name == "") { // Assign an empty value to the "display" div in "search.php". $("#display").html(""); } // If the name is not empty. else { // Initiate an AJAX request. $.ajax({ // Set the AJAX type as "POST". type: "POST", // Send data to "ajax.php". url: "ajax.php", // Pass the value of "name" into the "search" variable. data: { search: name }, // If a result is found, this function will be called. success: function(html) { // Assign the result to the "display" div in "search.php". $("#display").html(html).show(); } }); } }); });

    style.css

    This file contains styling elements for the search engine. Add the following code to a file called “style.css“:


    a:hover { cursor: pointer; background-color: yellow; }

    1. The search engine is now ready for testing. To proceed, follow these steps:

    localhost:8080/search.php

    1. Enter some text in the search field to perform a search in the database.

    Note that as you type, the text will be sent to the script.js file, which will then forward the request to ajax.php. In ajax.php, a JavaScript function named “fill()” will process the fetched results and display them in the “display” div of the search.php file.

    Conclusion

    Congratulations! You have been successful in using PHP, MySQL, and AJAX to create a dynamic live search box. You now own a strong tool that can offer a flawless search experience to visitors to your website after completing this thorough guide. To make sure your website appears high on search engine result pages, keep in mind to regularly improve your content and track its performance.

    FAQs on Live Search Box

    Can I implement a live search box without using AJAX?

    While it’s possible to create a live search box using other technologies, AJAX is the recommended approach for its seamless and real-time data fetching capabilities.

    Do I need advanced programming skills to build a live search box?

    Basic knowledge of PHP, MySQL, HTML, CSS, and JavaScript is required. However, following the steps provided in this article will guide you through the process.

    Can I customize the appearance of the live search box to match my website’s design?

    Yes, you can customize the HTML and CSS of the live search box to ensure it aligns with your website’s branding and design.

    Is it possible to include additional search features, such as filters or sorting options?

    Absolutely! Once you have the core live search functionality implemented, you can expand upon it and add more advanced search features based on your specific requirements.

    Will the live search box work on mobile devices?

    Yes, by ensuring mobile responsiveness in your design and development process, the live search box will function seamlessly on all devices, including mobile phones and tablets.

    I’ve followed this tutorial thoroughly, and had success with it. However, it leads me to a dead end where I have to pay to access the tutorial on implementing a “Search” functionality to it.

    I was wondering if anyone could help me out on how I can implement a search functionality given how the tutorial is constructed? Tutorials seems like they don’t work with this.

    I’ve tried this on a separate page so far, but it doesn’t seem to work – also I don’t know how it can be implemented on my actual site.


    '.$fname.''.$lname.''; } } } ?>

    <br /> Search<br />



    Also, here’s where I’m trying to implement a search functionality. It just displays a table with the entries I’ve added to the database.

    List of Student Volunteers


    query($sql) as $row) { echo '

    '; echo '

    '; echo '

    '; echo '

    '; echo '

    '; echo '

    '; } Database::disconnect(); ?>

    Name Email Address Mobile Number Action
    '. $row['FirstName'] . ' '. $row['EmailAddress'] . ' '. $row['MobileNum'] . ' '; echo '

    Read

    '; echo ' '; echo '

    Update

    '; echo ' '; echo '

    Delete

    '; echo '

    In this tutorial we will create a Simple Search Box using PHP. PHP is a server-side scripting language designed primarily for web development. Using PHP, you can let your user directly interact with the script and easily to learned its syntax. It is mostly used by newly coders for its user-friendly environment.

    So Let’s do the coding…

    First, you have to download & install XAMPP or any local server that can runs PHP scripts. Here’s the link for XAMPP server https://www.apachefriends.org/index.html.

    And this is the link for the jquery that i used in this tutorial https://jquery.com/.

    Lastly, this is the link for the bootstrap that i used for the layout design https://getbootstrap.com/.

    Open your database web server then create a database name in it db_box. After that, click Import then locate the database file inside the folder of the application then click ok.

    Or, you can also create the sample table and insert a sample data in your database by copying and pasting the code below at SQL tab in your PHPMyAdmin.

    `blog_id` int(11) NOT NULL PRIMARY KEY AUTO_INCRMENT,(1, ‘The Little Gingerbread Man’, ‘Once upon a time there was an old woman who loved baking gingerbread. She would bake gingerbread cookies, cakes, houses and gingerbread people, all decorated with chocolate and peppermint, caramel candies and colored frosting.’),(2, ‘The Halloween House’, ‘Now Suzie\’s moved in–she\’s only 4–along with her brother, her father and mother, and little Picador. He\’s their dog. Well, maybe half a dog. He\’s a Chihuahua, as small as they come.\r\n\r\nSuzie\’s room is in the attic. It\’s no fun. With a high ceiling, cold and gloomy, and shadows that run halfway up the walls. Suzie hides under the blanket. Picador too. Come on, he\’s no guard dog.’);

    Open your any kind of text editor(notepad++, etc..). Then just copy/paste the code below then name it

    conn.php

    .


    $conn = mysqli_connect(‘localhost’, ‘root’, ”, ‘db_box’) or die(mysqli_error());if(!$conn){die(“Error: Failed to connect to database”);}?>

    This is where we will create a simple form for our application. To create the forms simply copy and write it into your text editor, then save it as

    index.php

    .


    PHP – Simple Search Box



    if(ISSET($_POST[‘search’])){$keyword = $_POST[‘keyword’];?>

    Kết quả



    Với đoạn mã nó sẽ hoạt động như sau:

    • Đầu tiên dữ liệu đưa vào input và lấy từ name=”search”
    • if(ISSET($_POST[‘submit’])) sẽ kiểm tra button xem người dùng đã nhấp chuột chưa
    • Nếu nhấp chuột thì dữ liệu được truyền từ name là search sang một biến $keyword
    • Sử dụng mệnh đề LIKE ‘%$keyword%’ nó sẽ tìm bất kỳ giá trị nào bằng với $keyword
    • Cuối cùng sử dụng vòng lặp để in dữ liệu đã tìm thấy lên màn hình
    • SELECT * FROM `posts` là bảng posts trên Database bạn phải điền đúng
    • WHERE `title`: title là cột trong CSDL

    Đây là bài tập đơn giản nhưng qua đây bạn sẽ hiểu được cách sử dụng mệnh đề LIKE để tìm kiếm trong PHP và MySQL. Sau khi làm xong bài này bạn sẽ xây dựng nên chức năng phức tạp hơn bằng cách kết hợp jQuery,

    You can create an HTML form that allows you to search records in your MySQL Tables and print the results in a web browser.

    In these project we use LIKE and wildcards for the query so that users do not have to have an exact match for results to be provided.

    Simple Search Form Project

    search.html



    Search



    phpSearch.php



    connect_error){ die("Connection failed: ". $conn->connect_error); } $sql = "select * from students where name like '%$search%'"; $result = $conn->query($sql); if ($result->num_rows > 0){ while($row = $result->fetch_assoc() ){ echo $row["name"]." ".$row["age"]." ".$row["gender"].""; } } else { echo "0 records"; } $conn->close(); ?>

    Option Box Search Form Project

    searchoption.html



    Search Column:



    phpSearchOption.php



    connect_error){ die("Connection failed: ". $conn->connect_error); } $sql = "select * from students where $column like '%$search%'"; $result = $conn->query($sql); if ($result->num_rows > 0){ while($row = $result->fetch_assoc() ){ echo $row["name"]." ".$row["age"]." ".$row["gender"].""; } } else { echo "0 records"; } $conn->close(); ?>

    Want to build a powerful Live search box using PHP, MySQL, and Ajax?

    If yes! Then this guide will help you explore how to create a powerful live search.

    Our goal is to provide you with an itemized step-by-step guide so that you can create a Live search box for yourself, understand the technical aspects of building a live search feature, and also outrank other websites.

    The live search feature, or AJAX search, refers to the search engine beginning to display results as you type text into the input field. You can view search results without bringing up a display page, thanks to this feature . As a result, people may locate what they’re seeking more quickly.. The development of AJAX search uses JavaScript (jQuery), MySQL, PHP, and AJAX.

    Even Google, the most popular search implements the idea of Live search on its page:

    #12. Search Data using PHP and MySQL database.
    #12. Search Data using PHP and MySQL database.

    Example Explained – The HTML Page

    When a user types a character in the input field above, the function “showResult()” is executed. The function is triggered by the “onkeyup” event:

    Source code explanation:

    If the input field is empty (str.length==0), the function clears the content of the livesearch placeholder and exits the function.

    If the input field is not empty, the showResult() function executes the following:

    • Create an XMLHttpRequest object
    • Create the function to be executed when the server response is ready
    • Send the request off to a file on the server
    • Notice that a parameter (q) is added to the URL (with the content of the input field)

    Requirement before start

    • A basic understanding of HTML, CSS, PHP, MySQL, and Javascript
    • A local or remote server with Apache and MySQL (either XAMPP or WAMP)
    • Code editor – Downloads | Notepad++

    For this article, I’m using XAMPP. On my local PC, I will first compile the script. To do this, I’ll need to link the AJAX form to a MySQL database that contains some test data.

    Ajax Live Data Search with jQuery PHP MySQL
    Ajax Live Data Search with jQuery PHP MySQL

    Result


    require ‘conn.php’;$query = mysqli_query($conn, “SELECT * FROM `blog` WHERE `title` LIKE ‘%$keyword%’ ORDER BY `title`”) or die(mysqli_error());while($fetch = mysqli_fetch_array($query)){?>



    }?>


    }?>

    There you have it we successfully created Simple Search Box using PHP. I hope that this simple tutorial helps you to what you are looking for. For more updates and tutorials just kindly visit this site.

    Enjoy Coding!

    AJAX Live Search

    The following example will demonstrate a live search, where you get search results while you type.

    Live search has many benefits compared to traditional searching:

    • Results are shown as you type
    • Results narrow as you continue typing
    • If results become too narrow, remove characters to see a broader result

    Search for a W3Schools page in the input field below:

    The results in the example above are found in an XML file (links.xml). To make this example small and simple, only six results are available.

    Create a Search Box & Pagination in PHP using DataTable.
    Create a Search Box & Pagination in PHP using DataTable.

    Database Setup

    After installing the XAMPP Control Panel, start Apache and MySQL.

    Now open the URL: https://localhost/phpmyadmin/ – Yours may be different.

    Now Click on “New”

    Create a database name ”Classmate” (or whatever you like to call it)

    The following query should be copied and pasted to construct the table (search), column names (Id, Name), and then enter fictitious data.


    CREATE TABLE search ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, Name VARCHAR(30) NOT NULL ); INSERT INTO `search` VALUES (1, 'Emily Anderson'), (2, 'Liam Johnson'), (3, 'Sophia Martinez'), (4, 'Ethan Thompson'), (5, 'Olivia Davis');

    PHP


    $servername


    "localhost"


    $username


    "root"


    $password


    ""


    $databasename


    "geeksforgeeks"


    $conn


    = mysqli_connect(


    $servername


    $username


    $password


    $databasename


    );


    if


    (!


    $conn


    ) {


    die


    "Connection failed: "


    . mysqli_connect_error());


    $query


    "SELECT Roll_No, Name FROM `Student Details`;"


    $result


    = mysqli_query(


    $conn


    $query


    );


    if


    (mysqli_num_rows(


    $result


    ) > 0) {


    while


    $row


    = mysqli_fetch_assoc(


    $result


    )) {


    echo


    "Roll No: "


    $row


    "Roll_No"


    " - Name: "


    $row


    "Name"


    ].


    ""


    else


    echo


    "0 results"


    $conn


    ->close();


    ?>

    Output:

    Roll No: 1 – Name: Ram
    Roll No: 2 – Name: Shyam
    Roll No: 3 – Name: Rohit
    Roll No: 4 – Name: Suresh

    PDO Approach:

    PHP Code:

    search bar using Php and MySQL
    search bar using Php and MySQL

    Setup Files

    The following files need to be created in the htdocs folder, which are categorically located at C:/xampp/htdocs:

    • search.php: This serves as the main file for the search engine, enabling user input and result display.
    • db.php: This file contains the database connection details.
    • ajax.php: This is the primary file responsible for generating AJAX requests to the server and retrieving results.
    • script.js: Contains JavaScript functions for executing AJAX requests.
    • style.css: Provides styling for the search engine.

    Creating Search Form and Related Files In this step,

    We will create the following files:

    Search.php

    Name the file search.php while creating. This is a main file of a search engine, where the user can view the result and input data. Put the code below into it by simply pasting it.


    <br /> Live Search using AJAX<br />






    Example:


    Emily Anderson, Liam Johnson, Sophia Martinez, Ethan Thompson, Olivia Davis




    db.php

    This file contains the necessary details for establishing a database connection. Create a file named “db.php” and insert the following code:

    ajax.php

    This file acts as the main source for generating AJAX requests to the server and retrieving the results. Make a file called “ajax.php” and put the following code in it:


    '; // Fetch the results from the database. while ($Result = MySQLi_fetch_array($ExecQuery)) { ?>

  • ")'>


  • script.js

    This file contains JavaScript functions that perform AJAX requests. Add the following code to the “script.js” file you just created:


    // Retrieve the value from "ajax.php". function fill(Value) { // Assign the value to the "search" div in "search.php". $('#search').val(Value); // Hide the "display" div in "search.php". $('#display').hide(); } $(document).ready(function() { // When a key is pressed in the "Search box" of "search.php", this function will be called. $("#search").keyup(function() { // Assign the search box value to a JavaScript variable named "name". var name = $('#search').val(); // Validate if "name" is empty. if (name == "") { // Assign an empty value to the "display" div in "search.php". $("#display").html(""); } // If the name is not empty. else { // Initiate an AJAX request. $.ajax({ // Set the AJAX type as "POST". type: "POST", // Send data to "ajax.php". url: "ajax.php", // Pass the value of "name" into the "search" variable. data: { search: name }, // If a result is found, this function will be called. success: function(html) { // Assign the result to the "display" div in "search.php". $("#display").html(html).show(); } }); } }); });

    style.css

    This file contains styling elements for the search engine. Add the following code to a file called “style.css“:


    a:hover { cursor: pointer; background-color: yellow; }

    1. The search engine is now ready for testing. To proceed, follow these steps:

    localhost:8080/search.php

    1. Enter some text in the search field to perform a search in the database.

    Note that as you type, the text will be sent to the script.js file, which will then forward the request to ajax.php. In ajax.php, a JavaScript function named “fill()” will process the fetched results and display them in the “display” div of the search.php file.

    Conclusion

    Congratulations! You have been successful in using PHP, MySQL, and AJAX to create a dynamic live search box. You now own a strong tool that can offer a flawless search experience to visitors to your website after completing this thorough guide. To make sure your website appears high on search engine result pages, keep in mind to regularly improve your content and track its performance.

    FAQs on Live Search Box

    Can I implement a live search box without using AJAX?

    While it’s possible to create a live search box using other technologies, AJAX is the recommended approach for its seamless and real-time data fetching capabilities.

    Do I need advanced programming skills to build a live search box?

    Basic knowledge of PHP, MySQL, HTML, CSS, and JavaScript is required. However, following the steps provided in this article will guide you through the process.

    Can I customize the appearance of the live search box to match my website’s design?

    Yes, you can customize the HTML and CSS of the live search box to ensure it aligns with your website’s branding and design.

    Is it possible to include additional search features, such as filters or sorting options?

    Absolutely! Once you have the core live search functionality implemented, you can expand upon it and add more advanced search features based on your specific requirements.

    Will the live search box work on mobile devices?

    Yes, by ensuring mobile responsiveness in your design and development process, the live search box will function seamlessly on all devices, including mobile phones and tablets.

    Database operations in PHP are a very crucial thing that is especially needed in CRUD (Create, Read, Update and Delete) operations.

    In this article, we will discuss the Read part i.e. data fetching from database.

    There are two ways to connect to a database using PHP. They are as follows.

    1. MySQLi (“i” stands for improved)
    2. PDO (PHP Data Objects)

    MySQLi vs PDO: Both the ways are really good but there is only one difference between the two methods, PDO can work on 12 different database systems whereas MySQLi works with MySQL databases only.

    Connecting to a Database:

    • MySQLi Object-Oriented

      $conn = new mysqli($servername, $username, $databasename)

    • MySQLi Procedural

      $conn = mysqli_connect($servername,
      $username, $password, $databasename);

    • PDO

      $conn = new PDO(“mysql:host=$servername;dbname=myDB”,
      $username, $password, $databasename);

    Executing Queries: After connecting to the database we need to run queries to fetch data. In Read operations, we will use only select queries to fetch data from the database.

    Close Connection: After the fetching is performed, you should close the connection to the database using the close() function.

    $conn->close();

    Sample Database

    Create Table in the database:

    CREATE TABLE `Student Details` (
    `Roll_No` int(11) NOT NULL,
    `Name` varchar(255) NOT NULL,
    `City` varchar(255) NOT NULL,
    `Age` int(11) NOT NULL,
    PRIMARY KEY (`Roll_No`)
    );

    Student Details

    MySQLi Object-Oriented approach:

    PHP Code:

    Result


    require ‘conn.php’;$query = mysqli_query($conn, “SELECT * FROM `blog` WHERE `title` LIKE ‘%$keyword%’ ORDER BY `title`”) or die(mysqli_error());while($fetch = mysqli_fetch_array($query)){?>



    }?>


    }?>



    This code contains the save query of the application. This code will save the data to the database server. To do that just copy and write this block of codes inside the text editor, then save it as

    save_content.php

    .


    require_once ‘conn.php’;if(ISSET($_POST[‘save’])){$title = addslashes($_POST[‘title’]);$content = addslashes($_POST[‘content’]);mysqli_query($conn, “INSERT INTO `blog` VALUES(”, ‘$title’, ‘$content’)”) or die(mysqli_error());header(‘location: index.php’);}?>

    This code contains the view content of the application. This script will display the search keyword content that have been inputted. To make these just follow and write the code below inside the text editor, then save it as

    get_blog.php

    .


    PHP – Simple Search Box


    Back


    require ‘conn.php’;if(ISSET($_REQUEST[‘id’])){$query = mysqli_query($conn, “SELECT * FROM `blog` WHERE `blog_id` = ‘$_REQUEST[id]'”) or die(mysqli_error());$fetch = mysqli_fetch_array($query);?>

    }?>


    This code contains the main function of the application. This code will find and search the inputted keyword to check if it exist in the database To do this just copy and write the code inside the text editor, then save it as

    search.php

    .


    if(ISSET($_POST[‘search’])){$keyword = $_POST[‘keyword’];?>

    Php : How To Search And Filter Data In Html Table Using Php And MySQL Database [ with source code ]
    Php : How To Search And Filter Data In Html Table Using Php And MySQL Database [ with source code ]

    PHP


    $servername


    "localhost"


    $username


    "root"


    $password


    ""


    $databasename


    "geeksforgeeks"


    $conn


    = mysqli_connect(


    $servername


    $username


    $password


    $databasename


    );


    if


    (!


    $conn


    ) {


    die


    "Connection failed: "


    . mysqli_connect_error());


    $query


    "SELECT Roll_No, Name, City FROM `Student Details` WHERE Age > 18;"


    try


    $conn


    new


    PDO(


    "mysql:host=$servername;dbname=$databasename"


    $username


    $password


    );


    $conn


    ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


    $stmt


    $conn


    ->prepare(


    $query


    );


    $stmt


    ->execute();


    $r


    $stmt


    ->setFetchMode(PDO::FETCH_ASSOC);


    $result


    $stmt


    ->fetchAll();


    foreach


    $result


    as


    $row


    echo


    "Roll No: "


    $row


    "Roll_No"


    ].


    " - Name: "


    $row


    "Name"


    ].


    " | City: "


    $row


    "City"


    ].


    ""


    catch


    (PDOException


    $e


    ) {


    echo


    "Error: "


    $e


    ->getMessage();


    $conn


    ->close();


    ?>

    Output:

    Roll No: 2 – Name: Shyam | City: Mumbai
    Roll No: 4 – Name: Suresh | City: Kolkata

    Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

    Last Updated :
    17 Mar, 2022

    Like Article

    Save Article

    Share your thoughts in the comments

    Please Login to comment…

    This tutorial will show you how to create a search engine that allows users to search the content on your website. To complete this tutorial you will require a database to store the search results. You should be able to create a database easily if you chose a hosting provider that offers access to cPanel, as recommended in our tutorial on registering your website.

    The search engine will draw results from a SQL database. This tutorial will assume your web hosting provider offers access to cPanel. Your view of cPanel will depend on which theme you are using. The screenshots for this tutorial are from cPanel in Paper Lantern mode. If your cPanel layout does not look like the screenshots below then you may need to change your theme to Paper Lantern theme by clicking the ‘Switch Theme’ button pictured below.

    Once in Paper Lantern mode, navigate to the section called ‘MySQL® Databases’.

    If you have not done so already, then we will need to create an SQL user profile to manage and access the SQL database. To do this, navigate to the Add New User section and enter the username and password you would like to use. Be sure to note these details down somewhere safe because you will need them later. Part of the username may already have been filled in in the light grey box. Include this part in your notes too because it forms part of the complete username.

    Next, navigate to the Create New Database section and create a database called search. Again, a preceding part of the database name may be auto-filled in the grey box.

    Once you have created the database, return to the main cPanel dashboard and navigate to the section called phpMyAdmin.

    We will use phpMyAdmin to manage the search engine database. First, we need to create a table to store the search engine results. To do this, navigate to the search database. The database should be empty, as shown below.

    Let’s create a new table. The table will be called Results and will comprise five columns, each containing a different item of information about the search results. To create the results table, click the SQL tab then copy and paste the following SQL code into the text box:


    CREATE TABLE Results ( ID int NOT NULL AUTO_INCREMENT, Title varchar(255), URL varchar(255), Description varchar(255), Preview varchar(255), PRIMARY KEY (ID) );

    The above SQL code creates a table called Results that comprises the following columns:

    Once you have pasted the SQL code into the text box, press the Go button to run the code and create the Results table. You should see a confirmation message that the table was successfully created.

    Let’s now add search results to the database. To do this, navigate to the Results table in phpMyAdmin and click the Insert tab, as shown below.

    Fill in each field with the details of the search result. You can leave the ID field blank because the database will automatically assign a unique ID value. In the below screenshot, the search result description is simply “Dragon’s blood tree” because we will use that as a test search term later to confirm the search engine works; however, when you are creating your database entries you might like to copy and paste large sections of text from the target webpage. Providing as much useful text as possible in the description field will help ensure the record is returned in response to the user’s search query.

    If you ever need to edit a database entry then you can do this by returning to the Results table and pressing the edit button for the record you would like to change.

    Search results will be displayed on a PHP (PHP: Hypertext Preprocessor) web page. PHP is a server-side scripting language, which allows you to perform actions on the server that your website is hosted on. The results of these actions can be displayed to the user. In this instance, we will use PHP to query the search database and retrieve relevant results that we can show to the user. You can add HTML code to PHP files and build web pages in the usual way, just with the added functionality of PHP.In your code editor, create a new PHP file and save it in your website’s root directory (the same directory as your website’s homepage) using the filename search.php. To begin, add the regular HTML code you would add to a typical web page. For example, you should define the head and body elements, as shown below:


    <br /> Search results<br />


    Next, we’ll write the PHP code that connects to the database. To do this, add the following code to the body element:

    In the above code, replace LOCALHOST, USERNAME, PASSWORD and DATABASE with the details of your database. You set up a username, password and database in the section on creating the search database so you should already have these details. For the localhost number, you can find this by navigating to the Remote MySQL® section of cPanel and noting down the access hosts number (an example of what this number will look like is circled in red below):

    Once the PHP file has connected to the database, we can retrieve the search results. To do this, replace the // Retrieve the search results here comment in the PHP script with the following code:


    if (isset($_GET['search'])) { $param = "%{$_GET['search']}%"; $query = mysqli_prepare($con, "SELECT * FROM Results WHERE Description LIKE ?"); mysqli_stmt_bind_param($query, "s", $param); mysqli_stmt_execute($query); $results = mysqli_stmt_get_result($query); $rows = mysqli_num_rows($results); mysqli_stmt_close($query); if ($rows > 0) { echo "

    PHP


    $servername


    "localhost"


    $username


    "root"


    $password


    ""


    $databasename


    "geeksforgeeks"


    $conn


    new


    mysqli(


    $servername


    $username


    $password


    $databasename


    );


    if


    $conn


    ->connect_error) {


    die


    "Connection failed: "


    $conn


    ->connect_error);


    $query


    "SELECT * FROM `Student Details`;"


    $result


    $conn


    ->query(


    $query


    );


    if


    $result


    ->num_rows > 0)


    while


    $row


    $result


    ->fetch_assoc())


    echo


    "Roll No: "


    $row


    "Roll_No"


    ].


    " - Name: "


    $row


    "Name"


    ].


    " | City: "


    $row


    "City"


    ].


    " | Age: "


    $row


    "Age"


    ].


    ""


    else


    echo


    "0 results"


    $conn


    ->close();


    ?>

    Output:

    Roll No: 1 - Name: Ram | City: Delhi | Age: 18
    Roll No: 2 - Name: Shyam | City: Mumbai | Age: 19
    Roll No: 3 - Name: Rohit | City: Chennai | Age: 18
    Roll No: 4 - Name: Suresh | City: Kolkata | Age: 20

    MySQLi Procedural approach:

    PHP Code:

    How to make Search box & filter data in HTML Table from Database in PHP MySQL | PHP Tutorials - 15
    How to make Search box & filter data in HTML Table from Database in PHP MySQL | PHP Tutorials - 15

    Requirement before start

    • A basic understanding of HTML, CSS, PHP, MySQL, and Javascript
    • A local or remote server with Apache and MySQL (either XAMPP or WAMP)
    • Code editor – Downloads | Notepad++

    For this article, I’m using XAMPP. On my local PC, I will first compile the script. To do this, I’ll need to link the AJAX form to a MySQL database that contains some test data.

    Database Setup

    After installing the XAMPP Control Panel, start Apache and MySQL.

    Now open the URL: https://localhost/phpmyadmin/ – Yours may be different.

    Now Click on “New”

    Create a database name ”Classmate” (or whatever you like to call it)

    The following query should be copied and pasted to construct the table (search), column names (Id, Name), and then enter fictitious data.


    CREATE TABLE search ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, Name VARCHAR(30) NOT NULL ); INSERT INTO `search` VALUES (1, 'Emily Anderson'), (2, 'Liam Johnson'), (3, 'Sophia Martinez'), (4, 'Ethan Thompson'), (5, 'Olivia Davis');

    AWARD winning goldfish breeder | Pearlscale goldfish facility tour | BREEDING setup
    AWARD winning goldfish breeder | Pearlscale goldfish facility tour | BREEDING setup

    No search queryPlease try your search again.

    "; } mysqli_close();

    The user’s search query will be appended to the web page URL. In the above code, we retrieve the search query using PHP’s GET command. If no search query is provided, then a message will be printed to the web page asking the user to submit their query again. Meanwhile, if the PHP code successfully retrieves the user’s search query, then it wraps the query string in percentage symbols (%). The percentage symbols indicate that one or more characters can appear before or after the user’s search query when we search the database for suitable matches. This step is important because it means search results will be returned even if the user only enters a fragment of an entries Description field in the Results database table.Next, we prepare the SQL query that will search the Records table for entries that contain the user’s search query somewhere in their description. It is important to never add PHP variables directly to the SQL query string because hackers can manipulate the variables using SQL injection and access your database. For this reason, the above code instead prepares the query then binds the user’s search query parameter later. Preparing and binding SQL queries introduces extra validation steps and ensures the SQL query has not been manipulated by hackers.If the user’s search query returns results from the database, then the PHP script will extract the information from each result and add it to the web page. Meanwhile, if no results are found then a message will advise the user accordingly.

    To begin styling the search results, it would be a good idea to add the following CSS code to your main.css stylesheet:


    .search_result { color: MidnightBlue; text-align: center; } .search_result a { color: RoyalBlue; }

    The above code styles the text colour and text alignment of the text and links in each search result.

    Now we’ve got our database and PHP script up-and-running, we can incorporate a search box into the web page. The HTML code for this search box is included below:

    The opening div tag should be assigned the class search-box for styling purposes. The opening (

    ) and closing (

    ) form tags create an HTML form that will allow the user to input their search query. Inside the opening form tag we declare action=”search.php” method=”get”. The action attribute specifies the destination of the file which will process the form data/search query, while the method attribute determines how the form data will be sent. The get method appends the form data to the URL and allows the search result to be bookmarked; however, this is not very secure. If you ever have a form that processes sensitive data then the post method is preferable because it appends the form data to the body of the HTTP request and not the URL, thereby keeping it hidden.The tag determines what data the user can enter into the form. In this case, the input data will be a search query and so we set the ‘type’ to text and ‘name’ to search. The ‘maxlength’ attribute specifies how long the search query can be and the ‘placeholder’ determines the message that will be displayed in the search box when it is empty. Adding ‘required’ to the end of the input element means that it is not possible to submit the form unless the input field contains a value.The

    This stylesheet gives you access to over a thousand icons that can enhance the look of your website. A full list of these icons can be found on the publisher’s website here. We will be using the search icon, which is depicted below.

    To style the search box, you could add the following code to your main.css stylesheet:


    .search-box { position: absolute; top: 40%; left: 22%; }

    The above code will position the search box in the centre of the web page. You can position the search box elsewhere if you prefer.


    .search-box button { height: 32px; width: 32px; margin-left: -5px; background: LightGrey; font-size: 17px; border: none; }

    The above code styles the search button. It defines the height and width of the button and sets the left margin to -5px. This margin value helps ensure the button appears beside the search box. Meanwhile, the background property determines what colour the button will be and the font size property sets how big the search icon will appear. You can set the ‘border’ property to none if you do not want your button to have a border.You can also style the search box:


    .search-box input[type=text] { height: 26px; font-size: 17px; width: 50vw; }

    The above code defines the height and width of the search box and the font size of the displayed text. Specifying a width with the units vw means the search box to vary in size depending on the width of the browser window. If you want a fixed search box size then use px units instead.And that’s it! Your search engine should now be fully up-and-running. If you have been following along with the previous tutorials then the search engine should look like this when we are typing in our search (e.g. Dragon’s blood tree)

    Once we hit enter we will be referred to the ‘search.php’ and the results of the search will be displayed. In this example, the result is a link to a webpage containing photos of rare trees (such as the Dragon’s blood tree!).

    If you would like to do more with your search engine then you may be interested in this tutorial on how to integrate the search box into a navigation bar.

    Want to build a powerful Live search box using PHP, MySQL, and Ajax?

    If yes! Then this guide will help you explore how to create a powerful live search.

    Our goal is to provide you with an itemized step-by-step guide so that you can create a Live search box for yourself, understand the technical aspects of building a live search feature, and also outrank other websites.

    The live search feature, or AJAX search, refers to the search engine beginning to display results as you type text into the input field. You can view search results without bringing up a display page, thanks to this feature . As a result, people may locate what they’re seeking more quickly.. The development of AJAX search uses JavaScript (jQuery), MySQL, PHP, and AJAX.

    Even Google, the most popular search implements the idea of Live search on its page:

    The PHP File

    The page on the server called by the JavaScript above is a PHP file called “livesearch.php”.

    The source code in “livesearch.php” searches an XML file for titles matching the search string and returns the result:

    $xmlDoc=new DOMDocument();

    $xmlDoc->load(“links.xml”);

    $x=$xmlDoc->getElementsByTagName(‘link’);

    //get the q parameter from URL

    $q=$_GET[“q”];

    //lookup all links from the xml file if length of q>0

    if (strlen($q)>0) {

    $hint=””;

    for($i=0; $i<($x->length); $i++) {

    $y=$x->item($i)->getElementsByTagName(‘title’);

    $z=$x->item($i)->getElementsByTagName(‘url’);

    if ($y->item(0)->nodeType==1) {

    //find a link matching the search text

    if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q)) {

    if ($hint==””) {

    $hint=”

    ” .

    $y->item(0)->childNodes->item(0)->nodeValue . “”;

    } else {

    $hint=$hint . ”

    ” .

    $y->item(0)->childNodes->item(0)->nodeValue . “”;

    // Set output to “no suggestion” if no hint was found

    // or to the correct values

    if ($hint==””) {

    $response=”no suggestion”;

    } else {

    $response=$hint;

    //output the response

    echo $response;

    ?>

    If there is any text sent from the JavaScript (strlen($q) > 0), the following happens:

    Bước 1 : Đầu tiên chúng ta mở lại file index.php đã được tạo ở Phần 1 và xây dựng cấu trúc HTML cho form tìm kiếm gồm một input và 2 nút submit là đủ. Do chúng ta phải truyền đối số vào url nên chúng ta đặt method của form bằng phương thức GET.

    Bước 2 : Xử lý tìm kiếm với lệnh LIKE trong MySQL. Tham khảo full đoạn code dưới đây nhé :

    Bước 3 : Chạy lại file index.php, chúng ta nhận được danh sách sinh viên ban đầu :

    Vào ô tìm kiếm, ví dụ ta sẽ tìm kiếm những bạn sinh năm 1998 rồi ấn nút Tìm thì chúng ta sẽ nhận đươc kết quả này:

    Còn ví dụ chúng ta tìm kiếm danh sách sinh viên có tên là Lan thì chúng sẽ trả về kết quả rỗng :

    Nguồn Devmaster Academy

    Thiết kế và lập trình Website PHP, Laravel chuyên nghiệp – FullStack
    Lập trình ứng dụng trên nền tảng android
    Lập trình Ứng dụng với Công nghệ ASP.NET Core MVC, WebAPI, ReactJS – FullStack
    Lập trình ứng dụng với WINDOWS FORM
    Lập trình ứng dụng với JAVA (FORM)
    Thiết kế và lập trình Ứng dụng với công nghệ Java (Java Framework springBoot, hibernate,…) – FullStack
    Thiết kế và lập trình website với công nghệ HTML5, CSS3, Javascript, Bootstrapt 4, Jquery
    Lập trình frontend với reacjs (Full)

    You can create an HTML form that allows you to search records in your MySQL Tables and print the results in a web browser.

    In these project we use LIKE and wildcards for the query so that users do not have to have an exact match for results to be provided.

    Simple Search Form Project

    search.html



    Search



    phpSearch.php



    connect_error){ die("Connection failed: ". $conn->connect_error); } $sql = "select * from students where name like '%$search%'"; $result = $conn->query($sql); if ($result->num_rows > 0){ while($row = $result->fetch_assoc() ){ echo $row["name"]." ".$row["age"]." ".$row["gender"].""; } } else { echo "0 records"; } $conn->close(); ?>

    Option Box Search Form Project

    searchoption.html



    Search Column:



    phpSearchOption.php



    connect_error){ die("Connection failed: ". $conn->connect_error); } $sql = "select * from students where $column like '%$search%'"; $result = $conn->query($sql); if ($result->num_rows > 0){ while($row = $result->fetch_assoc() ){ echo $row["name"]." ".$row["age"]." ".$row["gender"].""; } } else { echo "0 records"; } $conn->close(); ?>

    Sau khi đọc xong bài viết này bạn sẽ xây dựng được chức năng tìm kiếm đơn giản trong PHP. Truy vấn sẽ thực thi tìm kiếm các từ khóa giống như từ mà bạn đang tìm kiếm bằng cách sử dụng LIKE. Vậy cách thực hiện như thế nào hãy xem chi tiết bài này của mình.

    Công việc khá đơn giản bạn chỉ cần tạo ra một tập tin là

    search.php

    với nội dung như sau

    How to run PHP file on localhost XAMPP | open php file in browser
    How to run PHP file on localhost XAMPP | open php file in browser

    Keywords searched by users: search code in php

    Categories: Sưu tầm 47 Search Code In Php

    Coding A Php Search - Youtube
    Coding A Php Search – Youtube
    Search A Record From Database In Php Mysql
    Search A Record From Database In Php Mysql
    Search Bar Using Php And Mysql - Youtube
    Search Bar Using Php And Mysql – Youtube
    Creating A Simple Search Box Using Php | Sourcecodester
    Creating A Simple Search Box Using Php | Sourcecodester
    Search Pagination In Php
    Search Pagination In Php
    Mysql – Search Form With Html And Php – Eli The Computer Guy
    Mysql – Search Form With Html And Php – Eli The Computer Guy
    Php Tutorial: Make A Simple Search Engine Mysqli (1/2) | Simple Search Code  In Php With Demo - Youtube
    Php Tutorial: Make A Simple Search Engine Mysqli (1/2) | Simple Search Code In Php With Demo – Youtube
    Xây Dựng Chức Năng Tìm Kiếm Dữ Liệu Với Php Và Mysql (Phần 5) | Devmaster
    Xây Dựng Chức Năng Tìm Kiếm Dữ Liệu Với Php Và Mysql (Phần 5) | Devmaster
    How To Create Search Engine With Pagination Using Php & Mysql - Youtube
    How To Create Search Engine With Pagination Using Php & Mysql – Youtube
    Simple Search Using Php And Mysql - Owlcation
    Simple Search Using Php And Mysql – Owlcation

    See more here: kientrucannam.vn

    See more: https://kientrucannam.vn/vn/

    Tag:

    Trả lời

    Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *