Re: No Database Connection possible (mySQL)

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



David Robley wrote:
Aviation Coding wrote:

Hi all,

I am having problems with a connection to a mysql database.

I am using

----
function con()
{
mysql_connect("localhost","user","pass") or die(mysql_error());
mysql_select_db("tava") or die(mysql_error());
}
----

Now, when I call the _function_ (!)
----
con() or die("no con");
----
I get the "no con" output.

When I call the mysql_connect and mysql_select directly before executing a
query, I get some DB output. But that won't work when I am using the
function...

Any ideas would be greatly appreciated.

Cheers!

Chris

I think you need to return something from the function, like true if the
connection/select worked, false if not.



Cheers
You are correct.

function foo() {
 // does something
}

var_dump(foo()); // returns NULL

why? because you don't explicitly return anything. If you did, that'd be the return value. So if you did:
function bar() {
   // does something
   return true;
}

var_dump(bar()); // return true

Now, your script assumes a return-value:
baz() or somethingElse();
is an expression. This basically says:
if(!baz()) {
   somethingElse();
}

Now, return (implicitly) null will result in (trough lazy comparison) a false value (*null == false*, null !== false), which then triggers your die() condition. Returning a meaningful value will get rid of that.

Other than that, choose 1 of 2 techniques:
1. error out inside the function itself (like you do now)
OR
2. error out based on the return-value of the function (like you do now ASWELL)
don't combine 1 and 2, stick with either, but not both.

function con()
{
mysql_connect("localhost","user","pass") or die(mysql_error());
mysql_select_db("tava") or die(mysql_error());
}
con();

works. The following would work too:
function con()
{
$r = mysql_connect("localhost","user","pass");
if(!$r) {
   return false;
}
$r2 = mysql_select_db("tava");
if(!$r2) {
   return false;
}
return true;
}

con() or die('no conn');

would also work correctly. So, stick with either, don't mix em.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux