Darkaaja
Darkaaja

Reputation: 98

Variable between php files

Before anyone points out my code is flawed in security or etc know that I am quite a PHP noob and wouldn't mind you forwarding some help to fix that rather than just yelling it is terrible.

Also I did try this below and it won't work for me because it stores it into the session (Unless session is more secure than I thought. I assume users can extract data from one, correct?): http://tinyurl.com/myqx3xo

As for my question, how would I be able to access the variable $connectdb in my users function? When I do that it gives me 'Undefined variable' error, and isn't detecting that it exists whatsoever. Both are requires in main\folder\start.php that is loaded every page, and on those pages I attempted to call the function and it gave me a failure. The code works fine when I attempt to hardcode the $connectdb's varible into the functions but again there are good reasons not to. Will add additional details if required.

Undefined variable: connectdb in main\folder\folder1\users.php on the line that starts with $data

main\folder\folder1\users.php function:

function user_data($id) {
    $data = array();
    $user_id = (int)$id;
    $func_num_args = func_num_args();
    $func_get_args = func_get_args();
    if ($func_num_args > 1) {
        unset($func_get_args[0]);
        $fields = '' . implode(', ', $func_get_args) . '';
        $data = mysqli_fetch_assoc(mysqli_query($connectdb,"SELECT $fields FROM users WHERE id = $id"));
        return $data;
    }
}

main\folder\folder2\connect.php:

<?php
$connect_fail = 'Example connection failure.';

$dbhost = 'host';
$dbuser = 'user';
$dbpass = 'pass';
$db     = 'database';
$connectdb = mysqli_connect($dbhost, $dbuser, $dbpass, $db) or die($connect_fail);
?>

Upvotes: 0

Views: 58

Answers (2)

Padmanathan J
Padmanathan J

Reputation: 4620

include your connect.php into your user.php

include('../fodler2/connect.php');

function user_data($id) {
    $data = array();
    $user_id = (int)$id;
    $func_num_args = func_num_args();
    $func_get_args = func_get_args();
    if ($func_num_args > 1) {
        unset($func_get_args[0]);
        $fields = '' . implode(', ', $func_get_args) . '';
        $data = mysqli_fetch_assoc(mysqli_query($connectdb,"SELECT $fields FROM users WHERE id = $id"));
        return $data;
    }
}

Upvotes: 1

ElefantPhace
ElefantPhace

Reputation: 3814

in your users.php file you need to add

include "../folder2/connect.php";

Upvotes: 0

Related Questions