Reputation: 329
I've been requested to manage entities stored in a DB as object once retrieved. My questione is related on when a SELECT
returns many tuples.
I'd need to use every result to create a new object, the problem is that off course I can't anticipate how many, and which name use on them.
question improvement: However I already know the table structure, and I already have wrote the class to instatiate a single class, I'm just wondering on the correct way to manager an arbitrary numer of them.
My idea so far is to use an array, and push into it a new object for every row in the result set.
Please, your opinions are welcome.
Thanks in advance.
Upvotes: 0
Views: 88
Reputation: 187
You can try something like this:
public function getDataFromTable()
{
$con = new mysqli(db_host, db_user,db_pass,db_name);
if ($con->connect_errno) {
print ("Connection error (" . $con->connect_errno . "): $con->connect_error");
}
else {
// $res is a result of this query down
$res = $con->query("SELECT * FROM whatever");
if ($res)
{
$whatever=null;
while($row=$res->fetch_assoc()) //row will be one row from table and you just need to create your objects and put them in array, then return array.. ofc you will return this like json, and after that you will need to encode that and do something with response
{
$whatever[]=new Whatever($row["id"],$row["name"]);
}
$res->close();
return $whatever;
}
else
{
print ("Query failed");
}
}
}
Upvotes: 1