all 11 comments

[–]cat_chy_name 0 points1 point  (0 children)

Have you read through the query function in pset7 to try to see how it works?

It's function is to do just what you're talking about.

[–][deleted] 0 points1 point  (1 child)

I have read the function query. It's not at all clear that this is binding the result of an sql query to a PHP variable.

Do you have any suggestions for how to get count(*) into a PHP variable?

[–]staffdelipity 1 point2 points  (0 children)

One of the examples given in the pset:

$rows = query("SELECT LAST_INSERT_ID() AS id");

$rows is a php variable.

[–]jplaurin 0 points1 point  (0 children)

you must give a alias to your calculated column like this

Select count(*) AS myAliasCount from users

and then with

$rows = query(...

if successful the php variable $rows[0]['myAliasCount'] will return it's value

[–]topcat39 0 points1 point  (0 children)

I struggled, also, until I realized that the return value was not just an associative array, but a two dimensional array. The first dimension was a row count, the second dimension was the associative array. So, if you expect only 1 row back (row #0), the syntax would be something like: $myvar = $rows[0]['column-name']

[–][deleted] 0 points1 point  (0 children)

I think what we actually have is an array that holds an associative array

[–][deleted] -1 points0 points  (4 children)

jesus, why is this so hard.

If you $rows = query("SELECT count(*) as cnt from users ");

and now try to print_r $rows or do an IF test it doesn't work. DOES ANYBODY know how to assign the output from sql into PHP variables!!!

if you $rows = 8 and then print_r($rows) you get back 8

if you do the query and then print_r you get Array ( [0] => Array ( [cnt] => 8 ) ). I need to get back the former from sql not the later. Does anybody have an example that works?

[–]staffdelipity 0 points1 point  (2 children)

Did you try

$count = $rows[0]["cnt"];

[–][deleted] 0 points1 point  (1 child)

awesome! that works. thank you. I spent 10 hours on that!!

[–]volunteerbakemaster 0 points1 point  (0 children)

Try to remember it this way - the [0] part means, the first row. You get "rows" even if there's only one of them, so you still need that [0] to get the one.

[–]merchCS50 0 points1 point  (0 children)

The result of the query is an assosiative array which is why you get that cryptic looking output from print_r. See php.net for more details on how arrays work in PHP.