Sean Asbury
Sean Asbury

Reputation: 27

Mysql query and $con

$query = "SELECT id, firstname, lastname, username FROM users ORDER BY id desc";
$stmt = $con->prepare( $query );
$stmt->execute();

When I run the above code for my CRUD Single page Application I get a return on my webpage of:

"Notice: Undefined variable: con in C:\xampp\htdocs\contactlist\read.php on line 7

Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\contactlist\read.php on line 7"

How can I solve this?

Upvotes: 0

Views: 8741

Answers (3)

Gabriel L.
Gabriel L.

Reputation: 5014

This message :

Notice: Undefined variable: con in C:\xampp\htdocs\contactlist\read.php on line 7

It means that $con is not defined in your code. Did you do something like this before the preparation of your query as an example:

$con = new mysqli("example.com", "user", "password", "database");
if ($con->connect_errno) {
    echo "Connection failed to MySQL : (" . $con->connect_errno . ") " .    $con->connect_error;
}

Now, this error :

Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\contactlist\read.php on line 7"

means that you cannot call to a member function which is prepare if $con doesn't exist.

Upvotes: 2

steven
steven

Reputation: 4875

Using PDO your $con may be defined like this

class db {
    public static function dbFactory($host, $dbase, $user, $pass) {
        $pdo = new PDO("mysql:host=$host;dbname=$dbase", $user, $pass);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);        
        return $pdo;
    }
}
$con = db::dbFactory('localhost','mydbname','myusername','mypassword');

Upvotes: 0

immulatin
immulatin

Reputation: 2118

You need to create a database connection prior to running any SQL queries

$con = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

You can find a beginning to end example on the PHP doc here: http://php.net/manual/en/mysqli.prepare.php

Upvotes: 0

Related Questions