简体   繁体   中英

Echo a function variable in PHP

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=

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM