I have a database connection PHP file which has a lot of queries to the database. Here are 3 of the functions that I am using:
public function deleteAccount($token)
{
$sql1 =
"DELETE FROM $this->table_user
WHERE $this->key_token = ?;";
$stmt1 = $this->connection->prepare($sql1);
$stmt1->bind_param("s", $token);
$stmt1->execute();
$result = $stmt1->affected_rows;
$stmt1->close();
return ($result >= 1);
}
public function getAccountDetails($token)
{
$sql1 =
"SELECT $this->key_name, $this->key_username, $this->key_email
FROM $this->table_user
WHERE $this->key_token = ?;";
$stmt1 = $this->connection->prepare($sql1);
$stmt1->bind_param("s", $token);
$stmt1->execute();
$stmt1->bind_result($name, $username, $email);
$stmt1->fetch();
$stmt1->close();
return
array(
"name" => $name,
"username" => $username,
"email" => $email
);
}
public function resetPassword($password, $hash, $email)
{
$sql1 =
"UPDATE $this->table_user
SET $this->key_hash = ?
WHERE $this->key_email = ? AND $this->key_passwordhash = ?;";
$stmt1 = $this->connection->prepare($sql1);
$passhash = password_hash($password, $this->algorithm);
$stmt1->bind_param("sss", $passhash, $email, $hash);
$stmt1->execute();
$result = ($stmt1->affected_rows == 1);
$stmt1->close();
return $result;
}
To me this seems like a lot of code duplication and I find myself doing a lot of copying and pasting which is a big sign that it is very duplicated but I am struggling to see how I can refactor this code so that for every sql query I perform it does not require so many lines of code.