variables with sql code?

Ask about a PHP problem here.
Post Reply
sturekdrf
Posts: 40
Joined: Fri Jun 15, 2012 8:25 pm

variables with sql code?

Post 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]
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: variables with sql code?

Post 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
sturekdrf
Posts: 40
Joined: Fri Jun 15, 2012 8:25 pm

Re: variables with sql code?

Post 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
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: variables with sql code?

Post 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.
sturekdrf
Posts: 40
Joined: Fri Jun 15, 2012 8:25 pm

Re: variables with sql code?

Post 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.
Post Reply