试图获取mysqli的非对象属性

时间:2014-11-30 10:27:13

标签: php mysqli

我是mysqli面向对象程序的新手。 在这里,我创建了一个用于将数据插入数据库的php类:

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';
}
}
}

如果我在php页面中包含该类并尝试插入数据,则会显示以下错误消息:

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

第43行是:

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

2 个答案:

答案 0 :(得分:0)

在你的情况下

$result包含布尔值yes / no。

$this->con根据您的查询结果保存数据的数量。

我认为您需要将行改为

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

查看php手册以获取更多信息。

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

答案 1 :(得分:0)

您的解决方案已经完成。但是如果我使用SELECT语句使用相同的类:

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';
}
}
}

在这种情况下,我可以获得正确的行号。如果$ result包含boolean,那么在这种情况下它如何正确返回结果?