PHP & MySQL - math and array problems - php

I'm trying to add all the values from the grade_points field for example 10, 12.5, 2.1 and then divide it by how many times grade points where entered into the database for example 24.6 / 3.
I know that $total_rating_points is an array but I don't really know how to convert the array so I can add the total grade points and then divide it by how many times points where entered. I was hoping if someone can help me out with this problem? That I have been working on forever.
Here is the code I'm having trouble on.
$sql2 = "SELECT grade_points
FROM grades
JOIN articles_grades ON grades.id = articles_grades.grade_id
WHERE articles_grades.users_articles_id = '$page'";
$result = mysqli_query($dbc,$sql2);
if (!mysqli_query($dbc, $sql2)) {
print mysqli_error($dbc);
return;
}
$total_rating_points = mysqli_fetch_array($result);
if (!empty($total_rating_points) && !empty($total_ratings)){
$avg = (round($total_rating_points / $total_ratings,1));
$votes = $total_ratings;
echo $avg . "/10 (" . $votes . " votes cast)";
} else {
echo '(no votes cast)';
}
Here is the full code I'm working on.
function getRatingText(){
$dbc = mysqli_connect ("localhost", "root", "", "sitename");
$page = '3';
$sql1 = "SELECT COUNT(users_articles_id)
FROM articles_grades
WHERE users_articles_id = '$page'";
$result = mysqli_query($dbc,$sql1);
if (!mysqli_query($dbc, $sql1)) {
print mysqli_error($dbc);
return;
}
$total_ratings = mysqli_fetch_array($result);
$sql2 = "SELECT grade_points
FROM grades
JOIN articles_grades ON grades.id = articles_grades.grade_id
WHERE articles_grades.users_articles_id = '$page'";
$result = mysqli_query($dbc,$sql2);
if (!mysqli_query($dbc, $sql2)) {
print mysqli_error($dbc);
return;
}
$total_rating_points = mysqli_fetch_array($result);
if (!empty($total_rating_points) && !empty($total_ratings)){
$avg = (round($total_rating_points / $total_ratings,1));
$votes = $total_ratings;
echo $avg . "/10 (" . $votes . " votes cast)";
} else {
echo '(no votes cast)';
}
}

To start off, you need to grab ALL of the values from your query. PHP's library only returns results one row at a time so you need to loop over it and continue to get results until you have them all. So do this:
$resource = mysqli_query($statement);
while ($result = mysql_fetch_array($resource))
{
$total_results_points[] = $result[0];
}
From there, summing and averaging the array in PHP should be fairly simple:
$average = array_sum($total_rating_points) / count($total_rating_points)
In a nutshell, the array_sum() function returns all the elements in an array added together. The count() function tells you how many elements are in the array. So using the two, you can obtain the mean of the array quite easily.

Or you could just go:
SELECT AVG(grade_points)
FROM grades
JOIN articles_grades ON grades.id = articles_grades.grade_id
WHERE articles_grades.users_articles_id = '$page'
One call to mysql_fetch_array will return the only row returned by this statement, an array with one element, there's your average.

When you're confused about what's in an array you can use
print_r($total_rating_points);
To see what's in the array.
EDIT: Responding to comment
You have to use a while. mysqli_fetch_array retrieves a row, not all rows. So something like this would be in order:
$total_rating_points = array();
while ($rating_row = mysqli_fetch_array($result))
{
$total_rating_points[] = $rating_row[0]; //0 might be the wrong index depending on the actual query.
}
print_r($total_rating_points);
You can then use array functions like sum and count as mentioned in some of the other solutions.

Related

Using mysql_fetch_assoc and updating each record

