我正在尝试验证函数是否插入数据库并返回消息..
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;还是错误?
答案 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!";
}
希望这会对你有所帮助。