PHP Code How To Search Data In MySQL Database By Id Using PDO

Php Code To Search Data In Mysql Database Table And Dispaly Results In Inputs Using PDO .


________________________________________________________

In this Php Tutorial we will Learn How To Find Data In MySQL Database Table By Id And Show The Results In Form Inputs In Php  using  PDO .
I Use In This Tutorial:
- NetBeans IDE .
- XAMPP .
- PhpMyAdmin .


 




Php Source Code:


<?php

// php search data in mysql database using PDO
// set data in input text

$id = "";
$fname = "";
$lname = "";
$age = "";

if(isset($_POST['Find']))
{
        // connect to mysql
    try {
        $pdoConnect = new PDO("mysql:host=localhost;dbname=test_db","root","");
    } catch (PDOException $exc) {
        echo $exc->getMessage();
        exit();
    }
    
    // id to search
    $id = $_POST['id'];
    
     // mysql search query
    $pdoQuery = "SELECT * FROM users WHERE id = :id";
    
    $pdoResult = $pdoConnect->prepare($pdoQuery);
    
    //set your id to the query id
    $pdoExec = $pdoResult->execute(array(":id"=>$id));
    
    if($pdoExec)
    {
            // if id exist 
            // show data in inputs
        if($pdoResult->rowCount()>0)
        {
            foreach($pdoResult as $row)
            {
                $id = $row['id'];
                $fname = $row['fname'];
                $lname = $row['lname'];
                $age = $row['age'];
            }
        }
            // if the id not exist
            // show a message and clear inputs
        else{
            echo 'No Data With This ID';
        }
    }else{
        echo 'ERROR Data Not Inserted';
    }
}


?>

<!DOCTYPE html>

<html>

    <head>

        <title> PHP SEARCH DATA USING PDO </title>

        <meta charset="UTF-8">

        <meta name="viewport" content="width=device-width, initial-scale=1.0">

    </head>

    <body>

        <form action="php_search_in_mysql_database_using_pdo.php" method="post">

            ID To Search : <input type="text" name="id" value="<?php echo $id;?>"><br><br>

            First Name : <input type="text" name="fname" value="<?php echo $fname;?>"><br><br>

            Last Name : <input type="text" name="lname" value="<?php echo $lname;?>"><br><br>

            Age : <input type="text" name="age" value="<?php echo $age;?>"><br><br>

            <input type="submit" name="Find" value="Find Data">

        </form>
    
    </body>

</html>



///////////////OUTPUT:



                     
php search mysql pdo
Php Search




Share this

Related Posts

Previous
Next Post »

3 comments

comments
17 août 2016 à 17:02 delete

Thank you very much man i really appreciate every single tutorial you do

Reply
avatar
Anonyme
30 janvier 2019 à 22:08 delete

how to search multiple data? i want to search range of budget do you have any code to do?

Reply
avatar
Anonyme
27 février 2020 à 23:25 delete

merci pour ce tuto

Reply
avatar