简体   繁体   中英

PHP mysql error Call to undefined function mysql_connect()

I have been trying to spot the problem in the

<?php
require_once("config.php");

class MYSQLDatabase{

    private $connection;
// open the connection as soon as object is created
function __construct(){

    $this->open_connection();
}

public function open_connection(){

    $this->connection = mysql_connect("DB_SERVER", "DB_USER", "DB_PASS");

    if(!$this->connection){
        die("Database failed " . mysql_error());
    }else{
     $db_select = mysql_select_db(DB_NAME, $this->connection);   
        if(!$db_select){
            die("Database connection failed " . mysql_error());
        }
    }
}

    public function close_connection(){
        if(isset($this->connection)){
            mysql_close($this->connection);
            unset($this->connection);
        }
    }

    public function query($sql){
        $result = mysql_query($sql, $this->connection);
        $this->confirm_query($result);
        return $result;
    }



    private function confirm_query($result){
        if(!result){
            die("Database query failed: " . mysql_error());
        }
    }
}
$database = new MYSQLDatabase();

?>

When I go to the index.php file and test the class with the code below i get the following error:
This page isn't working

localhost is currently unable to handle this request. HTTP ERROR 500.

require_once("../includes/database.php");
if(isset($database)){
    echo "true";
}else{
    echo "false";
}

As I have just mentioned in my comment mysql extension is deleted from PHP 7 as PHP manual is saying here mysql is deleted from php 7 so that's why you are getting and error undefined function mysql

Use mysqli which is mysql improved version. here is an example if you don't know how to use it.

<?php
 // no need fo mysqli_select_db 
$con = mysqli_connect("localhost","my_user","my_password","my_db");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>

For more example check out W3schools

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM