Democreous Posted February 9, 2007 Share Posted February 9, 2007 I'm currently trying to grasp the concept of OOP and classes, but I figure I should first get a grasp of creating functions before I step up to the plate. I have a function I want to create that allows me to connect to my database whenever I call it. So far I have bits and pieces of what I need to do to create and call the function. My non-working code is as follows... $HOST = 'xxxxxxx'; $USER = 'xxxxxxx'; $PASS = 'xxxxxxx'; $NAME = 'xxxxxxx'; $T = 'xxxxxxx'; function con($host, $user, $pass, $name, $t); { // CONNECT TO DB $con = mysql_connect($host, $user, $pass); if (!$con) { die("Error connecting to MySQL database!"); } mysql_select_db($t, $con); } } con($HOST,$USER,$PASS,$NAME,$T); // Call Function? Any suggestions on how I could get this to work and connect to my database? Link to comment https://forums.phpfreaks.com/topic/37692-solved-function-creation/ Share on other sites More sharing options...
trq Posted February 9, 2007 Share Posted February 9, 2007 That should work fine (except there should be no colon after your arguments), however, you may also won't to return the connection. Also, I prefer to have my function return true or false and then let the client code handle any errors. eg; <?php function con($host, $user, $pass, $name) { if (!$con = mysql_connect($host, $user, $pass)) { return false; } if (!mysql_select_db($name, $con)) { return false; } return $con; } $HOST = 'xxxxxxx'; $USER = 'xxxxxxx'; $PASS = 'xxxxxxx'; $NAME = 'xxxxxxx'; if ($conn = con($HOST,$USER,$PASS,$NAME)) { // connection success. } else { die("Error connecting to MySQL database!"); } Link to comment https://forums.phpfreaks.com/topic/37692-solved-function-creation/#findComment-180285 Share on other sites More sharing options...
hvle Posted February 9, 2007 Share Posted February 9, 2007 You need to post the whole class. Link to comment https://forums.phpfreaks.com/topic/37692-solved-function-creation/#findComment-180289 Share on other sites More sharing options...
artacus Posted February 9, 2007 Share Posted February 9, 2007 PHP is case sensitive so if you do that, its not going to work. $HOST = 'xxxxxxx'; $USER = 'xxxxxxx'; $PASS = 'xxxxxxx'; $NAME = 'xxxxxxx'; $T = 'xxxxxxx'; function con($host, $user, $pass, $name, $t); Link to comment https://forums.phpfreaks.com/topic/37692-solved-function-creation/#findComment-180293 Share on other sites More sharing options...
Democreous Posted February 9, 2007 Author Share Posted February 9, 2007 Thanks alot, got it working Link to comment https://forums.phpfreaks.com/topic/37692-solved-function-creation/#findComment-180332 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.