Searching records in PHP

Searching records in PHP

In PHP, you can search for records in a database using the SELECT SQL statement. The SELECT statement retrieves one or more rows from a table, based on a specified condition.

Here’s an example of using the SELECT statement in PHP to search for records from a MySQL database:

// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

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

// Check the connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// Prepare the SQL statement
$sql = "SELECT * FROM users WHERE username = 'john'";

// Execute the SQL statement
$result = mysqli_query($conn, $sql);

// Check if any rows were returned
if (mysqli_num_rows($result) > 0) {
    // Loop through the rows and output the data
    while ($row = mysqli_fetch_assoc($result)) {
        echo "Name: " . $row["name"] . " - Email: " . $row["email

In this example, the SELECT statement searches the users table for records where the username column equals 'john'. The mysqli_query() function executes the SQL statement, and the mysqli_num_rows() function returns the number of rows returned by the query. The mysqli_fetch_assoc() function retrieves each row as an associative array, and the data is output using echo.

Note that the SELECT statement can be customized to search for specific columns or multiple conditions using logical operators such as AND and OR. Additionally, consider implementing input sanitization and validation to prevent SQL injection attacks.

Apply for PHP Certification!

https://www.vskills.in/certification/certified-php-developer

Back to Tutorials

Get industry recognized certification – Contact us

Menu