lancelot
lancelot

Reputation: 77

Cant find why my code started displaying Trying to get property of non-object suddenly

m sorry for posting this question..I have been stuck for a long time with this piece of code which suddenly started displaying Trying to get property of non-object notice..I added $email = !empty($email) ? "'$email'" : "NULL"; this line to my code for entering null values to my db when no data is entered in email column..Is that the reason M getting this notice..Because of this the query

$check =  $this->db->query($sql) ;
            $count_row = $check->num_rows;  

is failing and a user can register with a username or a email which was already used to register..I have put he functions as public and changed include_once to require_once..But still of no use..please help me.. m attaching the entire code..Kindly have a look

note:please dont mark it as duplicate as I have read all the possible related questions but found no use..

class.user.php

<?php 
    include "db_config.php";

    class User{

        public $db;
        public function __construct(){
            $this->db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);

            if(mysqli_connect_errno()) {

                echo "Error: Could not connect to database.";

            exit;

            }
        }

        /*** for registration process ***/
        public function reg_user($firstname,$lastname,$bloodgroup,$dob,$country,$state,$district,$city,$phonenumber,$secondnumber,$email,$username,$password,$activity){

            //$password = crypt($password);
            $password = md5($password);
            $email = !empty($email) ? "'$email'" : "NULL";
            $sql="SELECT * FROM users WHERE username='$username' OR email='$email'";

            //checking if the username or email is available in db
            $check =  $this->db->query($sql) ;
            $count_row = $check->num_rows;

            //if the username is not in db then insert to the table
            if ($count_row == 0){
                $sql1="INSERT INTO users SET firstname='$firstname',lastname='$lastname',bloodgroup='$bloodgroup',dob='$dob',
                country='$country',state='$state',district='$district',city='$city',phonenumber='$phonenumber',secondnumber='$secondnumber',
                email=$email,username='$username', password='$password',activity='$activity'";
                $result = mysqli_query($this->db,$sql1) or die(mysqli_connect_errno()."Data cannot inserted");
                return $result;
            }
            else { return false;}
        }
?>  

register.php

<?php

    require_once 'include/class.user.php';

    $user = new User();

    // Checking for user logged in or not
    /*if (!$user->get_session())
    {
       header("location:index.php");
    }*/
    if (isset($_REQUEST['submit'])){
        extract($_REQUEST);
        //$email = !empty($email) ? "'$email'" : "NULL";
        $register = $user->reg_user($firstname,$lastname,$bloodgroup,$dob,$country,$state,$district,$city,$phonenumber,$secondnumber,$email,$username,$password,$activity);
        if ($register) {
            // Registration Success
            echo 'Registration  successful <a href="login.php">Click here</a> to login';
        } else {
             //registration failed
             echo' registration failed,username or email already exists';       
             }
    }
?>  

The error is Trying to get property of non-object in D:\wamp\www\blood\include\class.user.php on line 29
And the line 29 is $count_row = $check->num_rows; in class.user.php Any help is appreciated..Thank you

edited piece I have removed the double ' as told by dave below...and that resulted in successful entries of null values into Db but when I try to enter a email value..It says data cannot be inserted..i.e., the error when The query sql1 of inserting values into db is failed in register.php

Upvotes: 0

Views: 270

Answers (1)

dave
dave

Reputation: 64657

Well, you have this:

$email = !empty($email) ? "'$email'" : "NULL";
$sql="SELECT * FROM users WHERE username='$username' OR email='$email'";

So, let's assume $email = "[email protected]"; $username = "whatever"

So you have

$email = !empty("[email protected]") ? "'[email protected]'" : "NULL";

And then you have

$sql="SELECT * FROM users WHERE username='whatever' OR email=''[email protected]''";

So, your query is

SELECT * FROM users WHERE username='whatever' OR email=''[email protected]''

The double ' makes it an invalid query, so it returns false when you run query($sql)

$count_row = (false)->num_rows;

will obviously throw an error.

I would change it to:

public function reg_user($firstname,$lastname,$bloodgroup,$dob,$country,$state,$district,$city,$phonenumber,$secondnumber,$email,$username,$password,$activity){
    $password = md5($password);
    $email = $email ?: null;
    $sql="SELECT * FROM users WHERE username=? OR email=?";
    //checking if the username or email is available in db
    $stmt = $this->db->prepare($sql);
    $stmt->bind_param('ss', $username, $email);
    $stmt->execute();
    //if the username is not in db then insert to the table
    if ($stmt->num_rows == 0) {
        $ref = new ReflectionMethod($this, 'reg_user');
        $columns = [];
        foreach($ref->getParameters() as $param) {
            $name = $param->name;
            $columns[$name] = &$$name;
        } 
        $sql= "INSERT INTO users 
                   (" . implode(",", array_keys($columns)) . ")
               VALUES
                   (" . str_repeat("?,", count($columns)) . ")";

        $stmt = $this->db->prepare($sql);
        call_user_func_array(array($stmt, "bind_param"), $columns);
        return $stmt->execute();
    }

Upvotes: 3

Related Questions