使用数组查询数据库

时间:2015-04-07 13:31:00

标签: php mysql arrays

当我这样做时,我只得到一个结果Fantasy0.1429当我应该得到7个不同的结果时,任何人都知道我做错了什么。

$userid = $_SESSION['sess_id'];

$genreQuery = $con ->query ("select distinct(genre) from movies");

$movieGenre = array();

while($row = $genreQuery->fetch_object())  {
$movieGenre[] = $row;
}

foreach($movieGenre as $MGenre){
 $query = $con ->query 
 (" select '$MGenre->genre' genre, IFNULL(count(*)/(select count(*) from user_movie_ratings where user_id = '$userid'),0) rating
    from   user_movie_ratings umr,
    movies m
    where  umr.user_id = '$userid'
    and    umr.movie_id = m.id
    and    m.genre = '$MGenre->genre'; ");

$movieTitle = array();

while($row = $query->fetch_object())  {
$movieTitle[] = $row;
}
}   

然后我稍后回复

<?php foreach($movieTitle as $movie): echo $movie->genre; echo $movie->rating; endforeach; ?>

1 个答案:

答案 0 :(得分:0)

尝试在foreach之前移除数组的instanciation,如:

// Some code ...
$movieTitle = array();

foreach($movieGenre as $MGenre){
 $query = $con ->query 
 (" select '$MGenre->genre' genre, IFNULL(count(*)/(select count(*) from user_movie_ratings where user_id = '$userid'),0) rating
    from   user_movie_ratings umr,
    movies m
    where  umr.user_id = '$userid'
    and    umr.movie_id = m.id
    and    m.genre = '$MGenre->genre'; ");

while($row = $query->fetch_object())  {
$movieTitle[] = $row;
}
}