0

I am going to import DatabaseConnector class in Controller class. DatabaseConnector class contains database connection queries. Both classes are different php file.

Here is my code.

DatabaseConnector:

class DatabaseConnector
{
    public $con;
    //function for getting connected to database
    public function getConnection()
    {
        $con=mysqli_connect("localhost","root","","abcd");
        // Check connection
        if (mysqli_connect_errno()) {
          echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }
        return $con;
    }
    public function closeConnection()
    {
        mysqli_close($con);
    }
}

Controller:

include "database_connector.php";
    $dc = new DatabaseConnector();
    $con = $dc->getConnection();
class Controller
{

    public function __construct(){

    }

    public function insertData()
    {

        $name = "Abcde";
        $sql = "insert into user_details values('".$name."')";
        mysql_query($con, $sql);
    }


}

Where i am wrong in this code. it shows me error on mysql_query($con,$sql): $con in undefined variable; and mysql_query() requires two parameters

Please help me.

1
  • 1
    Change mysql_query($con, $sql); to mysqli_query($con, $sql); you cannot mix MySQL APIs. It's not like rhum & coke. Add error reporting to the top of your file(s) error_reporting(E_ALL); ini_set('display_errors', 1); when in development. Commented May 19, 2014 at 6:25

1 Answer 1

1

Your $con is not in the class.

include "database_connector.php";
class Controller
{
    protected $con;

    public function __construct(){
        $dc = new DatabaseConnector();
        $this->con = $dc->getConnection();
    }

    public function insertData()
    {
        $name = "Abcde";
        $sql = "insert into user_details values('".$name."')";
        mysqli_query($this->con, $sql);
    }
}

I don't test the code, but this should work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.