How to Build Secure User Registration and Data Storage with PHP
This guide shows how to implement a PHP function for user registration that validates input, hashes passwords, stores user details in a MySQL database, and a separate function for generic data storage, while highlighting key security considerations.
User Registration
The registerUser function accepts three parameters— $username, $password, and $email. It first checks that none are empty, returning false if validation fails. The password is then encrypted using password_hash with PASSWORD_DEFAULT. A MySQL connection is created via mysqli_connect('localhost','username','password','database'), and an INSERT statement adds the new user to the users table. The function returns true on successful insertion, otherwise false.
function registerUser($username, $password, $email) {
if (empty($username) || empty($password) || empty($email)) {
return false;
}
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$conn = mysqli_connect('localhost', 'username', 'password', 'database');
$sql = "INSERT INTO users (username, password, email) VALUES ('$username', '$hashedPassword', '$email')";
$result = mysqli_query($conn, $sql);
if ($result) {
return true;
} else {
return false;
}
}Data Storage
The storeData function takes a single argument $data. It opens a MySQL connection, builds an INSERT query for the data table, executes it, and returns true if the operation succeeds, otherwise false.
function storeData($data) {
$conn = mysqli_connect('localhost', 'username', 'password', 'database');
$sql = "INSERT INTO data (data) VALUES ('$data')";
$result = mysqli_query($conn, $sql);
if ($result) {
return true;
} else {
return false;
}
}Conclusion
These examples demonstrate that PHP’s built‑in functions make implementing user registration and generic data storage straightforward. In production code, developers should further address security (e.g., prepared statements to prevent SQL injection) and performance concerns, but mastering these basics provides a solid foundation for backend development.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
