0

Here is my code in database.php

    $db_host = "localhost";
    $db_username = "root";
    $db_pass = "";
    $db_name = "ss";
    $con = new PDO('mysql:host=localhost;dbname=app', $db_username, $db_pass);

In my class page

include_once "database.php";
class article_fun
{
  public function myfun()
    {
     $sqlcreate = $con->query("selct query")
     }
}

How do we do we use $con->query("select query") getting an error Undefined variable: con how to fix this?

John Conde
  • 217,595
  • 99
  • 455
  • 496
Your Friend
  • 1,119
  • 3
  • 12
  • 27

5 Answers5

1

Pass$con as a parameter to article_fun::myFun()

class article_fun
{
  public function myfun($con)
  {
     $sqlcreate = $con->query("selct query")
  }
}

FYI, in PHP it is convention to start class names with a capital letter and use camelCase:

class ArticleFun
John Conde
  • 217,595
  • 99
  • 455
  • 496
1

Your created variables are outside of the function scope.
So you can't access variables outside a function from inside the function.
Try to use the magic function __construct()
Like this:

class article_fun{
  private $_con;

  public function __construct( $con ){
    $this -> _con = $con;
  };

  public function myfun(){
    $sqlcreate = $this -> _con->query("selct query")
  }
}

Now you just have to pass the $convar to the Class like so:

$article_fun = new article_fun( $con );
Octfx
  • 691
  • 1
  • 7
  • 18
1

use this

class article_fun
{
private $con;
public function __construct($con){
$this->con=$con;
}
  public function myfun()
    {
     $sqlcreate = $this->con->query("selct query")
     }
}

call this

include_once "database.php";

new article_fun($con);

or use this

class article_fun
    {
    private $con;
    public function __construct(){
    $db_host = "localhost";
    $db_username = "root";
    $db_pass = "";
    $db_name = "ss";
    $this->con = new PDO('mysql:host=localhost;dbname=app', $db_username, $db_pass);
    }
      public function myfun()
        {
         $sqlcreate = $this->con->query("selct query")
         }
    }
Harutyun Abgaryan
  • 2,013
  • 1
  • 12
  • 15
0
class article_fun
{
  public function myfun()
  {
     global $con;
     $sqlcreate = $con->query("select query")
  }
}

Your variable is definied in the global context and you try to use it in a method of a class.

andreashager
  • 667
  • 3
  • 9
-1

Use global variable

  $GLOBALS['con'] = $yourConnection;

Check this link for answer How to declare a global variable in php?

Community
  • 1
  • 1
Hassan Shifaz
  • 45
  • 2
  • 7