Jump to content

[SOLVED] Function Creation


Democreous

Recommended Posts

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

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!");
}

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.