PHP MySQL INSERT QUERY


In PHP, using MySQLi in procedural style to perform an INSERT query involves a few steps. Here’s a step-by-step explanation:

1. Establish a Database Connection

First, you need to connect to the MySQL database using mysqli_connect().

$conn= mysqli_connect('localhost', 'username','password', 'database');
if (!$conn){
die("Connection failed: "n . mysqli_connect_error());
}

2. Prepare the INSERT Query

Construct the SQL INSERT query string. For example, suppose you have a table named users with columns username and email, and you want to insert a new record:

$sql = "INSERT INTO users (username, email) VALUES ('john_doe', 'john@example.com')";

3. Execute the Query

Use mysqli_query() to execute the INSERT query.

if (mysqli_query($conn, $sql)){   
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

4. Close the Database Connection

After executing the query, close the connection using mysqli_close().

mysqli_close($conn);

Full Example

Here is a complete example that puts all the steps together:

<?php
// Step 1: Connect to the database
$conn = mysqli_connect('localhost', 'username', 'password', 'database'); // Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
} // Step 2: Prepare the INSERT query
$sql = "INSERT INTO users (username, email) VALUES ('john_doe', 'john@example.com')"; // Step 3: Execute the query
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
} // Step 4: Close the connection
mysqli_close($conn);
?>

Notes

  • Escaping Strings: To avoid SQL injection attacks, you should escape user input using mysqli_real_escape_string() before including it in your query.
  • Prepared Statements: For better security and to handle dynamic data more safely, consider using prepared statements with mysqli_prepare() and mysqli_stmt_bind_param().

Here’s an example using prepared statements:

// Step 1: Connect to the database
$conn = mysqli_connect('localhost', 'username', 'password', 'database'); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Step 2: Prepare the INSERT query $stmt = mysqli_prepare($conn, "INSERT INTO users (username, email) VALUES (?, ?)"); // Bind parameters mysqli_stmt_bind_param($stmt, "ss", $username, $email); // Set parameters and execute $username = 'john_doe'; $email = 'john@example.com'; mysqli_stmt_execute($stmt); echo "New record created successfully"; // Close the statement and connection mysqli_stmt_close($stmt); mysqli_close($conn);

Using prepared statements helps prevent SQL injection and is generally recommended for handling dynamic data.