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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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