zoran Posted October 30, 2009 Share Posted October 30, 2009 I am trying to connect to database using a funciton in a functions.php <?php function connect_db_Blog (){ $con=mysql_connect("localhost","root",""); $db=mysql_select_db("blog",$con); } ?> which I then include with include ("scripts/php_functions.php"); but when I run a code with connect_db_Blog(); var_dump($db); if (!$db) { echo "sorry, cannot connect to database"; } else { here comes some code.. I get: sorry , cennot connect to database message. when I listen for $db with var_dump($db); I get int(0); instead of int(1) which is needed to proceed with the code. If I just try to connect to database without the include I dont get the error message i.e. . Quote Link to comment Share on other sites More sharing options...
Bricktop Posted October 30, 2009 Share Posted October 30, 2009 Hi zoran, The easiest way woul dbe to declare the $db variable as global after you run the connect function. For example: connect_db_Blog(); global $db; var_dump($db); if (!$db) { echo "sorry, cannot connect to database"; } else { here comes some code.. Hope this helps. Quote Link to comment Share on other sites More sharing options...
zoran Posted October 30, 2009 Author Share Posted October 30, 2009 I did <?php function connect_db_Blog (){ $con=mysql_connect("localhost","root",""); global $db; $db=mysql_select_db("blog",$con); } ?> and it sloved the problem, thanks Bricktop. Strangely , declaring $db with global $db=mysql_select_db("blog",$con); gave an error: Parse error: parse error, expecting `','' or `';'' in C:\wamp\www\nivodesign.com\scripts\php_functions.php on line 5 Quote Link to comment Share on other sites More sharing options...
Bricktop Posted October 30, 2009 Share Posted October 30, 2009 Yes, sorry I pasted the wrong code snippet, glad it's working now. The second line: global $db=mysql_select_db("blog",$con); Is the wrong syntax, it should be: global $db; mysql_select_db("blog",$con); Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.