How to insert data into mysql database using core php for beginners

biswajit panda
8 min readFeb 6, 2024
created a folder called crud_core inside htdocs folder of xampp

The htdocs folder serves as the root directory for the local web server. Any files or folders placed in this directory are directly accessible via the web browser.

When you create PHP files inside the htdocs folder, you can execute and test them through your web browser by navigating to http://localhost/your-file.php

inside my crud_core folder created a file called user.php

if you go to the link now http://localhost/crud_core/user.php

you can see the page content , make sure you start the xampp server

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Registration Form</title>
</head>
<body>

<h2>User Registration Form</h2>

<form action="process_registration.php" method="post">
<label for="name">Name:</label>
<input type="text" name="name" required>
<br>

<label for="dob">Date of Birth:</label>
<input type="date" name="dob" required>
<br>

<label for="gender">Gender:</label>
<select name="gender" required>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select>
<br>

<label for="blood_group">Blood Group:</label>
<select name="blood_group" required>
<option value="A+">A+</option>
<option value="A-">A-</option>
<option value="B+">B+</option>
<option value="B-">B-</option>
<option value="O+">O+</option>
<option value="O-">O-</option>
<option value="AB+">AB+</option>
<option value="AB-">AB-</option>
</select>
<br>

<label for="weight">Weight (kg):</label>
<input type="number" name="weight" required>
<br>

<label for="state">State:</label>
<input type="text" name="state" required>
<br>

<label for="age">Age:</label>
<input type="number" name="age" required>
<br>

<label for="contact">Contact:</label>
<input type="tel" name="contact" required>
<br>

<label for="email">Email:</label>
<input type="email" name="email" required>
<br>

<input type="submit" value="Register">
</form>

</body>
</html>

i have added multiple form fields here .

form action attribute:

  • The action attribute specifies the URL or file where the form data will be submitted for processing.
  • If the action attribute is not specified, the form data is submitted to the same page or URL that contains the form.
  • In the provided example, action="process_registration.php" indicates that when the user submits the form, the data will be sent to the process_registration.php script for further processing.

we will see this later , lets create the database first

after opening xampp , click on admin

click on new and write this

-- Create a new database named 'user_registration'
CREATE DATABASE IF NOT EXISTS user_registration;

-- Switch to the 'user_registration' database
USE user_registration;

-- Create a table named 'users' to store user registration data
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
dob DATE NOT NULL,
gender ENUM('male', 'female', 'other') NOT NULL,
blood_group VARCHAR(4) NOT NULL,
weight DECIMAL(5,2) NOT NULL,
state VARCHAR(255) NOT NULL,
age INT NOT NULL,
contact VARCHAR(15) NOT NULL,
email VARCHAR(255) NOT NULL
);

-- Add an index on the email column for quicker searches
CREATE UNIQUE INDEX idx_email ON users (email);

Yes, you can create a database and table manually using the XAMPP control panel and a MySQL administration tool like phpMyAdmin.

if you want create manually table also by writing this data manually

Create a new file called : connect.php

Once test gets completed you remove the else block which echo connection success msg

The connect.php file in this context is used to encapsulate the code responsible for establishing a connection to the MySQL database. It serves as a reusable and centralized place to manage your database connection details.

  1. Database Configuration:
  • Here, you define the configuration parameters for connecting to your MySQL database.

These parameters include:

  • $host: The hostname where your MySQL database server is running. In this case, it's set to "localhost," indicating that the database server is on the same machine.
  • $username: The MySQL username used to connect to the database server. It's set to "root" in this example, which is a common default for local development servers.
  • $password: The password associated with the MySQL username. It's set to an empty string ("") in this example, indicating no password is used. In production, you should use a strong, secure password.
  • $database: The name of the MySQL database you want to connect to. In this case, it's set to "user_registration."
  1. Create a Connection to the Database:
  • The mysqli class is used to create a new MySQLi object, representing the database connection.
  • The new mysqli($host, $username, $password, $database) line establishes a connection to the MySQL database using the provided configuration parameters.

Check the Connection:

  • The if statement checks if the connection was successful by evaluating $mysqli->connect_error. If there is an error (meaning the connection failed), the script terminates with an error message using die().
  • If the connection is successful, the else block is executed, and a success message is echoed: "Connected successfully to the database."
  • The set_charset("utf8") line sets the character set for the connection to UTF-8. This is important to ensure proper handling of characters from different languages and character sets. (optional)

Create a new file called : process_registration.php

<?php

include("connect.php");

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$name = mysqli_real_escape_string($mysqli, $_POST["name"]);
$dob = mysqli_real_escape_string($mysqli, $_POST["dob"]);
$gender = mysqli_real_escape_string($mysqli, $_POST["gender"]);
$blood_group = mysqli_real_escape_string($mysqli, $_POST["blood_group"]);
$weight = mysqli_real_escape_string($mysqli, $_POST["weight"]);
$state = mysqli_real_escape_string($mysqli, $_POST["state"]);
$age = mysqli_real_escape_string($mysqli, $_POST["age"]);
$contact = mysqli_real_escape_string($mysqli, $_POST["contact"]);
$email = mysqli_real_escape_string($mysqli, $_POST["email"]);

