0

I'm pretty new to SQL and php and I came across a rather unfamiliar code here. I got it from a Youtuber and it's basically a Login system using MySQLi.

User.php This is where I established the db connection and use functions for MySQLi queries.

<?php
class User{
    private $dbHost     = "localhost";
    private $dbUsername = "root";
    private $dbPassword = "";
    private $dbName     = "regilog";
    private $userTbl    = "users";

    public function __construct(){
        if(!isset($this->db)){
            // Connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
            if($conn->connect_error){
                die("Failed to connect with MySQL: " . $conn->connect_error);
            }else{
                $this->db = $conn;
            }
        }
    }

    /*
     * Returns rows from the database based on the conditions
     * @param string name of the table
     * @param array select, where, order_by, limit and return_type conditions
     */
    public function getRows($conditions = array()){
        $sql = 'SELECT ';
        $sql .= array_key_exists("select",$conditions)?$conditions['select']:'*';
        $sql .= ' FROM '.$this->userTbl;
        if(array_key_exists("where",$conditions)){
            $sql .= ' WHERE ';
            $i = 0;
            foreach($conditions['where'] as $key => $value){
                $pre = ($i > 0)?' AND ':'';
                $sql .= $pre.$key." = '".$value."'";
                $i++;
            }
        }

        if(array_key_exists("order_by",$conditions)){
            $sql .= ' ORDER BY '.$conditions['order_by']; 
        }

        if(array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
            $sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit']; 
        }elseif(!array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
            $sql .= ' LIMIT '.$conditions['limit']; 
        }

        $result = $this->db->query($sql);

        if(array_key_exists("return_type",$conditions) && $conditions['return_type'] != 'all'){
            switch($conditions['return_type']){
                case 'count':
                    $data = $result->num_rows;
                    break;
                case 'single':
                    $data = $result->fetch_assoc();
                    break;
                default:
                    $data = '';
            }
        }else{
            if($result->num_rows > 0){
                while($row = $result->fetch_assoc()){
                    $data[] = $row;
                }
            }
        }
        return !empty($data)?$data:false;
    }

    /*
     * Insert data into the database
     * @param string name of the table
     * @param array the data for inserting into the table
     */
    public function insert($data){
        if(!empty($data) && is_array($data)){
            $columns = '';
            $values  = '';
            $i = 0;
            if(!array_key_exists('created',$data)){
                $data['created'] = date("Y-m-d H:i:s");
            }
            if(!array_key_exists('modified',$data)){
                $data['modified'] = date("Y-m-d H:i:s");
            }
            foreach($data as $key=>$val){
                $pre = ($i > 0)?', ':'';
                $columns .= $pre.$key;
                $values  .= $pre."'".$val."'";
                $i++;
            }
            $query = "INSERT INTO ".$this->userTbl." (".$columns.") VALUES (".$values.")";
            $insert = $this->db->query($query);
            return $insert?$this->db->insert_id:false;
        }else{
            return false;
        }
    }


   }
?>

userAccount.php This is where I check for any error and where everything is processed.

    <?php
