I'm trying to store a number of percentages that I've worked out into an array so that I can call it later on to create a pie chart but don't have a clue how to do it. Here is my PHP code so far for working out the percentages: Thanks for any help in advance!
//execute the SQL query and return records
$result = mysql_query("SELECT book_id, COUNT(*) FROM loan GROUP BY book_id ASC ORDER BY count(*) DESC LIMIT 10");
$book_count = mysql_num_rows($result);
$step = 1;
while($row = mysql_fetch_array($result))
{
$total = $total + $row['COUNT(*)'];
$i[$step] = $row['COUNT(*)'];
$step++;
}
for($index = 1; $index <= 10; $index++)
{
$percentage[$index] = (($i[$index]/$total)*100);
#$degrees = (($percentage/100)*360);
}
This should do what you're asking, just substitute the variables for real ones:
array_push($array, $value);
// This will add "$value" on to the end of $array, i.e the last element
It can also be done much simpler:
$array[] = $value;
Updated code:
//execute the SQL query and return records
$result = mysql_query("SELECT book_id, COUNT(*) FROM loan GROUP BY book_id ASC ORDER BY count(*) DESC LIMIT 10");
$book_count = mysql_num_rows($result);
$step = 1;
while($row = mysql_fetch_array($result))
{
$total = $total + $row['COUNT(*)'];
$i[$step] = $row['COUNT(*)'];
$step++;
}
$percentage_array = array();
for($index = 1; $index <= 10; $index++)
{
array_push($percentage_array, (($i[$index]/$total)*100));
#$degrees = (($percentage/100)*360);
}
Related
Looking for some help if possible.
$pilotsids is an array of ids.
merged is the table that holds the data.
For each pilotid, I'd like to create an array of newrat values, which I am going to use later to populate a chart. The index of the for loop must be added to the name of each array like this:
$data0[]
$data1[]
$data2[]...etc
It works when I do it separately:
$result = $mysqli->query("select newrat from merged where pilotid = $pilotids[0] order by mid asc");
while($row = mysqli_fetch_assoc($result)) {
$data0[] = $row['newrat'];
}
$result = $mysqli->query("select newrat from merged where pilotid = '$pilotids[1]' order by mid asc");
while($row = mysqli_fetch_assoc($result)) {
$data1[] = $row['newrat'];
}
$result = $mysqli->query("select newrat from merged where pilotid = '$pilotids[2]' order by mid asc");
while($row = mysqli_fetch_assoc($result)) {
$data2[] = $row['newrat'];
}
It doesn't if I try to to iterate automatically for lets say 10 times:
for($i=0; $i < 10; $i++) {
$result = $mysqli->query("select newrat from merged where pilotid = $pilotids[$i] order by mid asc");
while($row = mysqli_fetch_assoc($result)) {
${$data.$i}[] = $row['newrat'];
}
}
You can try this way:
$data = [];
for($i=0; $i < 10; $i++) {
$result = $mysqli->query("select newrat from merged where pilotid = $pilotids[$i] order by mid asc");
while($row = mysqli_fetch_assoc($result)) {
$data[$i][] = $row['newrat'];
}
}
As you can see I'm using a two dimensional array which is defined outside of the loop.
I have a column in a table that I would like to add up and return the sum. I have a loop, but it's not working.
while ($row = mysql_fetch_assoc($result)){
$sum += $row['Value'];
}
echo $sum;
You can completely handle it in the MySQL query:
SELECT SUM(column_name) FROM table_name;
Using PDO (mysql_query is deprecated)
$stmt = $handler->prepare('SELECT SUM(value) AS value_sum FROM codes');
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$sum = $row['value_sum'];
Or using mysqli:
$result = mysqli_query($conn, 'SELECT SUM(value) AS value_sum FROM codes');
$row = mysqli_fetch_assoc($result);
$sum = $row['value_sum'];
$query = "SELECT * FROM tableName";
$query_run = mysql_query($query);
$qty= 0;
while ($num = mysql_fetch_assoc ($query_run)) {
$qty += $num['ColumnName'];
}
echo $qty;
Try this:
$sql = mysql_query("SELECT SUM(Value) as total FROM Codes");
$row = mysql_fetch_array($sql);
$sum = $row['total'];
Let us use the following image as an example for the data in our MySQL Database:
Now, as the question mentions, we need to find the sum of a particular column in a table. For example, let us add all the values of column "duration_sec" for the date '09-10-2018' and only status 'off'
For this condition, the following would be the sql query and code:
$sql_qry = "SELECT SUM(duration_sec) AS count
FROM tbl_npt
WHERE date='09-10-2018' AND status='off'";
$duration = $connection->query($sql_qry);
$record = $duration->fetch_array();
$total = $record['count'];
echo $total;
MySQL 5.6 (LAMP) . column_value is the column you want to add up. table_name is the table.
Method #1
$qry = "SELECT column_value AS count
FROM table_name ";
$res = $db->query($qry);
$total = 0;
while ($rec = $db->fetchAssoc($res)) {
$total += $rec['count'];
}
echo "Total: " . $total . "\n";
Method #2
$qry = "SELECT SUM(column_value) AS count
FROM table_name ";
$res = $db->query($qry);
$total = 0;
$rec = $db->fetchAssoc($res);
$total = $rec['count'];
echo "Total: " . $total . "\n";
Method #3 -SQLi
$qry = "SELECT SUM(column_value) AS count
FROM table_name ";
$res = $conn->query($sql);
$total = 0;
$rec = row = $res->fetch_assoc();
$total = $rec['count'];
echo "Total: " . $total . "\n";
Method #4: Depreciated (don't use)
$res = mysql_query('SELECT SUM(column_value) AS count FROM table_name');
$row = mysql_fetch_assoc($res);
$sum = $row['count'];
$row['Value'] is probably a string. Try using intval($row['Value']).
Also, make sure you set $sum = 0 before the loop.
Or, better yet, add SUM(Value) AS Val_Sum to your SQL query.
$result=mysql_query("SELECT SUM(column) AS total_value FROM table name WHERE column='value'");
$result=mysql_result($result,0,0);
Get Sum Of particular row value using PHP MYSQL
"SELECT SUM(filed_name) from table_name"
$sql = "SELECT SUM(Value) FROM Codes";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
sum = $row['SUM(price)'];
}
echo sum;
$q = mysql_query("SELECT * FROM users WHERE ID=".$_SESSION['user_id']."");
while($row = mysql_fetch_array($q)) {
$array = (explode(":",$row['recent_views']));
for ($i = 1; $i < count($array); ++$i) {
$userids = $array[$i].',';
$q2 = mysql_query("SELECT * FROM item WHERE approved = 1 AND id IN(".$userids."0)");
echo $userids;
//NOTE: my echo is spitting out "18622,44968,44968," but when using $userids in mysql query it doesn't include the full list of numbers
}
}
I put }'s after mysql query to try to include variable in the for loop, if i close brackets before query $userids only prints last number from array.
Close the parenthesis before your query and use concatenation instead of re-assigning $userids on each iteration:
$q = mysql_query("SELECT * FROM users WHERE ID=".$_SESSION['user_id']."");
while($row = mysql_fetch_array($q)) {
$array = (explode(":",$row['recent_views']));
for ($i = 1; $i < count($array); ++$i) {
$userids .= $array[$i].',';
// ^ missing the period here
}
}
$q2 = mysql_query("SELECT * FROM item LEFT JOIN subcategory
ON item.subcategory_id=subcategory.subcategory_id LEFT JOIN genre ON item.genre_id=genre.genre_id WHERE approved = 1 AND broken = 0 AND id IN(".$userids."0)");
echo $userids;
You could also just get rid of the for-loop and use implode():
while($row = mysql_fetch_array($q)) {
$array = (explode(":",$row['recent_views']));
$userids .= implode(',', $array) + ',';
}
While this may fix the issue, know that this isn't very efficient nor maintainable. It would make more sense to use SQL JOIN syntax to combine a user's recent views with the sub-categories all in one query.
This code works:
$row = array(5,6,89,97,101);
$found = array();
$post = 89;
$count_row = count($row);
for($i = 0; $i < $count_row; $i++){
if($row[$i]==$post){
$found[] = $row[$i-2];
$found[] = $row[$i-1];
$found[] = $row[$i];
$found[] = $row[$i+1];
$found[] = $row[$i+2];
var_dump($found);
}
}
And this does not, probably doing something wrong in the mysql_fetch_array;
$found = array();
$q = "SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id='$term_tax_id'";
$rs = mysql_query($q) or die(mysql_error());
$row = mysql_fetch_array($rs, MYSQL_NUM);
$count_row = count($row);
for($i = 0; $i < $count_row; $i++){
print_r($row);
if($row[$i]==$post){
$found[] = $row[$i-2];
$found[] = $row[$i-1];
$found[] = $row[$i];
$found[] = $row[$i+1];
$found[] = $row[$i+2];
var_dump($found);
}
}
Nothing is shown if post is more than 1.
Anyone know a way to solve this problem?
mysql_fetch_array() fetches one single row, which, in your case, contains exactly one column.
You should either query all rows from the result set at once (which I don't know how that works), or you should do this:
$q = "SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id='$term_tax_id'";
$rs = mysql_query($q) or die(mysql_error());
$data = array();
while ($row = mysql_fetch_array($rs, MYSQL_NUM)) {
$data[] = $row[0];
}
for($i = 2; $i < count($data) - 2; $i++){ // adjusted boundaries
if($data[$i]==$post){
$found[] = $data[$i-2];
$found[] = $data[$i-1];
$found[] = $data[$i];
$found[] = $data[$i+1];
$found[] = $data[$i+2];
var_dump($found);
}
}
}
I as well have adjusted the boundaries: if you are interested in the range $i-2 to $i+2, you only should run from 2 to end-2.
The select statement should be rewritten so as to return only the values you're looking for. One way to do this is with a UNION of two selects, one returning lesser object IDs and one returning greater. You should also make use of WordPress's wpdb class. For one thing, a site admin may change the table prefix from "wp_" to something else; $wpdb->term_relationships will give the correct name for the table.
$statement = $wpdb->prepare(
" (SELECT object_id
FROM $wpdb->term_relationships
WHERE term_taxonomy_id= %d
AND object_id <= %d
ORDER BY object_id DESC
LIMIT 3)
UNION
(SELECT object_id
FROM $wpdb->term_relationships
WHERE term_taxonomy_id= %d
AND object_id > %d
ORDER BY object_id ASC
LIMIT 2)
ORDER BY object_id", $term_tax_id, $post, $term_tax_id, $post);
$found = $wpdb->get_results($statement);
This also has the advantage of working when there are less than two terms relationships before or after the center (the object with id $post).
I have a db table which have a row of a product amount. I want to create a loop that will calculate for me the sum for all the amounts.
$results = mysql_query("SELECT *
FROM prod");
while($info = mysql_fetch_array($results)) {
$amount = $info['amount'];
}
amount is the var for each product cost. I want to get a sum for all the vars together - how can I do it?
Use the SUM() function in a SQL query.
$result = mysql_query("SELECT SUM(amount) AS sum_amount FROM prod");
if ( $result )
$sum = mysql_result($result, 0, 0);
Easier to do in MySQL:
SELECT SUM(amount) FROM prod
Then fetch the result.
First:
You can do this with mysql
SELECT SUM(amount) FROM ....
Second:
while ($info = mysql_fetch_array($results)) {
$amount[] = $info['amount'];
}
$sum = array_sum($amount);
You can add the amounts to a variable:
$results = mysql_query("select * from prod");
$sum = 0
while($info = mysql_fetch_array($results)) {
$amount = $info['amount'];
$sum += $amount
}
Or you can do it in SQL:
SELECT SUM(column) FROM table