I have 2 columns in a table called Points. The 2 columns are UserPoints and UserID.
I want to be able to echo the total amount of points a user has.
I've got something like this but I dont think its right.
$getTotalPoints = mysql_query("SELECT SUM(UserPoints) FROM `Points` WHERE `UserID` = '1'") or die(mysql_error());
$totalPoints = mysql_fetch_array($getTotalPoints);
When i echo the above statement by echoing "$totalPoints" i get "Array".
Anyone know the correct query to do this ?
You're getting Array because that's what's stored in $totalPoints. Look closely at your code and you'll see you used the mysql_fetch_array() function, which retrieves a row of results from the results set as an array. If you do var_dump() on $totalPoints you'll see the following:
Array
(
[0] => 12345
[SUM(UserPoints)] => 12345
)
The sum you're looking for is at index 0 or the column name, in this case SUM(UserPoints), so you can output it using echo $totalPoints[0] or echo $totalPoints['SUM(UserPoints)'].
Alternatively, you could use the mysql_result() function. I think this is more in-line with the behavior you were expecting. It fetches a single value from the row from the result set. So, instead of mysql_fetch_array() you'd wrote:
$totalPoints = mysql_result($result, 0);
For more information on mysql_result(), check out the PHP documentation for it.
As an aside, I would recommend not using mysql_* functions if you have the option. A newer interface like PDO, or at least mysqli, would be better. This will depend on your project of course... if you're working with a large legacy code base it may be difficult to change. But if you're starting out now, I think you'd benefit from the newer libraries. You can see my opinion and some guidance on transitioning extensions in this article I wrote.
Hope this helped... and good luck!
mysql_fetch_array fetches a result row as an associative array, a numeric array, or both. by default it creates both. all that you need is to echo $totalPoints[0];
or, if you rewrite you request as
$getTotalPoints = mysql_query("SELECT SUM(UserPoints) total FROM `Points`
WHERE `UserID` = '1'") or die(mysql_error());
$totalPoints = mysql_fetch_array($getTotalPoints);
echo $totalPoints['total'];
mysql_fetch_array returns an array. Therefore you need to treat $totalpoints as an array.
try adding this line to the end of your snippet:
echo $totalPoints[0];
There are several ways to retrieve data with the mysql functions I suggest reading about them in the php manual.
Here is mysql_fetch_array
The resultset row is an array with as many elements as you got in the SELECT.
In you case you only got 1 element (the sum).
So you should:
echo $totalPoints[0];
If you need to debug this kind of issues I recommend you to read about print_r function.
Related
I'm currently working on a website with a friend and I need to display the average rating for a movie.
So, I have a database with numerous columns (name, mail, etc) including "note".
My friend wrote this code :
<?php
$moyenne = "SELECT avg(note) FROM `annee_1`";
$test = $db->prepare($moyenne);
$test->execute();
$resultat = $test->fetchAll(PDO::FETCH_ASSOC);
echo $resultat;
?>
I'm not overly familiar with php or mysql. I know something is wrong (since this doesn't display a number, but just "Array"), but I don't know what.
Any suggestiong, or solution to my problem?
Thanks ! :)
You can access to your result by passing parameter to your array with a while loop. Replace your echo $result by print_r($resultat) and you can check the result you have received.
Your query will return one row with one column. An easy way to get a single value from a query like that is to use
$resultat = $test->fetchColumn();
Instead of
$resultat = $test->fetchAll(PDO::FETCH_ASSOC);
You're seeing "Array" currently because $resultat is an array (because that's what fetchAll reutrns), and when you try to echo it, it gets converted to a string. In PHP, the string representation of any array is "Array". See the documentation here:
Arrays are always converted to the string "Array"; because of this, echo and print can not by themselves show the contents of an array.
But if you use fetchColumn() instead, $resultat won't be an array. Based on your comments, it should be an int.
I'm brand new to the PDO syntax and I'm liking the learning curve! I'm refactoring code - migrating over from archaic mysqli_* methods.
Predictably, I've run into some snags, being a novice. One of the big ones is (forgive if this is a dumb question) retrieving data from the DB and echoing it out on the page. Here is what I have so far:
$getURLid = $_GET['id'];
$idQuery = $connection->prepare("SELECT * FROM pages WHERE page_id = :getURLid");
$idQuery->execute(array(':getURLid' => $getURLid));
$idRetrieved = $idQuery->fetchAll(); // This is the part I'm unclear on.
When I echo $idRetrieved['value'] to the page, nothing shows up. I'm missing something or misunderstanding how it works. Maybe fetchAll isn't what I should be using.
If it is, is a loop necessary to retrieve all rows? I was under the impression that fetchAll would loop through them automatically based on what I've read.
Thanks for the help.
Read the doco for PDOStatement::fetchAll closely. It returns an array of row data.
The type of data representing each row depends on your fetch mode which by default is PDO::FETCH_BOTH. This would mean each row is an array with both numeric and associative keys. If you're only going to access the data associatively, I'd recommend using PDO::FETCH_ASSOC, eg
$idRetrieved = $idQuery->fetchAll(PDO::FETCH_ASSOC);
You would then either need to loop or access each row via its index, eg
foreach ($idRetrieved as $row) {
echo $row['value'];
}
// or
echo $idRetrieved[0]['value']; // assuming there's at least one row.
I've read through PHP PDO Book and now have some basic questions:
If i understood correctly, i'll have to use begin_transaction() in order to turn off autocommit. If i am okay with autocommit, i am always good to go with a simple query()Is this correct?
Did i get it right, that there is basically no difference between query() and exec(), except of the above asked topic?
I made a query like this one:
foreach ($db->query('SELECT * from user') as $row) {
$row = json_encode($row);
echo $row;
}
Which returns a JSON Object:
{
"alias":"tk",
"0":"tk",
"password":"pw",
"1":"pw",
}
This is basically correct, however, why is each value returned twice, once with my chosen keyword and another time with an Integer key?
why is each value returned twice, once with my chosen keyword and another time with an Integer key?
The array has the values both with the column names as keys, and the column ordinals too. So you could access the values from the result set by using the number of which column you want. (of course, that does not seem to be of too much use with a select * statement...)
You can affect this behaviour with PDOStatement::setFetchMode(). The constants starting with PDO::FETCH_ are applicable here. Their documentation can be found here
I have a table with a lot of data, so I retrieve it and display it one page at a time (my request is lengthy so there is no way I run it on the entire table).
But I would like to paginate the results, so I need to know what is the total number of elements in my table.
If I perform a COUNT(*) in the same request, I get the number of selected elements (in my case, 10).
If I perform a COUNT(*) on my table in a second request, the result might be wrong because of the where, join and having clauses in my main query.
What is the cleanest way to:
Retrieve the data
Know the maximum number of elements in my table for this specific request
One solution seems to be using the Mysql function FOUND_ROWS :
I tried this, as mysql_query performs one query at a time: (taken here)
$query = 'SELECT SQL_CALC_FOUND_ROWS * FROM Users';
$result = mysql_query($query);
// fetching the results ...
$query = 'SELECT FOUND_ROWS()';
$ result = mysql_query($query);
// debug
while ($row = mysql_fetch_row($result)) {
print_r($row);
}
And I got an array with 0 results:
Array ( [0] => 0 )
Whereas my query does returns results.
What is wrong with my approach ? Do you have a better solution ?
Set mysql.trace_mode to Off if it is On.
ini_set('mysql.trace_mode','Off'); may also work depending on your host configuration if you cannot edit my.cnf
If that doesn't make the code you posted above work, then you will need to run the query again without LIMIT and count it that way.
The code above works fine. I wasn't opening the connection correctly.
Output is :
Array ( [0] => 10976 )
I am still interested for an other way to do it, especially something that is not mysql dependent.
I have a simple mySQL database table that I am loading into a PHP array. I would like the id column of the mySQL table (which is auto incremented, but I don't think that's relevant) to be the array key for each element of the PHP array, instead of the array being numeric.
Instead of this:
Array(
Array(id=>'1', field1=>someval, field2=>val),
Array(id=>'2', field1=>val, field2=>otherval),
Array(id=>'4', field1=>val, field2=>otherval)
)
I want this:
Array(
1=>Array(field1=>someval, field2=>val),
2=>Array(field1=>val, field2=>otherval),
4=>Array(field1=>val, field2=>otherval)
)
I don't care if id is left in the associative array for each row.
Is there a way to do this without looping through the original mySQL array and using up lots of processing time?
You can do it at the fetch time like this:
$query_ret = mysql_query(...);
$result = array();
while ($row = mysql_fetch_assoc($query_ret)) {
$result[array_shift($row)] = $row;
}
"Is there a way to do this without looping through the original mySQL array and using up lots of processing time?"
I believe the answer to this is no. The best you can do is to try to be as efficient as possible when looping through the array.
If you have PDO, you should definitely see Example #3 from the PDO documentation for fetchall: http://www.php.net/manual/en/pdostatement.fetchall.php#example-1022
Not only is this way more efficient use of your server's memory and processing power... it would also enable you to take advantage of several of PDO's other powerful APIs.