Why does it give me this notice?
Who does:
echo $post['avg']
Give me:
Notice: Undefined index: avg in posts.php on line 39
SELECT p.id, p.message, p.poster, avg(r.rating)
FROM posts p
LEFT OUTER JOIN userpostratings r ON p.id = r.postID
WHERE p.id = 1
GROUP BY p.id
CREATE TABLE IF NOT EXISTS `userpostratings` (
`userID` int(10) NOT NULL DEFAULT '0',
`postID` int(10) unsigned NOT NULL DEFAULT '0',
`rating` int(2) NOT NULL DEFAULT '0',
KEY `userPostRatings_userID` (`use开发者_如何学PythonrID`),
KEY `userPostRatings_postID` (`postID`)
)
CREATE TABLE IF NOT EXISTS `posts` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`message` text,
`poster` int(10) unsigned NOT NULL DEFAULT '0',
`posted` int(10) unsigned NOT NULL DEFAULT '0',
`topic_id` int(10) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
)
The field is named avg(r.rating)
not avg
.
So $post['avg(r.rating)']
would be correct (assuming you're storing the query results in $post), while $post['avg']
would return a warning, because that index (avg
) is never set or defined anywhere.
Use an alias in your query to make the name more friendly, like this:
SELECT p.id, p.message, p.poster, avg(r.rating) AS avg_rating
FROM posts p LEFT OUTER JOIN userpostratings r ON p.id = r.postID WHERE p.id = 1 GROUP BY p.id
Don't use avg
as the alias, since this is a reserved word.
You are getting that notice because the your the avg
index in your $post
array is not defined. Note, this is not the same as data from your HTTP Post data, $_POST
.
As noted the actual field name is "avg(r.rating)" usually its best to Tweak your SQL like so:
SELECT p.id, p.message, p.poster, avg(r.rating) as avgr
FROM posts p
LEFT OUTER JOIN userpostratings r ON p.id = r.postID
WHERE p.id = 1
GROUP BY p.id
Then you can refer to the result of the function with the much more readable"
echo $post['avgr']
Change it to
echo $_POST['avg']
精彩评论