2016-09-15 2 views
0

JOINクエリから結果をフェッチする場合、各行ごとに結合の各テーブルごとに個別の変数を取得するにはどうすればよいですか?例えば結合の各テーブルのMySQL行を別々の変数に分割する方法

$result = $mysql->query(sprintf('SELECT * 
    FROM `TableOne` one 
    JOIN `TableTwo` two ON (one.TwoID = two.TwoID) 
    JOIN `TableThree` three ON (one.ThreeID = three.ThreeID) 
    WHERE one.OneID = %u', 
    (int)$primary_key)); 
while ($row = $result->fetch_assoc()) { 
    // Instead of $row, I want: 
    // $one: all fields from TableOne 
    // $other: all fields from TableTwo and TableThree 
} 

答えて

0

が溶液:

function mysqli_fetch_assoc_per_table(mysqli_result $result, $instruction) { 
    $row = $result->fetch_assoc(); 
    if (!$row) return false; 
    $fields = $result->fetch_fields(); 

    $groups = array(); 
    foreach (explode(',', $instruction) as $arg) { 

     $group = array(); 
     foreach (explode('|', $arg) as $table) { 
      foreach ($fields as $field) { 
       if ($field->table == $table) { 
        $group[$field->name] = $row[$field->name]; 
       } 
      } 
     } 

     $groups[] = $group; 
    } 

    return $groups; 
} 

使用:

while (list($one, $other) = mysqli_fetch_assoc_per_table($result, 'one,two|three')) { 

} 
+0

これはない3つのループで行うことができ – nogad

関連する問題