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

Member Avatar for diafol

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?

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.

Thanks! That works.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.