pdo - Call to a member function prepare() on a non-object [duplicate]
$pdo
is undefined. You're not declaring it inside the function, and it isn't being passed in as an argument.
You need to either pass it in (good), or define it in the global namespace and make it available to your function by placing global $pdo
at the top (bad).
You can make a function of database connection in the same php page & call that function whenever you want. As,
public function connection()
{
$dbc = new PDO("mysql:host=localhost;dbname=chat","root","");
}
public function1()
{
this->connection();
// now you have the connection.. now, time for to do some query..
}
public function2()
{
this->connection();
// now do query stuffs..
}
Or simply you can simply write the database connection line in that page every time when you need it. As,
public function a()
{ // connecting DB for this function a only...
$dbc = new PDO("mysql:host=localhost;dbname=chat","root","");
// bla bla bla...
}
public function b()
{ // connecting DB for this function b only...
$dbc = new PDO("mysql:host=localhost;dbname=chat","root","");
// abra ke dabra... boom
}
The $pdo
object isn't in scope within your function.
@Anvd . I had the same problem but I did solve it by connecting the database in the same page not just to include the coonnecting page . It worked for me
<?php
try {
$pdo = new PDO('mysql:host=localhost;dbname=tish_database;charset=utf-8','root','');
} catch(PDOException $e){
echo 'Connection failed'.$e->getMessage();
}
?>
In regards the equivalent of mysql_num_rows in PDO is basically FETCH_NUM it return a index number of the selected row.