stockBoi
stockBoi

Reputation: 287

Trying to get property of non-object for mysqli

I am new to mysqli object oriented procedure. Here I have made a php class for inserting data into database:

class main{
private $con;

function __construct(){
$this->db_connect();
}

private function db_connect(){
  $this->con = new mysqli('localhost', 'user_name', 'password');
  if ($this->con->connect_error) {
     echo '<br />Failed to connect database! Please try again later';
  }else{
     echo '<br />Connected Successfully!';
  }
}

private function db_select($db){
    $this->con->select_db('prefix_'.$db);
}

public function post_data($value2,$value3,$value4,$value5,$value6){
$this->db_select('database_name');
$result = $this->con->query("INSERT INTO table_name (column2,column3,column4,column5,column6) VALUES('$value2','$value3','$value4','$value5','$value6')");
if($result->affected_rows>=1){
  echo 'Data inserted successfully';
}else{
  echo 'Data could not be inserted';
}
}
}

if I include the class in a php page and trying to insert data, then this error message is showing:

Trying to get property of non-object in C:\zpanel\hostdata\dir\public_html\folder\phppage.php on line 43

There Line 43 is:

if($result->affected_rows>=1){

Upvotes: 1

Views: 2901

Answers (2)

stockBoi
stockBoi

Reputation: 287

Your solution is worked. But If I use SELECT statement using the same class like this:

class main{
private $con;

function __construct(){
$this->db_connect();
}

private function db_connect(){
  $this->con = new mysqli('localhost', 'user_name', 'password');
  if ($this->con->connect_error) {
     echo '<br />Failed to connect database! Please try again later';
  }else{
     echo '<br />Connected Successfully!';
  }
}

private function db_select($db){
    $this->con->select_db('prefix_'.$db);
}

public function post_data($value2,$value3,$value4,$value5,$value6){
$this->db_select('database_name');
$result = $this->con->query("SELECT * FROM table_name");
if($result->num_rows>=1){
  echo 'Data found';
}else{
  echo 'Data could not be found';
}
}
}

In this case, I can get the correct row number. If $result contains boolean, then how it can return result correctly in this case?

Upvotes: 0

fortune
fortune

Reputation: 3372

In your case

$result contains a boolean value yes/no.

But $this->con holds the number of data based on your query result.

I think you need to change your line to

if($this->con->affected_rows>=1){

Check the php manual for more information.

http://php.net/manual/en/mysqli.affected-rows.php

Upvotes: 1

Related Questions