darkness darkness - 11 months ago 31
SQL Question

mysql get selection data to store in array but i only get 1 as return

public function select($sql){
$results = $this->connection_database->prepare($sql);

$results->execute();

if($results->rowCount() >0){};

return $results;
}

public function prepare_product(){
if(!empty($this->directoryfile)){
$table = $this->directoryfile;
$sql = "SELECT * FROM $table ";
$results = $this->select($sql);

//Fetch our results into an associative array
$results = $results->fetch(PDO::FETCH_ASSOC);

//The registration date of the stored matching user
$productname = $results['DATA_PATH'];


echo json_encode($productname);
}
}


lets said mysql database have "ID" and "DATA_PATH", my intention is to get all the "DATA_PATH" data store in array , but i only get 1 "DATA_PATH" as return , what did i miss ?
can anyone give me some help ?

the data do return but i only get one , there is 5 item in my database.

Answer

You have to:-

1.Create an array variable

2.Apply a loop

3.Assign all data to that array variable

4.At last apply json_encode() to that array variable

like below:-

$results = $this->select($sql);
$productname = array(); // create an array

while($row = $results->fetch(PDO::FETCH_ASSOC)){

      //The registration date of the stored matching user
      $productname[] = $row['DATA_PATH']; // assign value to that array
}
echo json_encode($productname);