Page 1 of 1

Can I call mysql_connect in function?

Posted: Thu Aug 11, 2005 1:48 am
by goodmorningsky
I wrote following in db.php

Code: Select all

$user="root";
$password="1234";
$database="test";
function ExecuteNonquery($query){
	//try{ //php 5.0 or higher
		mysql_connect(localhost,$user,$password); //create connection
		//After you have connected to the database server you must then select the database you wish to use.
		//This must be a database to which your username has access. The following command:
		@mysql_select_db($database) or die( "Unable to select database"); // relate to a database
		mysql_query($query);
		echo $query;
		mysql_close();
		return true;
	//}catch(Exception $ex){
	//	echo 'Caught exception: ',  $ex->getMessage(), "\n";
	//	return false;
	//}
}

and I included the db.php in Test.php

and I called the function from Test.php

Code: Select all

$query = "INSERT INTO contacts VALUES ('','John','Smith','01234 567890','00112 334455','01234 567891','johnsmith@gowansnet.com','http://www.gowansnet.com')";
ExecuteNonquery($query);
But, It doesn't work.
When I put code toghter it works, but If I put the code in function,
it doesn't work...

What 's problem?


feyd | please use

Code: Select all

and

Code: Select all

where appropriate when posting.[/color]

Posted: Thu Aug 11, 2005 2:59 am
by feyd
your call from test.php is just setting a string. It never calls the function.

Posted: Sat Aug 13, 2005 1:38 am
by goodmorningsky
what does 'never call function' mean?
ExecuteNonquery($query); is calling function!!.

I'm new to PHP, please explain more...
thank you.

Posted: Sat Aug 13, 2005 3:36 am
by onion2k
mysql_connect(localhost,$user,$password);
Localhost is a string, so it should be in quotes.

$user and $password are not available within the function (they're defined outside of the scope), so you need to pass them in in the same way you're doing with $query.

Posted: Sat Aug 13, 2005 8:48 am
by feyd
the function call was scrolled offscreen at the time and was impossible to realize. So cool it.