jraavis icon

PHP: Search by ID

jraavis | PRO | 04/12/20 05:46:13 PM UTC | 0 ⭐ | 955 👁️ | Never ⏰ | []
PHP |

1.63 KB

|

None

|

0 👍

/

0 👎

<?php
    /* These are usefull to show all errors */
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    /* /These are usefull to show all errors */
 
    $db_host = '127.0.0.1';
    $db_user = 'root';
    $db_pass = 'root';
    $db_name = 'college';
    $tb_name = 'students';
    $conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
    if($conn === false){
        die('Error while connecting:' . mysqli_connect_error());
    }
    $post = $_POST;
    $columns = array('id'=>'ID', 'first_name'=>'First Name', 'last_name'=>'Last Name', 'email'=>'E-Mail');
    if( isset($post) && isset($post['id']) && $post['id'] != '' ) {
        $sql_query = "SELECT * FROM $tb_name WHERE $id = '" . $post['id'] . "'";
        if($result = mysqli_query($conn, $sql_query)){
            if(mysqli_num_rows($result) > 0){
                echo "<table>";
                echo "<tr>";
                foreach($columns as $column) {
                    echo "<th>$column</th>";
                }
                echo "</tr>";
 
                while($row = mysqli_fetch_array($result)){
                    echo "<tr>";
                        echo "<td>" . $row['id'] . "</td>";
                        echo "<td>" . $row['first_name'] . "</td>";
                        echo "<td>" . $row['last_name'] . "</td>";
                        echo "<td>" . $row['email'] . "</td>";
                    echo "</tr>";
                }
                echo "</table>";
                mysqli_free_result($result);
            } else {
                echo "Sorry! No records found.";
            }
        } else {
            echo "Error while executing $sql_query. " . mysqli_error($conn);
        }
     
        // Close connection
        mysqli_close($conn);
    } else {
        echo "Sorry! Invalid ID entered/selected";
    }
    
?>

Comments