简体   繁体   中英

Extract multiple rows with same id mysql php

Hi I have the following table:

id  request_id  ein intervention_date   time_slot
10  1   600545383   18/05/2015 00:00    AM
11  3   802877145   01/06/2015 00:00    AM
12  3   802310154   02/06/2015 00:00    PM
13  3   801777170   03/06/2015 00:00    AM

I have the following query:

function get_coach_request_assignment_on_request_id($request_id){
        $connection = get_db();
        $query = 'SELECT * FROM coach_request_assignment WHERE request_id='.$request_id;
        return $connection->query($query);
    }

When I call this function, it returns only the first row where request_id=3 how to extract all the values returned by the query?

This is what I have tried:

$coach_request_assignment_data = get_coach_request_assignment_on_request_id($request_id);
$coach_request_assignment_data = $coach_request_assignment_data->fetch_assoc();

That's how the var_dump($coach_request_assignment_data) looks like:

array (size=5)
  'id' => string '11' (length=2)
  'request_id' => string '3' (length=1)
  'coach_uin' => string '802877145' (length=9)
  'date_intervention' => string '2015-06-01 00:00:00' (length=19)
  'time_slot' => string 'AM' (length=2)

Thanks here...

If this is a MySQLi API, then you'll need multiple invocations of fetch_assoc() in order to get those multiple rows. You have only invoked ->fetch_assoc() once:

$results = get_coach_request_assignment_on_request_id($request_id);
$coach_data = array();
while($row = $results->fetch_assoc()) {
    $coach_data[] = $row; // push row
}
// print_r($coach_data);

I'm guessing you're using the mysqli extension?

What about trying:

$coach_request_assignment_data->fetch_all(MYSQLI_ASSOC);

This will fetch the entire result set at once, rather than needing to loop through it yourself. The MYSQLI_ASSOC tells it to return it in an associative array with the column names included. The default is MYSQLI_NUM, which simply returns a numerical-indexed array with no column names.

Are you using PDO::query() ? If yes, query() returns a PDOStatement which you can loop over, eg :

$results = get_coach_request_assignment_on_request_id($request_id);
foreach ($results as $result) {
   //do something with $result
}

Doc : http://php.net/manual/fr/pdo.query.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM