Can I call mysql_connect in function?

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
goodmorningsky
Forum Newbie
Posts: 11
Joined: Thu Aug 11, 2005 12:40 am

Can I call mysql_connect in function?

Post 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]
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

your call from test.php is just setting a string. It never calls the function.
goodmorningsky
Forum Newbie
Posts: 11
Joined: Thu Aug 11, 2005 12:40 am

Post by goodmorningsky »

what does 'never call function' mean?
ExecuteNonquery($query); is calling function!!.

I'm new to PHP, please explain more...
thank you.
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post 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.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

the function call was scrolled offscreen at the time and was impossible to realize. So cool it.
Post Reply