I have a database table with two fields both id and value and I'd like to add the two entries for value together and then echo out the total of the sum.
So far I've been able to display both entries for value by using the following.
function showTotal() {
global $connection;
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);
if (!$result) {
die('Query FAILED' . mysqli_error());
} else if (isset($failed)) {
echo "Failed";
}
while ($row = mysqli_fetch_assoc($result)) {
$value = $row['value'];
echo "$value";
}
}
What I really want is these values added together rather than displaying alongside each other.
Thanks
James
I haven't tested it, but something like this could potentially be a one-liner.
echo array_sum( array_column( mysqli_fetch_all( $result, MYSQLI_ASSOC), 'value' ) );
That said, if you do not need all the results, this is a better option:
$result = mysqli_query( 'SELECT SUM(value) AS mysum FROM table' );
echo mysqli_fetch_array($result, MYSQLI_ASSOC)['mysum'];
Using php you could sum up the values like so:
$value = 0;
while ($row = mysqli_fetch_assoc($result)) {
$value += $row['value'];
}
echo $value;
While I personally would opt to go with the solution offered by #jm, PHP does offer another way with its array_sum(), as follows:
<?php
$value = 0;
while ($row[] = mysqli_fetch_assoc($result)) {}
echo array_sum($row['value']);
See Manual
Note: you could change the fetching of the result by using mysqli_fetch_all, if you have the MySQL native driver; see here.
Related
I have a polymer(1.0) app i am trying to create (based on stretch-tutorials league table), i cant figure out the routing if use mvc, so i have opted for the one page site, referencing different php files.
I Have a table in MYSql that i trying to incorporate into the table, using a simple echo table script, but this repeats itself hundreds of times. How can i stop this loop ?
$result = mysql_query('select * from results',$connection) or die('cannot show tables');
while($tableName = mysql_fetch_row($result)) {
$sql = ('SELECT `home_team_name`,`away_team_name`,`home_goals_for`, `away_goals_for`, DATE_FORMAT(`fixture_date`, "%e %M %Y"), TIME_FORMAT(`fixture_time`, "%h:%i %p") FROM `results` ORDER BY fixture_date desc LIMIT 20 '.$table) or die('cannot show columns from '.$table);
echo '<h3>',$table,'</h3>';
$result2 = mysql_query($sql);
if(mysql_num_rows($result2)) {
echo '<table cellpadding="4" cellspacing="0" class="table table-striped table-hover table-bordered">';
echo '<tr class="info"><th>Home team</th><th>Away Team</th><th>Score</th><th>Score</th><th>Date<th>Time</th></tr>';
while($row2 = mysql_fetch_row($result2)) {
echo '<tr>';
foreach($row2 as $key=>$value) {
echo '<td>',$value,'</td>';
}
echo '</tr>';
}
echo '</table><br />';
}
}
I have added ' < 50 ' but this returns 50 table header rows only ?
the site is live at http://jay-o.uk/#!/results the css and other data are okay for now, just this pesky loop.
Well.. maybe you need this code:
// Create an array
$items = array();
while ($row = mysql_fetch_array($resulting, MYSQL_ASSOC)) {
/* print new insert */
var_dump('new item');
/* add a new item */
$items[] = array(
'home_team_name' => $row['home_team_name'],
'away_team_name' => $row['away_team_name'],
'home_goals_for' => $row['home_goals_for'],
'away_goals_for' => $row['away_goals_for']
);
}
$json_response = json_encode($items);
print $json_response;
If $json_response are a empty array maybe the problem is that the query don't return any row.
You need to set a "LIMIT" in the first query if you want to avoid a timeout operation, also i think that is posible to call a unique query that return all the info that you need but i don't know because your query is unintelligible.
Your code is wrong, the second query don't use the $table variable that is null value and what is de purpose to putting it after the limit parameter?
$results = mysql_query('SELECT * FROM table_name ORDER BY field_name LIMIT 50');
if(mysql_num_rows($results)) {
print '<table>';
while ($row = mysql_fetch_row($results)) {
print '<tr>';
foreach ($row as $field_name => $field_value) print '<td>'.$field_value.'</td>';
print '</tr>'
}
print '</table>';
}
Sorry, the code is a bit messy, ive been working on this for a while and ifs frustrating, im not sure where i am going wrong, if i remove the $tableName variable i get an empty array, no matter what i do this is the results.
I have tried in json to no avail...
$db = mysql_connect($host,$user,$pass);
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db($db_name,$db);
$resulting = mysql_query("select * from results", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($resulting, MYSQL_ASSOC)) {
$row_array['home_team_name'] = $row['home_team_name'];
$row_array['away_team_name'] = $row['away_team_name'];
$row_array['home_goals_for'] = $row['home_goals_for'];
$row_array['away_goals_for'] = $row['away_goals_for'];
//push the values in the array
array_push($json_response,$row_array);
$json = json_encode($json_response);
//echo $json;
$json_result = print_r((array) json_decode($json,true));
echo $json_result;
}
which leaves this: jay-o.uk/config/config.php
Could this be because i am referring to a view in mySql rather than a table ?
How about a simpler solution, just limit the query from the database to 1:
$results = mysql_query('SELECT * FROM table_name ORDER BY field_name LIMIT 1');
$result = mysql_query("SELECT * FROM Race");
$rows = mysql_num_rows($result);
for ($i = 0 ; $i < $rows ; ++$i)
{
$row = mysql_fetch_row($result);
echo $row[0];
}
above is probably an awkward method but it'll print out all datas stored in first column, which is good but now, I want to store each one of them into an array...
I tried
$array[$i]=$row[0];
and echoed it out, but it just prints"Array"...
I tried
$result = mysql_query("SELECT raceid FROM Race");
while ($row = mysql_fetch_array($result)) {
$array[]=$row[0];
}
...which does the same as code written before, i guess, since it too just print "Array".
Please help! Thank you!!
Do you use simple echo $array;? It's wrong. You can't output array this way.
Use this:
$array = array();
$result = mysql_query("SELECT raceid FROM Race");
while ($row = mysql_fetch_array($result)) {
$array[]=$row[0];
}
foreach($item in $array) {
echo $item."<br>"; // and more format
}
If you want to watch array contents without any format use (e.g. for debugging) print_r or var_dump:
print_r($array);
var_dump($array);
Advice: better to use assoc array.
$array = array();
$result = mysql_query("SELECT raceid FROM Race");
while ($row = mysql_fetch_array($result)) {
$array[]=$row['raceid'];
}
Advanced advice: better to use PDO and object results.
You SQL code will be invulnerable to SQL injections
Code will be more modern and readable.
I am querying a database to get 6 values in my params table suing this;
$result = mysql_query("SELECT * FROM params");
while($row = mysql_fetch_array($result))
{
$param = $row['value'] ;
}
is this right, if so is their away i can add one to the variable name each time round so i get $param1, $param2....
I dont want to have to send a query to the database for each param, is it possible to get them all like this?
The simpliest way is to use an array:
$result = mysql_query("SELECT * FROM params");
$param = array();
$i = 0;
while($row = mysql_fetch_array($result)) {
$param[$i] = $row['value'] ;
$i++;
}
Than you get $param[0], $param[1], ...
You can create variable names like this:
${'var'.1}
${'var'.'1.cat'}
${'var'.$x}
${$y.$x}
and so on.
This seems like a design flaw. But what you can do is:
$count = 1;
$result = mysql_query("SELECT * FROM params");
while($row = mysql_fetch_array($result))
{
$paramname = 'param' . $count++;
$$paramname = $row['value'] ;
}
You may find the list function useful - http://php.net/manual/en/function.list.php
list($param1,$param2,$param3,$param4,$param5,$param6) = mysql_fetch_row($result);
Probably more use when using descriptive variables, just a thought.
It must be Monday, the heat or me being stupid (prob the latter), but for the life of me I cannot get a simple php function to work.
I have a simple query
$sql = mysql_query("SELECT * FROM table WHERE field_name = '$input'");
Which I want to run through a function: say:
function functionname($input){
global $field1;
global $field2;
$sql = mysql_query("SELECT * FROM table WHERE field_name = '$input'");
while($row = mysql_fetch_array($sql)) :
$field1[] = $row['field1'];
$field2[] = $row['field2'];
endwhile;
mysql_free_result($sql);
}
So that I can call the function in numerious places with differeing "inputs". Then loop through the results with a foreach loop.
Works fine the first time the function is called, but always gives errors there after.
As said "It must be Monday, the heat or me being stupid (prob the latter)".
Suggestions please as I really only want 1 function to call rather than rewrite the query each and every time.
This is the error message
Fatal error: [] operator not supported for strings in C:\xampp\htdocs\functions.php on line 270
function functionname($input){
$sql = mysql_query("SELECT field1,field2 FROM table WHERE field_name = '$input'");
$result = array('field1' => array()
'field2' => array()
);
while($row = mysql_fetch_array($sql)) :
$result['field1'][] = $row['field1'];
$result['field2'][] = $row['field2'];
endwhile;
mysql_free_result($sql);
return $result;
}
it seems that somewhere the $field1 or $field2 are converted to strings and you cant apply the [] to a string...
i'd say that you have to do:
$field1 = array();
$field2 = array();
before the WHILE loop
The problem is that you so called arrays are strings!
global $field1;
global $field2;
var_dump($feild1,$feild2); //Will tell you that there strings
Read the error properly !
[] operator not supported for strings
And the only place your using the [] is withing the $feild - X values
GLOBAL must work because the error is telling you a data-type, i.e string so they must have been imported into scope.
another thing, why you selecting all columns when your only using 2 of them, change your query to so:
$sql = mysql_query("SELECT feild1,feild2 FROM table WHERE field_name = '$input'");
another thing is that your using mysql_fetch_array witch returns an integer indexed array, where as you want mysql_fetch_assoc to get the keys.
while($row = mysql_fetch_assoc($sql)) :
$field1[] = $row['field1'];
$field2[] = $row['field2'];
endwhile;
What I would do
function SomeFunction($variable,&$array_a,&$array_b)
{
$sql = mysql_query("SELECT field1,field2 FROM table WHERE field_name = '$variable'");
while($row = mysql_fetch_assoc($sql))
{
$array_a[] = $row['field1'];
$array_b[] = $row['field2'];
}
mysql_free_result($sql);
}
Then use like so.
$a = array();
$b = array();
SomeFunction('Hello World',&$a,&$b);
In my opinion, it's pretty unusual and even useless approach at all.
This function is too localized.
To make a general purpose function would be a way better.
<?
function dbgetarr(){
$a = array();
$query = array_shift($args);
foreach ($args as $key => $val) {
$args[$key] = "'".mysql_real_escape_string($val)."'";
}
$query = vsprintf($query, $args);
$res = mysql_query($query);
if (!$res) {
trigger_error("dbgetarr: ".mysql_error()." in ".$query);
return FALSE;
} else {
while($row = mysql_fetch_assoc($res)) $a[]=$row;
}
return $a;
}
and then call it like this
$data = dbgetarr("SELECT field1,field2 FROM table WHERE field_name = %s",$input);
foreach ($data as $row) {
echo $row['field1']." ".$row['field1']."<br>\n";
}
To understand your issue, we need the error, however, are you sure you are going about this in the right way?
Why do you need to call the function multiple times if you are just changing the value of the input field?
You could improve your SQL statement to return the complete result set that you need the first time.. i.e. SELECT * FROM table GROUP BY field_name;
Not sure if that approach works in your scenario, but in general you should aim to reduce the number of round trips to your database.
I don't know, i right or not. But i advise to try this:
function functionname($input){
global $field1;
global $field2;
$sql = mysql_query("SELECT * FROM `table` WHERE `field_name` = '" . $input . "'");
while($row = mysql_fetch_assoc($sql)) :
$field1[] = $row['field1'];
$field2[] = $row['field2'];
endwhile;
mysql_free_result($sql);
}
This code selects cell values in MySQL and manually adds them to PHP variables:
$sql = "SELECT * FROM table LIMIT 0,1";
$result = mysql_query($sql);
while($rows = mysql_fetch_array($result)) {
$col1 = $rows['col1'];
$col2 = $rows['col2'];
$col3 = $rows['col3'];
.....
}
This is obviously unmanageable for multiple and large tables.
What's a better way to automatically generate the variable names and values without manually entering all the column names on all tables?
I think this is what you're looking for
$sql = "SELECT * FROM table LIMIT 0,1";
$result = mysql_query($sql);
while ($rows = mysql_fetch_array($result, MYSQL_ASSOC)) {
foreach ($rows as $key => $value) {
$$key = $value;
}
}
You could use extract() for that. But I'd keep the values in the array.
..SELECT x,y,z FROM ..
while( false!==($rows=mysql_fetch_array($result, MYSQL_ASSOC)) ) {
extract($rows);
echo $x;
...
}
Wouldn't it be more convenient having associative arrays? That way you can call your variables with their column name as you describe plus you have the benefit of having them bundled in one unit which is much better if you need to pass more than one of them to any function or view or whatever.
so I would use mysql_fetch_assoc and that's it.
I don't recommend having a variable for each row, I used to do the same to simplify writing HTML later:
echo "<tr><td>$name</td><td>$count</td></tr>";
Instead of:
echo "<tr><td>{$row['name']}</td><td>{$row['count']}</td></tr>";
Until I found a better and more readable way do it using mysql_fetch_object
while ($row = mysql_fetch_object($result)) {
:
echo "<tr><td>{$row->name}</td><td>{$row->count}</td></tr>";
:
}
Use variable variables:
Code example:
$a = 'col1';
$$a = 'somevalue';
echo $col1;
will output 'somevalue'.
http://www.php.net/manual/en/language.variables.variable.php