Jump to content

Functions and MySQL Connectivity issues


ANdrww
Go to solution Solved by ANdrww,

Recommended Posts

I am trying to create a script (from a tutorial I try to adapt to my own needs) and I am running into a few problems. Here I go...

 

I have an /includes folder which contains the following: database.php and functions.php with the following content:

 

database.php

<?php

// Database connectivity stuff

$host     = "localhost"; // Hostname for the database. Usually localhost
$username = "root"; // Username used to connect to the database
$password = "root"; // Password for the username used to connect to the database
$database = "blog"; // The database used

// Connect to the database using mysqli_connect
$connection = mysqli_connect($host, $username, $password, $database);

// Check the connection for errors
	if (mysqli_connect_errno($connection)) {
	// Stop the whole page from loading if errors occur
	die("<br />Could not connect to the database. Please check the settings and try again.") . mysqli_connect_error() . mysqli_connect_errno();
}


?>

functions.php

<?php

// Functions file for the system
function show_posts($user_id) {
    $posts = array();
    $sql = "SELECT body, stamp from posts where user_id = '$user_id' order by stamp desc";
    $result = mysqli_query($connection, $sql);

    while ($data = mysqli_fetch_assoc($result)) {
    	$posts = array(
	    		'stamp' => $data->stamp,
	    		'user_id' => $user_id,
	    		'body' => $data->body
    		);
    }
    return $posts;
}

function show_users() {
	$users = array();
	$sql = "SELECT id, username FROM users WHERE status = 'active' ORDER BY username";
	$result = mysqli_query($connection, $sql);

	while ($data = mysqli_fetch_array($result)) {
		$users[$data->id] = $data->username;
	}
	return $users;
}

function following($user_id) {
	$users = array();
	$sql = "SELECT DISTINCT user_id FROM following WHERE follower_id = $user_id";
	$result = mysqli_query($connection, $sql);

	while ($data = mysqli_fetch_assoc($result)) {
		array_push($users, $data->user_id);
	}
	return $users;
}

?>

And here's the code that I run to display the users in users.php

      <?php

        $users = show_users();
        foreach ($users as $key => $value) {
          echo $key . " " . $value;
        }

      ?>

That throws me the following errors:

 

Notice: Undefined variable: connection in /Applications/MAMP/htdocs/blog/includes/functions.php on line 22

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /Applications/MAMP/htdocs/blog/includes/functions.php on line 22

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in /Applications/MAMP/htdocs/blog/includes/functions.php on line 24

 

 

I've tried to pass the $connection value to the show_users(); function with no results... any help would be appreciated. I am able to display the users from the database if I introduce the following code in users.php, but I want to try and keep things as clear as possible, without cluttering the files unnecessary.

       <?php 
        $users = array();
        $query = "SELECT id, username FROM users WHERE status = 'active' ORDER BY username";
        $result = mysqli_query($connection, $query);
        if ($result) {
        while ($member = mysqli_fetch_assoc($result)) { 
          echo strip_tags($member['username'])  . "<br />";
        }
        }
        else {
          echo "There are no posts to display. Why not add a new one?";
        }
        mysqli_free_result($result);
        mysqli_close($connection);
      ?>

PS: The users.php file also has require('includes/database.php'); and require('includes/functions.php'). I guess I'm trying to recreate the last bit of code into a working function... and I can't seem to do it.  Any help is appreciated. I hope it makes an sense...

 

-- Andrei

Link to comment
Share on other sites

You need to read up on variable scope as this the issue with your code.

 

The problem is the $connection variable is defined outside of your functions. Functions have their own variable scope, meaning variables defined outside of it are not accessible. The solution is to either define $connection as global or pass it to your functions as an argument.

Edited by Ch0cu3r
Link to comment
Share on other sites

You need to read up on variable scope as this the issue with your code.

 

The problem is the $connection variable is defined outside of your functions. Functions have their own variable scope, meaning variables defined outside of it are not accessible. The solution is to either define $connection as global or pass it to your functions as an argument.

 

Please don't suggest using globals.  We strive to teach best practices here, and using 'global' is anything but.

Link to comment
Share on other sites

Thanks for the reply Ch0cu3r.

 

I've tried passing the $connection variable to my function as follows:

function show_users($conection) {
	$users = array();
	$sql = "SELECT id, username FROM users WHERE status = 'active' ORDER BY username";
	$result = mysqli_query($connection, $sql);

	while ($data = mysqli_fetch_array($result)) {
		$users[$data->id] = $data->username;
	}
	return $users;
}

That throws the folloing error:

 

Warning: Missing argument 1 for show_users(), called in /Applications/MAMP/htdocs/blog/users.php on line 18 and defined in /Applications/MAMP/htdocs/blog/includes/functions.php on line 19

Notice: Undefined variable: connection in /Applications/MAMP/htdocs/blog/includes/functions.php on line 22

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /Applications/MAMP/htdocs/blog/includes/functions.php on line 22

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in /Applications/MAMP/htdocs/blog/includes/functions.php on line 24

 

I should pass the $connection variable when calling the function in users.php ? Like this?

      <?php

        $users = show_users($connection);
        foreach ($users as $key => $value) {
          echo $key . " " . $value;
        }

      ?>

Thanks Kevin for pointing that out.

Link to comment
Share on other sites

I should pass the $connection variable when calling the function in users.php ? Like this?

Yes, you should. You need to define it as a parameter when declaring the function (as you did with function show_users($connection){) and you need to actually pass in the value at the time you call the function (as you showed).

 

The errors you posted are caused by you forgetting to actually pass in the value when calling the function.

Link to comment
Share on other sites

Yes, you should. You need to define it as a parameter when declaring the function (as you did with function show_users($connection){) and you need to actually pass in the value at the time you call the function (as you showed).

 

The errors you posted are caused by you forgetting to actually pass in the value when calling the function.

Thanks a lot.. still not quite there though :\

 

Functions.php

function show_users($conection) {
	$users = array();
	$sql = "SELECT id, username FROM users WHERE status = 'active' ORDER BY username";
	$result = mysqli_query($connection, $sql);

	while ($data = mysqli_fetch_array($result)) {
		$users[$data->id] = $data->username;
	}
	return $users;
}

Users.php

      <?php

        $users = show_users($connection);
        foreach ($users as $key => $value) {
          echo $key . " " . $value;
        }

      ?>

Error

Notice: Undefined variable: connection in /Applications/MAMP/htdocs/blog/includes/functions.php on line 22

 

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /Applications/MAMP/htdocs/blog/includes/functions.php on line 22

 

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in /Applications/MAMP/htdocs/blog/includes/functions.php on line 24

 

It still doesn't get the connection. What am I missing? I've included the database.php file in users.php, I have the variable $connection = mysqli_connect($host, $username, $password, $database);

 

Frustrating

Link to comment
Share on other sites

  • Solution

Sorry, sorry sorry. I've just read that I misspelled $connection. It's now working as expected, and I'm currently trying to figure out the other functions I've wrote as well. Please don't close the topic (though solved) as I might (will for sure) ask other questions as well.

 

Thanks a lot. Turns out I need to be more careful when writing the names.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.