For starters, it would help if you indented your PHP code properly and posted it in [php][/php] bbcode tags, e.g.,
<?php
//conn.php
$config['db']['host'] = "mysql:host=localhost;dbname=new";
$config['db']['user'] = "root";
$config['db']['pass'] = "";
//main.php
require "conn.php";
class DbConnect {
public $conn;
function __construct() {
global $config;
$host = $config['db']['host'];
$user = $config['db']['user'];
$pass = $config['db']['pass'];
try {
$this->conn = new PDO($host, $user, $pass);
}
catch (PDOException $pe) {
die("Cannot connect");
}
}
public function showCAt($query) {
$this->conn->prepare($query);
$que = $this->conn->query($query);
$row = $que->fetch(PDO::FETCH_ASSOC);
return $row;
}
}
$query = "select * from friends";
$db = new dbconnect();
$db = $db->showCAt($query);
foreach($db as $key => $value){
echo "<br>".$value;//the problem that I get Only one row from database.
}
Now, the problem is that DbConnect::showCAt() returns an array representing the first row retrieved from the execution of the query. It does not retrieve the rest of the rows. A simple solution is to return an array of arrays, i.e., an array of all the row results, e.g.,
public function showCAt($query) {
$this->conn->prepare($query);
$que = $this->conn->query($query);
$rows = array();
while ($row = $que->fetch(PDO::FETCH_ASSOC)) {
$rows[] = $row;
}
return $rows;
}
However, note that now your foreach loop does not loop over the fields of a particular result row, but over the array of result rows. As such, you would need to nest another loop or manually extract the fields.