Object PHP and MYSQL queries
I'm experiencing mysql with object-oriented php, so i created a db with only one table called users that i want to query using php classes (the insertion function properly works)
This is my php user class:
<?php
class user{
var $name;
var $surname;
var $email;
var $age;
function set_user_properties($pname, $psurname, $pemail, $page){
include "include.php";
$sql = "INSERT INTO users (name, surname, email, age)
VALUES ('$pname', '$psurname','$pemail', '$page')";
if ($conn->query($sql) === TRUE){
echo "New record created successfully";
}else{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
function get_user_properties($name){
include "include.php";
$sql3 = "SELECT name, surname, email, age
FROM users
WHERE name='$name'";
$result3 = $conn->query($sql3);
if ($result3->num_rows > 0) {
// output data of each row
while($row3 = $result3->fetch_assoc()) {
$this->name=$row3["name"];
$this->surname=$row3["surname"];
$this->email=$row3["email"];
$this->age=$row3["age"];
}
}
$conn->close();
return $this;
}
}
?>
And this is the page where i want to read all the query results:
<?php
include("class_lib.php");
$pname=$_POST["firstname"];
$user1=new user();
$user1->get_user_properties($pname);
echo $user1->name;
echo $user1->surname;
echo $user1->email;
echo $user1->age;
?>
My question is: when i make a query which is supposed to have more than just one result (like this one), how can i pass all the results to the destination page?
Answer
Solution:
The problem is that your class only stores information for one user, and that means you can't really expect it to store multiple users at once.
So the question is: "how do I get an array of users instead of just one?" And the answer to that is to create a class that performs DB queries and parses each row of the query results into a user object
referencing this part of your code:
If you add a constructor function to your user class to instantiate a user with a name, surname, email, and age, you can end up with code in your DB class that looks more like the following
I hope that makes sense.
Answer
Solution:
Thanks everyone for helping, I solved my problem adding a constructor and using a class method. Here is the code, in case someone else will struggle on the same problem.
This is the class_lib.php where is defined the all() method that make an array with the resutus of the query:
People are also looking for solutions of the problem: illegal string offset
Source
Share
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.