How to sum result of query - php

I have one query where the output processing looks like this:
while($row = mysql_fetch_array($result)){
echo $row['username'] . " " . $row['earning'];
}
And outputs result is like this:
JOHN 200
JOHN 350
NEO 100
NEO 220
What I want to achieve is that every name appears once, and "earning" is sum of all earnings of that name, like this:
JOHN 550
NEO 320
I have to mention that I CANNOT change the query; that is biggest problem.
Is there any hope? Some suggestions? :)

You can sum the values in the loop to another array and then output it.
Try:
$earnings = array();
while($row = mysql_fetch_array($result)) {
if (!isset($earnings[$row['username']])) $earnings[$row['username']] = 0;
$earnings[$row['username']] += $row['earning'];
}
foreach($earnings as $user => $earnings) {
echo "$user $earnings<br />\n";
}

try:
$user = array();
while($row = mysql_fetch_array($result)){
$user[$row['username']] += $row['earning'];
}
to do echo :
foreach($user as $key => $value) {
echo $key."=". $earnings."<br>";
}

To get a quick solution to this answer you may want to simply append these results to an associated array and then simply loop over it to get the final count.
So, something like this:
$names= array();
while($row = mysql_fetch_array($result)){
$names[$row["username"]] += $row["earning"];
}
foreach($names as $k => $v) {
echo $k." ".$v."\n";
}

Instead of just selecting the data, select the field and SUM(otherfield) with otherfield being the field with the number to be summed. Then add GROUP BY with the first field.

try this in mysql side you don't need to calculate in php side so don't change your PHP side code jst change query like this
SELECT
username,
SUM(earning)
FROM yourtable
GROUP BY (username)
hope its will work for you

Related

cannot retrieve indexes correctly mysqli

$search = htmlspecialchars($_GET["s"]);
if(isset($_GET['s'])) {
// id index exists
$wordarray = explode(" ",$search);
$stringsearch = implode('%',$wordarray);
echo $stringsearch;
echo ",";
$result = mysqli_fetch_array($conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%';"));
if (!empty($result)) {
echo sizeof($result);
echo ",";
Database has 3 rows with titles test,pest,nest with corresponding id's 1,2,3. when i request domain.com/?s=est
it echos something like this
est,2,
Now when i checked $result[0] and $result[1], $result[0] echoed 1 and $result[1] didn't echo anything. When I use foreach function, it is taking only value of $result[0]
and $result should be array of all the three indexes.
I cannot find any mistake,
when i type the same command in sql console it works, somebody help me, thanks in advance.
The problem is, if you're expecting multiple rows, then don't do this:
$result = mysqli_fetch_array($conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%';"));
This only fetches the first row, you need to loop it to advance the next pointer and get the next following row set:
$result = $conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%' ");
while($row = $result->fetch_array()) {
echo $row[0] . '<br/>';
// or $row['ID'];
}
Sidenote: Consider using prepared statements instead, since mysqli already supports this.

MySQL Row in one output

Im pretty new to MySQl and PHP. I need some help with a small issue.
My statement is as follows:
while($row = $stmt->fetch()) {
$return_arr[] = $row['name'];
$return_arr[] = $row['value'];
}
It outputs as follows:
Mr James Jones
23
How can I bring it together into one line? Like this:
Mr James Jones 23
Thank you
Use implode to join the array elements:
echo implode(' ', $return_arr);
Do like this
while($row = $stmt->fetch()) {
$return_arr[] = $row['name']." ".$row['value'];
}
//print_r($return_arr); // The results gets printed as you expected or you could make use of a foreach construct as shown below.
//Printing using a foreach construct
foreach($return_arr as $k=>$v)
{
echo $v;echo "<br>";
}
Just use like this,
while($row = $stmt->fetch()) {
$return_arr[] = $row['name']. ' '.$row['value'];
}
it will work.
And if you want any other help let me know.
An alternate way is handling it inside your mysql query:
SELECT CONCAT(name, ' ', value) as name_and_value FROM ....
Than you can use
$row['name_and_value']
in your php code.

Passing the values of mysql_fetch_array to an Array()?

this is my code:
$scontain = "SELECT id FROM voting";
$qcontain = mysql_query($scontain);
$r_idarray = array();
while ($rcontain = mysql_fetch_array($qcontain))
{
$r_idarray[] = $rcontain['id'];
//let's say there are 5 names here//
}
echo $r_idarray;
I was trying to get the whole content of my table 'voting'. Inside the while loop it successfully prints out the whole content of the table which is under the column 'id' but when I tried to echo it outside the while loop it prints 'Array'? Can anyone knows how to solve this. Thank you in advance...
To print the array you can do:
print_r($r_idarray);
instead of
echo $r_idarray;
You have to use print_r($r_idarray) .
echo is used for printing strings.
use print_r for printing arrays.
Use print_r or var_dump for printing the array
Replace:
echo $r_idarray;
With:
print_r($r_idarray);
Or:
var_dump($r_idarray);
If you want to display whole content
SELECT id FROM voting
To
SELECT * FROM voting
And after that you can use print_r($r_idarray);
You can't "echo" an array, you can only "echo" a string. Of course you will see 'Array'.
In order to print out the contents of an array, you either have to iterate through it's contents, or do a "var_dump($array)".
while($val in $array){
echo $val;
}
or:
print_r($array);
or:
var_dump($array);
One thing youe query should be like this to select all columns
$scontain = "SELECT * FROM voting";
You only have to do this
$i=0;
while ($rcontain = mysql_fetch_array($qcontain))
{
$r_idarray[$i] = $rcontain;
$i++;
}
echo '<pre>';
print_r($r_idarray);
And if you need particular columns from result
$i=0;
while ($rcontain = mysql_fetch_array($qcontain))
{
$r_idarray[$i]['id'] = $rcontain['id'];
$r_idarray[$i]['column1'] = $rcontain['column1'];
$r_idarray[$i]['column2'] = $rcontain['column2'];
$r_idarray[$i]['column3'] = $rcontain['column3'];
$i++;
}
echo '<pre>';
print_r($r_idarray);

MYSQL - Select specific value from a fetched array

I have a small problem and since I am very new to all this stuff, I was not successful on googling it, because I dont know the exact definitions for what I am looking for.
I have got a very simple database and I am getting all rows by this:
while($row = mysql_fetch_array($result)){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
Now, my question is: how do I filter the 2nd result? I thought something like this could work, but it doesnt:
$name2= $row['name'][2];
Is it even possible? Or do I have to write another mysql query (something like SELECT .. WHERE id = "2") to get the name value in the second row?
What I am trying to is following:
-get all data from the database (with the "while loop"), but than individually display certain results on my page. For instance echo("name in second row") and echo("id of first row") and so on.
If you would rather work with a full set of results instead of looping through them only once, you can put the whole result set to an array:
$row = array();
while( $row[] = mysql_fetch_array( $result ) );
Now you can access individual records using the first index, for example the name field of the second row is in $row[ 2 ][ 'name' ].
$result = mysql_query("SELECT * FROM ... WHERE 1=1");
while($row = mysql_fetch_array($result)){
/*This will loop arround all the Table*/
if($row['id'] == 2){
/*You can filtere here*/
}
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
$counter = 0;
while($row = mysql_fetch_array($result)){
$counter++;
if($counter == 2){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
}
This While loop will automatically fetch all the records from the database.If you want to get any other field then you will only need to use for this.
Depends on what you want to do. mysql_fetch_array() fetches the current row to which the resource pointer is pointing right now. This means that you don't have $row['name'][2]; at all. On each iteration of the while loop you have all the columns from your query in the $row array, you don't get all rows from the query in the array at once. If you need just this one row, then yes - add a WHERE clause to the query, don't retrieve the other rows if you don't need them. If you need all rows, but you wanna do something special when you get the second row, then you have to add a counter that checks which row you are currently working with. I.e.:
$count = 0;
while($row = mysql_fetch_array($result)){
if(++$count == 2)
{
//do stuff
}
}
Yes, ideally you have to write another sql query to filter your results. If you had :
SELECT * FROM Employes
then you can filter it with :
SELECT * FROM Employes WHERE Name="Paul";
if you want every names that start with a P, you can achieve this with :
SELECT * FROM Employes WHERE Name LIKE "P%";
The main reason to use a sql query to filter your data is that the database manager systems like MySQL/MSSQL/Oracle/etc are highly optimized and they're way faster than a server-side condition block in PHP.
If you want to be able to use 2 consecutive results in one loop, you can store the results of the first loop, and then loop through.
$initial = true;
$storedId = '';
while($row = mysql_fetch_array($result)) {
$storedId = $row['id'];
if($initial) {
$initial = false;
continue;
}
echo $storedId . $row['name'];
}
This only works for consecutive things though.Please excuse the syntax errors, i haven't programmed in PHP for a very long time...
If you always want the second row, no matter how many rows you have in the database you should modify your query thus:
SELECT * FROM theTable LIMIT 1, 1;
See: http://dev.mysql.com/doc/refman/5.5/en/select.html
I used the code from the answer and slightly modified it. Thought I would share.
$result = mysql_query( "SELECT name FROM category;", db_connect() );
$myrow = array();
while ($myrow[] = mysql_fetch_array( $result, MYSQLI_ASSOC )) {}
$num = mysql_num_rows($result);
Example usage
echo "You're viewing " . $myrow[$view_cat]['name'] . "from a total of " . $num;

Print mysql results column by column

I feel incredibly stupid for not being able to figure this out, but I guess that's what Stackoverflow is for. If someone could point me to helpful resources or explain to me how to solve this, I would be very appreciative.
Basically I'm fetching a couple of rows from a table, and now I need to be able to print them out the value of each row's field, followed by the values of each row from a different field, and so on. It's hard to explain, but let me give you an example.
Let's say we have a table with three fields: id - name - url. Now I want to be able to output the result in this order:
1
2
3
John
Steven
Patrick
http://google.com/
http://stackoverflow.com/
http://php.net/
How do I loop through the results of my query in order to achieve this?
Well you should make an array and then spew it out:
$ids = array();
$names = array();
$urls = array();
while($row = ...){
$ids[] = $row['id'];
$names[] = $row['name'];
$urls[] = $row['url'];
}
foreach($ids as $id) {
echo $id . PHP_EOL;
}
//do the same for the other 2
You can do this via union. The only tricky part is making sure to cast all of the fields to a common data type (in this case, text). Also, each subquery is ordered by id to make sure that the ordering is consistent.
select id::text
from table
order by id
union
select name::text
from table
order by id
union
select url::text
from table
order by id
$result = mysql_query("SELECT id, name, url FROM yourtable") or die(mysql_error());
$data = array()
while($row = mysql_fetch_asssoc($result)) {
$data[] = $row;
}
foreach(array('id', 'name', 'url') as $key) {
foreach($data as $idx => $val) {
echo $val[$key], "\n";
}
}
The simplest way is
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$ids[] = $row['id'];
$names[] = $row['names'];
$wwws[] = $row['website'];
}
Then you iterate over the three arrays. There are surely better methods for doing this!

Categories