mercredi 28 octobre 2015

PHP - SQLite Copying SQLite PDO object to function as parameter

For start, I'm a novice with PHP and OOP, but I'll try my best to be specific and concise. Thanks for any answers and your time in advance.

I'm trying to make a small script in PHP that works with PDO and sqlite.

I've made a function to read a specific parameter (column value) for a specific user (in the same row as the username).

/* Function Return_Data_For_User_As_Object
Takes a username,
and returns an object containing all column values on the same row as the username

@param $db - PDO database object, the database to look in
@param $username - the username to find all associated data for

@return object, containing data for all columns of the same table row where the username was located,
eg. to access data, if having the result stored in an object, you would use $object->columnname
*/

function Return_Data_For_User_As_Object($db,$username)
{

// Create a prepared statement
$stmt = $db->prepare("SELECT * FROM UserData WHERE username= :usn");
$stmt->bindParam(':usn', $username);
$stmt->execute();
// Get the result data as an object
$result=$stmt->fetchObject();

$db = null;

//Return the result data object
return $result;
}

Somewhere in script (same file or another file after the function is imported), I would plan to call this function something like this:

<?php

    //Open the database
    $db = new PDO('sqlite:UserDataDb.sqlite');

    //Get all columns for one user as individual object variables
    $result = Return_Data_For_User_As_Object($db,'user1');

?>

Then I could do $result->columname to access the value of any other column. I'm targeting a specific value, so this method is fairly useful for me (no less than an array).

Questions:

1 - as this method should copy the $db object when forwarding it to the function, does that make it ineffective? If so, what is the simplest more effective way to achieve the same kind of function and usage.

2 - is it required to use $db = null; inside of the function (to close the database), or as it's a local copy used by the function, will it get closed automatically after the function has finished?

Thank you.

Aucun commentaire:

Enregistrer un commentaire