Ensure your servername, username and password are correct
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully"; // this is only for testing purposes and can be removed
?>
At the start of every new PHP file in your project that requires connection to the SQL database include this line of code at the top of your code.
<?php
include('connect.php');
?>
We learnt about insert statements in the SQL Section. In this example we insert static values into the database.
mysqli_query($conn, $sql);
This line of code executes the SQL query to the selected DB
//insert statement into a SQL Table
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
process.php - This file is run when the form is submitted from another page
<?php
include ('connect.php');
//get values from form array. You need to reference name of form input elements in square brackets
//You can use $_REQUEST as well
$first = $_POST['first'];
$last = $_POST['last'];
$email = $_POST['email'];
//insert statement into a SQL Table using variables collected from form
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('$first', '$last', '$email')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>