I have this table ID Tabs_Name 1 Drinks 2 Food 3 Console
I want to get all the Tabs_Names value but I cant find the way to do it. I only get the first result only. This is my code
class Tabs{
public $ID = 0;
public $Tab_Name = "";
public $Tab_Count=0;
public function __construct()
{
$servername = "****";
$username = "****";
$password = "****";
$dbname = "****";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT ID, Tab_Name, Count(Tab_Name) As Tab_Count FROM Dummie_tabs";
//$query2 = "SELECT COUNT(Tab_Name) AS Tab_Count FROM Dummie_tabs";
$result = $conn->query($query);
//$result2 = $conn->query($query2);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$this->ID = $row["ID"];
$this->Tab_Name = $row["Tab_Name"];
$this->Tab_Count =$row["Tab_Count"];
}
else {
echo "0 results";
}
}
public function __destruct()
{
;
}
public function setID($ID, $Tab_Count)
{
$this->ID = $ID;
$this->Tab_Count= $Tab_Count;
}
public function getTab()
{
return $this->Tab_Name . $this->Tab_Count ."<br />";
}
}
$R = new Tabs();
echo $R->getTab();
I need to retrieve all the values from the database
You can do one of two things to get the data from a database - it's no different in a class to what you would do in procedural code.
Method 1: Instead of using a "fetch" which pulls a single record from the database, you use a fetchall which fetches all the rows of the query.
Method 2: You use a loop to iterate through the records that are matching in the database. This is the approach most commonly used in code.
while($row = $result->fetch_assoc())
{
$this->ID = $row["ID"];
$this->Tab_Name = $row["Tab_Name"];
$this->Tab_Count =$row["Tab_Count"];
}
The way the code is written at the moment though, it will iterate through the results and replace the contents of the properties each time. You may consider putting them into an array like this instead:
while($row = $result->fetch_assoc())
{
$this->ID[] = $row["ID"];
$this->Tab_Name[] = $row["Tab_Name"];
$this->Tab_Count[] =$row["Tab_Count"];
}
EDIT: As pointed out in the comment below, your SQL query is also flawed. You are using a count(*) aggregate function - but have not grouped the selected columns properly:
SELECT ID, Tab_Name, Count(Tab_Name) As Tab_Count
FROM Dummie_tabs
GROUP BY ID, Tab_Name