Page 1 of 1

variables with sql code?

Posted: Sun Jun 17, 2012 3:03 am
by sturekdrf
Okay the below code is obviously not complete I had a question though. When I was watching the tutorial, I noticed that as far as I saw there was not a column for total_posts. So by doing the AS `total_posts` is that creating a variable or temporary table/column to store the about query information?


[syntax=sql]
SELECT
`posts`.`user_id`,
COUNT(`posts`.`post_id`) AS `total_posts`
FROM `posts`
GROUP BY `user_id`
[/syntax]

Re: variables with sql code?

Posted: Sun Jun 17, 2012 12:17 pm
by Temor
Yes, AS creates a new array key. Here's an example:
[syntax=php] <?php
// This will shorten the name of "really_long_column_name" to just "column" which is easier to type repeatedly.
$result = mysql_query("SELECT `really_long_column_name` AS `column`, `another_long_column_name` FROM `table`");

$columns = array();

while($row = mysql_fetch_assoc($result)){
$columns['column'] = $row['column'];
$columns['another_column'] = $row['another_long_column_name'];
}
?>[/syntax]

I hope that makes it a bit clearer. If not, please tell me :P

Re: variables with sql code?

Posted: Sun Jun 17, 2012 1:48 pm
by sturekdrf
So if I am reading this right and bear with me because query's are probably my the biggest thing I have trouble with in PHP.

That code, gets two columns from the table named table, turning the really long column into just column using the AS function and leaving the other one normal. The while statement I am not quite sure what it says, but I would assume its checking to make sure that there is information in $row using $result as the check to ensure you get the proper information where it should go.

Than (jeez it took me a minute to figure out the last part.)

you defined columns as a array, than made two keys one with the column information and the other with another long column. If I got something wrong her let me know.

Right? close? maybe? lol

Re: variables with sql code?

Posted: Sun Jun 17, 2012 1:57 pm
by Temor
Just right :D
The while loop is looping once for every result, and if there are no more results the function will return false. When it does, the loop stops.
It then assigns the name of the column as a key in the $row variable. We then use that to transfer the data into the $columns array.

Re: variables with sql code?

Posted: Sun Jun 17, 2012 1:59 pm
by sturekdrf
Thanks for the explanation with while, glad at least I am making some head way on querys, dunno why i have such a hassel with it.