dongyi7966 2019-03-28 06:06
浏览 23
已采纳

php数据库连接回显混淆以下代码

in my php i call database connection from other php but i got confuse here its not echo current php echo

this my db.php code

<?php
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);
class Database {
    private $con;
    public function connect (){
        include_once("constant.php");
        $this->con = new Mysqli(HOST,USER,PASS,DB);
        if ($this->con->connect_error) {
            echo"connect fails";
            //return $this->con;    
        }else{echo "connection success";}
        //return "DATABASE_CONNECTION_FAIL";

    }
}
$db = new Database();
$db->connect();
?>

and this my user.php code

<?php
/**
 * user class for account creation and login purpose
 */
class User {
    private $con;
    function __construct(){

        include_once("../database/db.php");  
        $db = new Database();
        $this->con = $db->connect();
        if($this->con) {
        echo "connect databases";
      }
    }


}
$obj = new User();
?>

in my browser i call user.php but i got echo as connection success connection success its repeat 2 time but in user.php echo not display

my expect echo is connect databases

enter image description here

  • 写回答

2条回答 默认 最新

  • douxian9706 2019-03-28 06:37
    关注

    This line in your user.php calls the connect() function in your Database class. This also echoes the first "connection success" string:

    $this->con = $db->connect();
    

    This line in your user.php calls again the connect() function in your Database class, and prints the second "connection success" string.

    if($this->con) { ... }
    

    These lines in your user.php does not work because connect() function does not return anything:

    if($this->con) {
      echo "connect databases";
    }
    

    You can replace your echoes in your Database class if-else block with return statements like this if you only want the "connect databases" string result:

    if ($this->con->connect_error) {
      return false;
    } else {
      return true;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?