0

I am trying to use a variable from my function in an echo in PHP for a form. This is an update form so I want to display current user informatoin.

My function is like this:

public static function current()
{
    $id = null;
    if ( !empty($_GET['id'])) {
        $id = $_REQUEST['id'];
    }
    $pdo = Database::connect();
    $sql = "SELECT * FROM customer where counter = ?";
    $q = $pdo->prepare($sql);
    $q->execute(array($id));
    $data = $q->fetch(PDO::FETCH_ASSOC);
    $firstname = $data['firstname'];
    $lastname = $data['lastname'];
    $email = $data['email'];
    Database::disconnect();
}

my form is trying to echo it here in the value:

<input class="form-control" name="firstname" id="firstname" 
value="<?php echo !empty($firstname)?$firstname:'';?>">

I can't seem to get the $firstname variable to echo the users first name. The user is called by a string in the url that uses ?id=

2
  • Your variable is not within scope of where you are trying to access it Commented May 19, 2015 at 3:58
  • is there no way to access the variable by using the function? Commented May 19, 2015 at 3:58

1 Answer 1

3

Two options,

return the desired value (or values) from the function

public static function current()
{
    $id = null;
    if ( !empty($_GET['id'])) {
        $id = $_REQUEST['id'];
    }
    $pdo = Database::connect();
    $sql = "SELECT * FROM customer where counter = ?";
    $q = $pdo->prepare($sql);
    $q->execute(array($id));
    $data = $q->fetch(PDO::FETCH_ASSOC);
    Database::disconnect();
    return array_intersect_key($data, array_flip(array('firstname', 'lastname', 'email')));
}

...

$user = Thing::current();
echo $user['email'];

OR set a static variable in your class to reference after

public static function current()
{
    $id = null;
    if ( !empty($_GET['id'])) {
        $id = $_REQUEST['id'];
    }
    $pdo = Database::connect();
    $sql = "SELECT * FROM customer where counter = ?";
    $q = $pdo->prepare($sql);
    $q->execute(array($id));
    $data = $q->fetch(PDO::FETCH_ASSOC);
    self::$firstname = $data['firstname'];
    self::$lastname = $data['lastname'];
    self::$email = $data['email'];
    Database::disconnect();
}

...

echo Thing::$firstname;

I'd prefer the first thing, but instead of returning an array with the details, make it into a Customer object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.