// Validate form data (you may want to add more validation)
if (empty($name) || empty($dob) || empty($gender) || empty($blood_group) || empty($weight) || empty($state) || empty($age) || empty($contact) || empty($email)) {
echo "All fields are required.";
} else {
// Insert data into the 'users' table
$sql = "INSERT INTO
users (name, dob, gender, blood_group, weight, state, age, contact, email)
VALUES ('$name', '$dob', '$gender', '$blood_group', '$weight', '$state', '$age', '$contact', '$email')";

if ($mysqli->query($sql) === TRUE) {
echo "Registration successful! Welcome, $name!";
} else {
echo "Error: " . $sql . "<br>" . $mysqli->error;
}
}
} else {

header("Location: user.php");
exit();
}

// Close the database connection
$mysqli->close();
?>

The process_registration.php script is responsible for handling the form submission from the user registration form (user.php). Let's break down the main functionalities and the purpose of each section in this script

  • In PHP, the include statement is used to bring the content of one PHP file into another. It's like taking the code from one file and putting it inside another file.
  • When we include a file using include, it's often because the included file contains useful functions, configurations, or connections that we want to use in the file where we include it.

connect.php File:

  • This file holds the code for connecting to the MySQL database. It includes information like the database host, username, password, and database name.
  • Instead of copying and pasting this database connection code into every PHP file that needs to connect to the database, we put it in a separate file (connect.php).
if ($_SERVER["REQUEST_METHOD"] == "POST") {

This condition checks if the script is being accessed through a POST request, indicating that the user has submitted the registration form.

// Retrieve and sanitize form data
$name = mysqli_real_escape_string($mysqli, $_POST["name"]);
$dob = mysqli_real_escape_string($mysqli, $_POST["dob"]);
$gender = mysqli_real_escape_string($mysqli, $_POST["gender"]);
$blood_group = mysqli_real_escape_string($mysqli, $_POST["blood_group"]);
$weight = mysqli_real_escape_string($mysqli, $_POST["weight"]);
$state = mysqli_real_escape_string($mysqli, $_POST["state"]);
$age = mysqli_real_escape_string($mysqli, $_POST["age"]);
$contact = mysqli_real_escape_string($mysqli, $_POST["contact"]);
$email = mysqli_real_escape_string($mysqli, $_POST["email"]);

mysqli_real_escape_string function to escape user input before inserting it into a MySQL database. This is a good practice to prevent SQL injection attacks.

In PHP, $_POST is a superglobal variable that is used to collect form data submitted in an HTTP POST request. When a form with the method set to "post" is submitted, the form data is sent in the body of the HTTP request, and PHP populates the $_POST superglobal array with the submitted data.

we can write like this also but not safe :

<?php
// Accessing form data submitted via POST
$name = $_POST['name']; //name is html field name
$dob = $_POST['dob']; //dob is html field dob


?>

we can write like this also but using
mysqli_real_escape_string is safe and secure

$_POST["name"] and $_POST["dob"] refer to the values submitted in an HTML form with input fields named "name" and "dob" and all

— — — — — — — — — —

// Validate form data (you may want to add more validation)
if (empty($name) || empty($dob) || empty($gender) || empty($blood_group) || empty($weight) || empty($state) || empty($age) || empty($contact) || empty($email)) {
echo "All fields are required.";
}
  1. The empty() function is used to check if a variable is considered empty. It returns true if the variable is empty, and false otherwise.
  2. The || (logical OR) operator is used to combine multiple conditions. If any of the conditions are true (i.e., any of the fields are empty), the entire expression evaluates to true.
  3. The if statement checks whether any of the specified fields are empty. If the condition evaluates to true, meaning at least one of the fields is empty, it executes the code block inside the curly braces.
  4. Inside the code block, it echoes the message “All fields are required.”

else block we written the mysql query :

// Insert data into the 'users' table
$sql = "INSERT INTO users (name, dob, gender, blood_group, weight, state, age, contact, email)
VALUES ('$name', '$dob', '$gender', '$blood_group', '$weight', '$state', '$age', '$contact', '$email')";

$sql Variable:

  • The $sql variable holds the SQL query string. This string contains an INSERT INTO statement, specifying the 'users' table and the columns into which data will be inserted.

Table Name:

  • ‘users’ is the name of the MySQL table where the data will be inserted. Presumably, this table is designed to store user information, given the column names such as ‘name’, ‘dob’, ‘gender’, etc.

Column Names:

  • The column names within the parentheses following INSERT INTO users correspond to the columns in the 'users' table. Each column is separated by a comma.

VALUES Clause:

  • The VALUES clause follows the column names and contains the actual values to be inserted into the respective columns. The values are provided as variables (e.g., $name, $dob, $gender) which should have been previously defined with the data received from the form.

— — — — — — — —

if ($mysqli->query($sql) === TRUE) {
echo "Registration successful! Welcome, $name!";
} else {
echo "Error: " . $sql . "<br>" . $mysqli->error;
}

This block checks if the SQL query was executed successfully. If successful, it echoes a success message with the user’s name. If there’s an error, it displays an error message along with the SQL query and the MySQL error.

you can go to xampp admin panel and check .

--

--

biswajit panda

biswajit is a curious programmer who loves solving complex problems creating intuitive software.he is skilled in various programming languages and framework.