0

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

3
Contributors
3
Replies
4
Views
5 Years
Discussion Span
Last Post by calebcook
0

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?

Edited by diafol: n/a

0

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.

Edited by Smeagel13: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.