将mySQL AS结果分配给变量

时间:2013-03-26 13:11:22

标签: php mysql

我试图将mySQL语句中的AS变量分配给变量,以便我可以处理结果。但是我无法将这些视频分配给这些视觉效果。

mySQL SELECT语句如下

$sql = "SELECT min(ups) AS minups, max(ups) AS maxups, min(downs) AS mindowns, max(downs) AS maxdowns, min(score) AS minscore, max(score) AS maxscore, min(comments) AS mincomments, max(comments) AS maxcomments, min(totalVotes) AS mintotalvotes, max(totalVotes) AS maxtotalvotes FROM reddit WHERE movie = ':movie'";
    $stmt = $conn->prepare( $sql );
    $stmt->bindValue( ":movie", $redditMovies->reddit, PDO::PARAM_INT );
    $stmt->execute();
    $row = $stmt->fetch();

我正在尝试将它们分配给这些变量

$minups = $row ['minups'];
$maxups = $row ['maxups'];
$rups = (int)($maxups - $minups);
print_r($rups);
$mindowns = $row ['mindowns'];
$maxdowns = $row ['maxdowns'];
$rdowns = (int)($maxdowns - $mindowns);
$minscore = $row ['minscore'];
$maxscore = $row ['maxscore'];
$rscore = (int)($maxscore - $minscore);
$mincomments = $row ['mincomments'];
$maxcomments = $row ['maxcomments'];
$rcomments = (int)($maxcomments - $mincomments);
$mintotalvotes = $row ['mintotalvotes'];
$maxtotalvotes = $row ['maxtotalvotes'];
$rtotalvotes = (int)($maxtotalvotes - $mintotalvotes);

我需要更改哪些内容才能解决此问题?

3 个答案:

答案 0 :(得分:1)

尝试删除查询中的括号,例如

movie = ':movie' to movie = :movie

答案 1 :(得分:1)

使用此代码。使用 extract($row) 用于直接为 $ row 数组中的键分配值

    $stmt = $conn->prepare("SELECT min(ups) AS minups, max(ups) AS maxups, min(downs) AS mindowns, max(downs) AS maxdowns, min(score) AS minscore, max(score) AS maxscore, min(comments) AS mincomments, max(comments) AS maxcomments, min(totalVotes) AS mintotalvotes, max(totalVotes) AS maxtotalvotes FROM reddit WHERE movie = ':movie'");
    $stmt->bindValue( ":movie", $redditMovies->reddit, PDO::PARAM_INT );
    $stmt->execute();
    $row = $stmt->fetch();

    extract($row);
    echo $minups;  // it prints the minups value from the result set $row.

    $rups = (int)($maxups - $minups);
    $rdowns = (int)($maxdowns - $mindowns);
    $rscore = (int)($maxscore - $minscore);
    $rcomments = (int)($maxcomments - $mincomments);
    $rtotalvotes = (int)($maxtotalvotes - $mintotalvotes);

这个摘录($ row);用于指定键的值

示例:

$row['maxups']=5;
$row['minups']=2;
extract($row);   
echo $maxups."-".$minups;

输出:5-2

答案 2 :(得分:0)

试试这个

echo '<pre>';
 print_r($row);

如果数组中没有值,则检查查询是否有任何错误