Jump to content

problem when runing a funciton


zoran

Recommended Posts

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. .

 

 

Link to comment
https://forums.phpfreaks.com/topic/179610-problem-when-runing-a-funciton/
Share on other sites

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.

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.