PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Moderator: General Moderators
anarkhos
Forum Newbie
Posts: 8 Joined: Tue Jul 10, 2007 3:48 pm
Post
by anarkhos » Tue Jul 10, 2007 6:59 pm
I know I can disable Notice's from within my php.ini, but I want to resolve this issue with better code.
index.php:
Code: Select all
<?php
require_once("lib.php");
// connect and select a database
dbconnect();
// assign passed variables
// discover current category
if(!isset($dbh)) $dbh = $_REQUEST['dbh'];
else die("Error: dbh not available");
?>
lib.php:
Code: Select all
<?php
// connect and select a database
function dbconnect()
{ if (!(isset($dbh)))
{ if ($dbh = mysql_connect('localhost', 'root', ''))
mysql_select_db('new', $dbh);
else
echo "<p>ERROR: Connection failed</p>";
}
}
?>
My error message:
Notice: Undefined index: dbh in /var/www/html/test/index.php on line 12
feyd
Neighborhood Spidermoddy
Posts: 31559 Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA
Post
by feyd » Tue Jul 10, 2007 7:26 pm
anarkhos wrote: I know I can disable Notice's from within my php.ini, but I want to resolve this issue with better code.
Great!
Notice: Undefined index: dbh in /var/www/html/test/index.php on line 12
The error is coming from $_REQUEST['dbh'], which isn't set.
$dbh is apparently supposed to be set by dbconnect(), however the function does not return anything so no variable could be set.
anarkhos
Forum Newbie
Posts: 8 Joined: Tue Jul 10, 2007 3:48 pm
Post
by anarkhos » Tue Jul 10, 2007 7:47 pm
ok, resolved it, thank you... A final thought, how could I pass this variable $dbh without 'return' or '_REQUEST', which seems to give Notices everytime?
Code: Select all
<?php
require_once("lib.php");
// connect and select a database
$dbh = dbconnect();
?>
<?php
// connect and select a database
function dbconnect()
{ if (!(isset($dbh)))
{ if ($dbh = mysql_connect('localhost', 'root', ''))
mysql_select_db('new', $dbh);
else
echo "<p>ERROR: Connection failed</p>";
}
return $dbh;
}
?>
feyd
Neighborhood Spidermoddy
Posts: 31559 Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA
Post
by feyd » Tue Jul 10, 2007 9:00 pm
$dbh won't ever be set when dbconnect() is called, so it will attempt to create a new connection, always. The return should be just fine.