//start session
session_start();
//load and initialize user class
ob_start();
include 'user.php';
$user = new User();
if(isset($_POST['signupSubmit'])){
    //check whether user details are empty
    if(!empty($_POST['first_name'])  && !empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['confirm_password'])){
        //password and confirm password comparison
        if($_POST['password'] !== $_POST['confirm_password']){
            $sessData['status']['type'] = 'error';
            $sessData['status']['msg'] = 'Your passwords do not match.'; 
        }else{
            //check whether user exists in the database
            $prevCon['where'] = array('email'=>$_POST['email']);
            $prevCon['return_type'] = 'count';
            $prevUser = $user->getRows($prevCon);
            if($prevUser > 0){
                $sessData['status']['type'] = 'error';
                $sessData['status']['msg'] = ' email already exists, please use another email';
            }else{
                //insert user data in the database
                $userData = array(
                    'first_name' => $_POST['first_name'],
                    'last_name' => $_POST['last_name'],
                    'email' => $_POST['email'],
                    'password' => md5($_POST['password'])

                );
                $insert = $user->insert($userData);
                //set status based on data insert
                if($insert){
                    $sessData['status']['type'] = 'success';
                    $sessData['status']['msg'] = 'You have registered successfully.';
                }else{
                    $sessData['status']['type'] = 'error';
                    $sessData['status']['msg'] = 'A problem occurred,';

                }
            }
        }
    }else{
        $sessData['status']['type'] = 'error';
        $sessData['status']['msg'] = 'All fields are required.';
    }
    //store signup status into the session
    $_SESSION['sessData'] = $sessData;
    $redirectURL = ($sessData['status']['type'] == 'success')?'logs.php':'registration.php';
    //redirect to the home/registration page
    header("Location:".$redirectURL);
}elseif(isset($_POST['loginSubmit'])){
    //check whether login details are empty
    if(!empty($_POST['email']) && !empty($_POST['password'])){
         //get user data from user class
        $conditions['where'] = array(
            'email' => $_POST['email'],
            'password' => md5($_POST['password']),
            'status' => '1'
        );
        $conditions['return_type'] = 'single';
        $userData = $user->getRows($conditions);
        //set user data and status based on login credentials
        if($userData){
            $sessData['userLoggedIn'] = TRUE;
            $sessData['userID'] = $userData['id'];
            $sessData['status']['type'] = 'success';
            $sessData['status']['msg'] = 'Hello '.$userData['first_name'].'!';
        }else{
            $sessData['status']['type'] = 'error';
            $sessData['status']['msg'] = 'Wrong email or password, please try again.'; 
        }
    }else{
        $sessData['status']['type'] = 'error';
        $sessData['status']['msg'] = 'Enter your email and password.';  
    }
    //store login status into the session
    $_SESSION['sessData'] = $sessData;
    //redirect to the home page
    ob_end_flush();
    header("Location:logs.php");
}elseif(!empty($_REQUEST['logoutSubmit'])){
    //remove session data
    unset($_SESSION['sessData']);
    session_destroy();
    //store logout status into the ession
    $sessData['status']['type'] = 'success';
    $sessData['status']['msg'] = 'You have logout successfully from your account.';
    $_SESSION['sessData'] = $sessData;
    //redirect to the home page
    header("Location:index.php");
}else{
    //redirect to the home page
    header("Location:registration.php");
}
?>
Karen Page
  • 33
  • 6
  • 1
    the best way to look if you already got this username is to build a find / select with the username If output = 0, you don't have this username. If output = 1, you have this username. If output > 1, you have a lot of this username – sheplu Aug 05 '17 at 18:03
  • How would that look code wise? Sorry, I'm so new. – Karen Page Aug 05 '17 at 18:12
  • pretty much the same things you got with user check. On your seconde file you have `//check whether user exists in the database`. – sheplu Aug 05 '17 at 18:14
  • You know that you shouldn't ask a question twice on stackoverflow ? – Chrisstar Aug 05 '17 at 18:15
  • This is more 'advanced' PHP code and frankly it's a mess to look at when you are only beginning. You're running before you can even walk! However if you want to use that code and expand on it you could make a new function in the User class and follow [this](https://stackoverflow.com/questions/22252904/check-if-row-exists-with-mysql) to get a simple and relative example of how you can use mysqli. – MinistryOfChaps Aug 05 '17 at 18:15
  • @sheplu `SELECT * FROM users WHERE username = $username`? – Karen Page Aug 05 '17 at 18:21
  • Remember to sanitize your inputs! – Scott C Wilson Aug 05 '17 at 18:57
  • How do I do that? @ScottCWilson – Karen Page Aug 05 '17 at 19:01

1 Answers1

0

First, be sure you sanitize your inputs! Do not do something like this:

$userData = array(
    'first_name' => $_POST['first_name'],
    'last_name' => $_POST['last_name'],
    'email' => $_POST['email'],
    'password' => md5($_POST['password'])
);
$insert = $user->insert($userData);

You need to use PDO and do a parameterized query. I'll show you how in my answer to your first question, which was how to check if a username exists. Suppose you have:

$username = $_POST['username'];

To see if it exists,

$link = new mysqli('localhost', 'user', 'pass', 'database');
if ($stmt = mysqli_prepare($link, "SELECT * FROM table_name WHERE user_name=?")) {
    mysqli_stmt_bind_param($stmt, "s", $username);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_store_result($stmt);
    if ($stmt->num_rows > 0) { 
        // Userid exists
    }
    mysqli_stmt_free_result($stmt);
    mysqli_stmt_close($stmt);

}
Vadim
  • 1,916
  • 2
  • 19
  • 39
Scott C Wilson
  • 19,102
  • 10
  • 61
  • 83