I have a function called: table()
.
I can't connect to the database by PDO if I've written the PDO connection outside of the function, like this:
include_once("server.inc");
$connect = new PDO('mysql:host='.$servername.'; dbname='.$db.';charset=utf8' , $username, $password);
function table()
{
$sql="select * FROM d1" ;
$result = $connect->query($sql) ;
foreach ($result as $rows )
{
echo $rows["Course_name"] . "<br/>" ;
}
}
echo table() ;
This code does not work and gives these errors:
Notice: Undefined variable: connect
Fatal error: Call to a member function query() on a non-object
Now if I use the code like this:
function table()
{
include_once("server.inc");
$connect = new PDO('mysql:host='.$servername.'; dbname='.$db.';charset=utf8' , $username, $password);
$sql="select * FROM d1" ;
$result = $connect->query($sql) ;
foreach ($result as $rows )
{
echo $rows["Course_name"] . "<br/>" ;
}
}
echo table() ;
everything will be alright, but another problem will happen -- I can only use function table() once! If I use it a second time, this error will happen:
Notice: Undefined variable: servername
Notice: Undefined variable: db
Notice: Undefined variable: username
Notice: Undefined variable: password
Warning: Invalid argument supplied for foreach()
What shall I do to use my function more than once without errors?
You can inject the PDO instance to the function:
include_once("server.inc");
$connect = new PDO('mysql:host='.$servername.'; dbname='.$db.';charset=utf8' , $username, $password);
function table($connect)
{
$sql="select * FROM d1" ;
$result = $connect->query($sql) ;
foreach ($result as $rows )
{
echo $rows["Course_name"] . "<br/>" ;
}
}
//echo table() ;
// Thanks barmar, missed the param before editing!
table($connect); // there's no need to echo the function as it does not return any value,
// the function does the echoing
Oh, and you should read the scoping of variables, and also the include vs. include_once