Some of my rows have a "," comma as the initial character in the field. So I need to loop through, check if each row has the initial commma, remove it if it does, and update the row.
I am running the following code, which seems to go on an endless loop when the update is called.
When I am just echoing out the result at the end, everything looks fine in the browser. But on execution of the update line below the echo, it seems as if a single datum from the column "Tags" is being populated for every record, instead of just the rows that have the initial commma that I am removing.
Would love help :)
$query = mysql_query("SELECT Tags FROM products")
or die (mysql_error());
while ($row = mysql_fetch_assoc($query))
{
$str = $row['Tags'];
$initial = substr($str,0,1);
if ($initial = ",") {
$str = (ltrim($str, ','));
}
echo "result: " .$str . "<br/>";
$result = "UPDATE products SET Tags = '" .$str ."'";
mysql_query($result);
}
Thank you.
You should pass the particular row id to the one you're making changes to, by using a WHERE clause:
$query = mysql_query("SELECT Tags FROM products")
or die (mysql_error());
while ($row = mysql_fetch_assoc($query)) {
$str = $row['Tags'];
$initial = substr($str,0,1);
if ($initial == ",") {
// == not =
$str = (ltrim($str, ','));
}
$id = $row['id'];
echo "result: " .$str . "<br/>";
$result = "UPDATE products SET Tags = '$str' WHERE id = $id";
mysql_query($result);
}
By the way, if possible kindly change to the better extension which is mysqli or PDO instead.
You're if() statement has an error in it.
You're using one equal:
if($initial = ",") {
}
Instead of two for actual comparison:
if($initial == ",") {
}
Here is the complete code. Thank you everyone.
$query = mysql_query("SELECT ProductID, Tags FROM products")
or die (mysql_error());
while ($row = mysql_fetch_assoc($query)) {
$str = $row['Tags'];
$initial = substr($str,0,1);
if ($initial == ",") {
$str = (ltrim($str, ','));
$id = $row['ProductID'];
//echo $id . " ";
//echo $str . "<br/>";
$result = "UPDATE products SET Tags = '$str' WHERE ProductID = $id";
echo $result ."<br>";
mysql_query($result);
}
}
So grateful for the help. I will update to mysqlli also.

Creating json from sql query with an additional key/value pair using PHP

Disclaimer: I'm fairly new to php.
I am trying to create an array out of a query witch could return multiple results. Additionally, I am doing a distance calculation and adding that value to the array, creating a json string, then returning it to my javascript.
I can create the array with the data from the database, and insert the additional value into the array, and return it, but when I try with a query witch returns more than one result, I'm only getting the last result back, because the array is being over written. I've tried to the array_merge function, but I'm still only getting the last one back.
Here is what I have so far:
$positionquery = "select d.code, d.lon, d.lat from table1 as d where d.lon <> 0 and d.lat <> 0 and d.brand = 'THE_BRAND'";
$results = mysql_query($positionquery) or die ('Query Failed" ' . mysql_error());
if(mysql_num_rows($results) > 0){
while($row = mysql_fetch_assoc($results)){
$locations = $row;
$tempdistance = distance($lat, $lon, $locations['lat'], $locations['lon'], 'M');
if($tempdistance <= 150){
$secondquery = 'SELECT * FROM table1 as d left join table2 as p on p.dealer_name = d.dealer_name left join table3 as o on o.retailercode = d.cicode where d.cicode ="'.$locations['cicode'].'"';
$queryResults = mysql_query($secondquery) or die('Query Failed ' . mysql_error());
$tempArray = mysql_fetch_assoc($queryResults);
$tempArray['distance'] = $tempdistance;
$returnArray = array_merge($returnArray,$tempArray);
}
}
echo json_encode($returnArray);
}
Any help would be greatly appreciated.
You're not creating an array of results, you're overwriting the $returnArray variable with each row of the results. It should be:
$returnArray = array();
while ($row = mysql_fetch_assoc($results)) {
...
$returnArray[] = $tempArray;
}
echo json_encode($returnArray);

MYSQL order limit with PHP variable

This is my code below
$query = mysql_query("SELECT * FROM table ORDER BY id LIMIT 10");
while($f = mysql_fetch_array($query)){
$match = 0; //In reality it's an array search function which returns 1 on match
if($match == 1) {
echo"Show content!";
}
}
Im trying to make an list with 10 rows, and i have a function which uses "name" from table to run an search query with an array generated by twitter API. In example if i get 3 matching records, i still want to show a list with 10 rows but hide the matching elements from there.
At the moment the script hides the matching elements and shows 7 rows instead of 10.
That is what i need help with, cheers :)
Process the data you are getting from the twitter api, collect the data you need in an array and query the database afterwards.
Something like that:
<?php
$collectArray = array();
foreach ($twitterData as $index => $data) {
if ($someCriteria === TRUE) {
$collectArray[] = $data;
}
}
$implodedCollectArray = "'" . implode("', '", $collectArray) . "'";
$sql = "SELECT * FROM `table_name` WHERE `some_column` IN (" . $implodedCollectArray . ")";
$query = mysql_query($sql) or die(mysql_error());
while($f = mysql_fetch_array($query)){
echo $f['column'];
}
?>
reinitilize match variable as the code:
$query = mysql_query("SELECT * FROM table ORDER BY id LIMIT 10");
while($f = mysql_fetch_array($query)){
if($f['name']!='variable_name_twiter'){
$match = 1; //In reality it's an array search function which returns 1 on match
}
if($match == 1) {
echo"Show content!";
}
$match = 0;
}

How to retrieve sum of a column in PHP

Hi I have a query in PHP that calculates the sum of all the values in a column. However when I try to print, nothing happens. I get a blank page. Im pretty sure its an obvious problem but constant coding means I cant think straight :(
$query = 'SELECT SUM(cost) AS total_price FROM items WHERE item_ID = $input';
$sum = mysql_query($query, $database);
$row = mysql_fetch_row($sum);
echo "Total "" = $". $row['total_price'];
mysql_fetch_row fetches a enumerated array, you want mysql_fetch_assoc.
Alternatively you can just use mysql_result to fetch the single field.
You also have a syntax error in your echo which would cause a blank page unless you have error_reporting/display_errors on:
echo "Total "" = $". $row['total_price'];
should be:
echo "Total = $". $row['total_price'];
Try this
$query = 'SELECT SUM(cost) AS total_price FROM items WHERE item_ID = $input';
$sum = mysql_query($query, $database) or die(mysql_error());
if(mysql_num_rows($sum) > 0) {
$row = mysql_fetch_assoc($sum);
echo 'Total = $'.$row['total_price'];
} else {
echo "No result found";
}

Use variable as ID and get table from mysql (edited)

I'm using a multiple select option form to get a table of venues. Each venue has an ID and this is what I used:
<?php
require("db_access.php");
if(isset($_POST['select3']))
{
$aVenues = $_POST['select3'];
if(!isset($aVenues))
{
echo("<p>You didn't select any venues!</p>\n");
}
else
{
$nVenues = count($aVenues);
echo("<p>You selected $nVenues venues: ");
for($i=0; $i < $nVenues; $i++)
{
echo($aVenues[$i] . " ");
}
echo("</p>");
$sql = "SELECT * FROM venues WHERE id IN (" . implode(",",$aVenues) . ")";
$comma_separated = implode(",", $aVenues);
echo $comma_separated;
}
}
?>
It results in this:
However I thought that the code would use those two numbers below and draw out a table with those id's I used :/ ? Am I missing something?
$array is used in implode(",", $array); but is not defined anywhere else that we can see. It is perhaps intended to be:
implode(",", $aVenues);
UPDATE
Per comments, it does not draw a table because you never actually query your database.
You build your SQL statement, but you need to execute it and fetch the result set.
// Make sure you actually have a database connection
$conn = mysql_connect('localhost', $username, $password);
mysql_select_db($database);
$sql = "SELECT * FROM venues WHERE id IN (" . implode(",",$aVenues) . ")";
$comma_separated = implode(",", $array);
echo $comma_separated;
// Execute query and fetch result rowset
$result = mysql_query($sql);
if ($result) {
$rowset = array();
while ($row = mysql_fetch_array($result)) {
$rowset[] = $row;
}
var_dump($rowset);
}
else echo mysql_error();

Categories