954,580 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Connect to DB through function

Hi. I'm trying to create a function which connects to a database, and then displays rows in it. I'm trying to use a function to connect, but it's not working. Here's my first code:

<?php

	define("SERVER", "mysql.example.com");

	define("USERNAME", "username");

	define("PASSWORD", "********");

	define("DATABASE", "db");


	function displayFunction() {
	
		$dbc = @mysqli_connect(SERVER, USERNAME, PASSWORD, DATABASE);
		
		$query = "SELECT * FROM table";
		
		$result = @mysqli_query($dbc, $query);
		
		while($row = @mysqli_fetch_array($result)) {
		
			return $row['row'];
			
		}
		
	}
	
	echo displayFunction();
	
?>

That works. However this code:

<?php

	define("SERVER", "mysql.example.com");

	define("USERNAME", "username");

	define("PASSWORD", "********");

	define("DATABASE", "db");

	function connect() {
		
		$dbc = @mysqli_connect(SERVER, USERNAME, PASSWORD, DATABASE);
			
		if(!$dbc) {
				
			return false;

		}

		else {

			return true;

		}

	}
	

	function displayFunction() {
	
		if(!connect()) {
			
			return false;

		}

		else {
		
			$query = "SELECT * FROM table";
		
			$result = @mysqli_query($dbc, $query);
		
			while($row = @mysqli_fetch_array($result)) {
		
				return $row['row'];
			
			}
		
		}

	}
	
	echo displayFunction();
	
?>


doesn't work.

Can anyone help me?

Thanks

calebcook
Junior Poster in Training
66 posts since Jun 2011
Reputation Points: 10
Solved Threads: 4
 

I don't think $dbc can be passed like this as it's not global. Dunno though.
That's the prob with mysqli - have to use the blasted connection var!

Perhaps using PDO would help?

diafol
Rhod Gilbert Fan (ardav)
Moderator
7,792 posts since Oct 2006
Reputation Points: 1,170
Solved Threads: 1,080
 

The scope of $dbc is local to connect() so displayFunction() cannot "see" it.

The best way would be to have connect() return either the connection ID or FALSE.

Then swap ...

if(!connect()) {


for ...

$dbc = connect();

if($dbc == FALSE) {


although, personally I would put the TRUE statement first, it flows better to me.

Smeagel13
Junior Poster in Training
83 posts since Oct 2011
Reputation Points: 15
Solved Threads: 8
 

Thanks! That works.

calebcook
Junior Poster in Training
66 posts since Jun 2011
Reputation Points: 10
Solved Threads: 4
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: