Get and insert Data into MySQL database using PHP with xampp on localhost

Get and insert Data into MySQL database using PHP with xampp on localhost

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Retrieving and Inserting Data into MySQL via PHP on XAMPP

You have successfully established a connection to your demo database using mysqli and executed a basic INSERT statement directly in your script. The code snippet provided demonstrates the core mechanics of connecting to a local server: defining credentials, instantiating the connection object, and running a raw SQL query. However, the transition from hardcoding values in PHP to capturing them from an HTML form introduces specific challenges regarding data flow and security.

When moving from static queries to dynamic form handling, the primary obstacle is often how PHP retrieves user input. In your current setup, the variables first_name, last_name, and email_address are hardcoded strings. To make this functional with a form, you must explicitly fetch these values from the $_POST or $_GET superglobals. If your HTML form uses the method="post" attribute, PHP expects data in the $_POST array. Accessing $_POST['first_name'] without checking if it exists first is a common pitfall that leads to undefined index notices, breaking the script before data insertion occurs.

Handling Form Input Safely

The most critical aspect of inserting dynamic data is validation and sanitization. Simply echoing the raw input or passing it directly to a SQL query without preparation invites security vulnerabilities like SQL Injection, though modern MySQL drivers handle basic escaping if you use prepared statements.

To implement this robustly, you should switch from direct string concatenation to prepared statements. This approach separates the SQL logic from the data, ensuring that user inputs are treated strictly as text rather than executable code. Here is how you would refactor the insertion logic to accept form data:

$username = 'root';
$password = '';
$db = 'demo';

$conn = new mysqli('localhost', $username, $password, $db) or die("unable to connect");

// Check for connection errors immediately
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Retrieve values from the form
$first_name = $_POST['first_name'] ?? '';
$last_name = $_POST['last_name'] ?? '';
$email_address = $_POST['email_address'] ?? '';

// Validate that fields are not empty
if (empty($first_name) || empty($last_name) || empty($email_address)) {
    echo "All fields are required.";
} else {
    $sql = "INSERT INTO persons (first_name, last_name, email_address) VALUES (?, ?, ?)";
    
    // Prepare the statement
    $stmt = $conn->prepare($sql);
    
    // Bind parameters: 's' stands for string
    $stmt->bind_param("sss", $first_name, $last_name, $email_address);
    
    if ($stmt->execute()) {
        echo "Data inserted successfully.";
    } else {
        echo "Error: " . $stmt->error;
    }
}

$conn->close();

This method ensures that even if a user attempts to inject malicious SQL code into the input fields, the database treats it as literal text. Additionally, always check $conn->connect_error or handle exceptions gracefully rather than using or die(), which halts execution abruptly and exposes stack traces in production environments.

Retrieving Data from MySQL

Once the insertion mechanism is stable, retrieving data follows a similar pattern but requires selecting the correct rows based on criteria. You can use SELECT statements combined with mysqli_query() or prepared statements for fetching as well.

$sql = "SELECT * FROM persons WHERE email_address = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $email_address);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "First Name: " . $row["first_name"] . ", ";
        echo "Last Name: " . $row["last_name"] . ", ";
        echo "Email: " . $row["email_address"];
    }
} else {
    echo "No records found.";
}

Moving Beyond Native PHP

While native PHP and mysqli are powerful tools for local development on XAMPP, they require managing database connections, security logic, and routing manually. As your application grows, this boilerplate code becomes harder to maintain. Many developers eventually seek a framework that abstracts these complexities, providing built-in support for migrations, ORM models, and secure request handling.

For those looking to scale their local XAMPP projects into production-ready applications, Laravel offers a robust ecosystem specifically designed to handle database interactions elegantly. LaravelCompany provides resources on leveraging Laravel's Eloquent ORM to simplify data retrieval and insertion further, allowing you to define relationships and queries in a fluent syntax that reduces the risk of errors associated with raw SQL strings.

Our network