Hey all,
I'm new to PHP in an object oriented approach but I like the idea behind it and am trying to develop this way from now on. I'm also very new to PHP prepared statements and am trying to implement all of my queries this way. I came up with some working code that does what I want but I would just really appreciate some feedback from the experts on whether or not this is 'efficient' or if it may cause slow loading times or other problems.
Here is how I call the data in my view page:
<?php $all_user = User::get_user(1); ?>
... blah blah
<?php foreach($all_user as $user): ?>
First: <?php echo $user->user_first; ?><br />
Last: <?php echo $user->user_last; ?><br /><br />
<?php endforeach; ?>
and here is the code, inside the class "User":
class User {
public $user_id;
public $user_first;
public $user_last;
public $user_email;
public static function get_user($user_id) {
global $database;
$query = "SELECT user_id, user_first, user_last, user_email FROM user WHERE user_id >= ?";
$stmt = $database->connection->stmt_init();
if ($stmt->prepare($query)) {
$stmt->bind_param("i", $user_id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($user_id, $user_first, $user_last, $user_email);
$object_array = array();
while($row=$stmt->fetch()) {
$object = new self;
$object->user_first = $user_first;
$object->user_last = $user_last;
$object_array[] = $object;
}
$stmt->free_result();
$stmt->close();
}
return $object_array;
}
}
I'm mostly curious about the way I set up the object_array as an array of objects so that I can refer to them as objects in my foreach on the view page... Is that common? Or is there a better way to do it?
Thanks everyone 🙂