验证对象类

时间:2018-06-01 10:11:19

标签: php class

我正在尝试验证函数是否插入数据库并返回消息..

class.php

<?php 
class Database {
    var $host="localhost";
    var $user="root";
    var $pass="";
    var $db="vjezba";

    public function spajanje() {
        $con=mysqli_connect($this->host,$this->user,$this->pass,$this->db); 
        return $con;
    }
    public function napravi_insert($imeTablice,$ime,$prezime) {
        $conn=$this->spajanje();
        mysqli_query($conn,"insert into $imeTablice values('','".$ime."','".$prezime."')");
    }
}

的index.php

    <?php 
    include "klase.php";

    $radnja = new Database();
    //use extract method so no need to call $_POST again and again
    extract($_POST);

    if(isset($save)) {
        $imeTablice = "admin2";
        $radnja->napravi_insert($imeTablice,$ime,$prezime);
        //echo "Done!";

/* I am trying to make something like this */
        if($radnja->napravi_insert == TRUE) {
            echo "Done!";
        } else {
            echo "Error!";
        }
/* // / / / // */

    }

如何将对象变为变量并测试它是否成功&#34;成功&#34;还是错误?

2 个答案:

答案 0 :(得分:1)

您需要返回msqli_query函数的结果:

public function napravi_insert($imeTablice,$ime,$prezime) {
    $conn=$this->spajanje();
    $insert_state = mysqli_query($conn,"insert into $imeTablice values('','".$ime."','".$prezime."')");
    return $insert_state !== false;
}

所以你的代码如下所示:

<强> class.php

<?php 
class Database {
    private $host = "localhost";
    private $user = "root";
    private $pass = "";
    private $db = "vjezba";

    public function spajanje() {
        return mysqli_connect($this->host, $this->user, $this->pass, $this->db);
    }

    public function napravi_insert($imeTablice, $ime, $prezime) {
        $conn = $this->spajanje();
        $insert_state = mysqli_query($conn, "INSERT INTO $imeTablice VALUES ('','".$ime."','".$prezime."')");
        return $insert_state !== false;
    }
}

<强>的index.php

include "klase.php";

$radnja = new Database();

//use extract method so no need to call $_POST again and again
extract($_POST);

if(isset($save)) {
    $imeTablice = "admin2";

    if($radnja->napravi_insert($imeTablice, $ime, $prezime) === true) {
        echo "Done!";
    } else {
        echo "Error!";
    }
}

答案 1 :(得分:1)

首先从napravi_insert方法

返回查询状态
public function napravi_insert($imeTablice,$ime,$prezime) {
    $conn=$this->spajanje();
    return mysqli_query($conn,"insert into $imeTablice values('','".$ime."','".$prezime."')");
}

然后比较napravi_insert方法的返回值

$insert_status = $radnja->napravi_insert($imeTablice,$ime,$prezime);
if($insert_status == TRUE) {
    echo "Done!";
} else {
   echo "Error!";
}

希望这会对你有所帮助。