Can you please tell me how to improve this code?
<?php
include 'configdb.php';
if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['email']) && !empty($_POST['password']))
{
$getUserData = getUserByEmail();
if (mysqli_stmt_num_rows($getUserData) > 0)
{
die(
'{
"status":"1",
"message":"Email Already Exists"
}'
);
}
else
{
insertUser();
die('{
"status":"0",
"message":"Registration Successful"
}');
}
}
function insertUser()
{
$email = $_POST['email'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$insertData = mysqli_prepare($GLOBALS['connection'], "INSERT INTO users (emailID, password, com_code) VALUES(?,?,?)");
if(false == $insertData)
{
handlePrepareStmtErrors("-1");
}
$bindParam = mysqli_stmt_bind_param($insertData, "sss", $email, $password, $com_code);
if(false == $bindParam)
{
handlePrepareStmtErrors("-2");
}
$executeStmt = mysqli_stmt_execute($insertData);
if(false == $executeStmt)
{
handlePrepareStmtErrors("-3");
}
}
function getUserByEmail()
{
$getUserData = mysqli_prepare($GLOBALS['connection'],"SELECT emailID FROM users WHERE emailID = ?");
if(false == $getUserData)
{
handlePrepareStmtErrors("-1");
}
$bindParam = mysqli_stmt_bind_param($getUserData,"s",$_POST['email']);
if(false == $bindParam)
{
handlePrepareStmtErrors("-2");
}
$executeStmt = mysqli_stmt_execute($getUserData);
if(false == $executeStmt)
{
handlePrepareStmtErrors("-3");
}
mysqli_stmt_store_result($getUserData);/*It Is Required To Get Number Of Rows By stmt_num_rows Method */
return $getUserData;
}
function handlePrepareStmtErrors($code)
{
switch((String)$code)
{
case "-1":
die('{
"status":"-1",
"message":"Statement prepare error"
}');
case "-2":
die('{
"status":"-1",
"message":"Parameter binding error"
}');
case "-3":
die('{
"status":"-1",
"message":"Statement execution error"
}');
}
}
?>
Things about which I am not sure:
- I read that MySQLi prepare statements will prevent SQL injections. Is there any possibility to hack my db by my design?
- I am planning to create a utils.php and will add
handlePrepareStmtErrors
function there. In that function, I am exiting the scripts if any errors are there. So only I am not usingbreak
statement there because it will not get executed. Is it right way? - I feel like my functions are not properly written, but it does what I want. I tried and registration is successful.