Add values from MySQL result together from array [duplicate] - php

This question already has answers here:
Get sum of MySQL column in PHP
(9 answers)
Closed 1 year ago.
I'm not sure if I'm overthinking this and being stupid but I'm trying to add all the values from my MySQL result.
Here is my code to fetch the values and store them in an array:
$query = "SELECT value FROM table";
$result = mysqli_query($dbcon, $query);
$array = array();
if(mysqli_num_rows($result) > 0 ){
while($row = mysqli_fetch_assoc($result)) {
$array[] = $row;
}
}
print_r($array);
Now I just need to figure out how I can add these values together and use this array for other things like working out the average. If there is an easier way to do this than storing the results in an array then please let me know.
Any help is much appreciated.

Managed to figure this out myself, I used the below code:
$query = "SELECT SUM(column) AS value_sum FROM table";
$result = mysqli_query($dbcon, $query);
$row = mysqli_fetch_assoc($result);
$sum = $row['value_sum'];
I guess I was overthinking it.

Related

How to display all table names in a database? [duplicate]

This question already has answers here:
Get table names using SELECT statement in MySQL
(14 answers)
Closed 2 years ago.
Im trying to echo out all table names in a specific database, but I can't find a working solution! Here is the code I have to far:
$sql = "SHOW TABLES FROM test";
$result1 = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result1);
if ($resultCheck > 0){
while ($row = mysqli_fetch_assoc($result1)){
echo $row;
}
}
Any help would be great!
The $row is coming as an array, so you have to fetch it as
echo $row['Tables_in_test']
First of all, be sure not to ask for a database outside of what the user you are using is able to see (Therefore, make sure that the user can see other databases).
One that is figured out, this is the code
$sql = "SHOW TABLES FROM test";
$result1 = $conn->query($sql);
while ($row = mysqli_fetch_assoc($result1)){
echo $row["Tables_in_test"];
}

Receiving an "Undefined index" notice when wanting to sum in a mysql query [duplicate]

This question already has answers here:
SELECT COUNT(*) AS count - How to use this count
(5 answers)
Closed 1 year ago.
I'm trying to get the sum of a column from my database. When I try this code I get the error Undefined index: sum(col_1). How can I do this? I'm a real beginner so keep it a bit simple.
$sql = "SELECT * FROM table_1";
$run = mysqli_query($conn, $sql);
while($rows = mysqli_fetch_assoc($run)){
$col_ans[1] = $rows['sum(col_1)'];
echo $col_ans[1];
}
You can easily find sum of a column this way.
$sql = "SELECT sum(col_1) as col_1_sum FROM table_1";
$run = mysqli_query($conn, $sql);
while($rows = mysqli_fetch_assoc($run)){
echo $rows['col_1_sum'];
}
Your problem is that you didn't use the SUM() function inside your query, so you won't get any sum from the query
You can also try the following:
$query = "SELECT productName, SUM(productQty) AS 'Products Ordered'
FROM ctrlaproducttab
GROUP BY productName
";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_assoc($result))
{
$productName = $row['productName'];
$itemsOrdered = $row['Products Ordered'];
}
Notice that we're giving an alias name Products Ordered to the result of expression SUM(productQty), and now we can use this alias name as an index in the associative array returned by mysqli_fetch_assoc()

MySql SUM not returning any results [duplicate]

This question already has answers here:
Get sum of MySQL column in PHP
(9 answers)
Closed 1 year ago.
I'm trying to get the sum off all the prize money from a column in a MySql table, but I'm not getting a result.
$result = mysqli_query("SELECT SUM(prize_money) FROM cards");
while ($rows = mysqli_fetch_array($result)) {
echo $rows['SUM(prize_money)'];
}
I just want to add all of the numbers in the prize_money column then echo the results.
Thank You
You should apply an alias to the SUM so it is easier to access in the PHP.
You then need to pass the connection string to the mysqli_query function as the first parameter.
So for example if your database connection were:
$con=mysqli_connect("localhost","my_user","my_password","my_db");
then you'd use this code to execute the query and assign the alias:
$result = mysqli_query($con, 'SELECT SUM(prize_money) AS sum_prize_money FROM cards');
$row = mysqli_fetch_assoc($result);
$sum = $row['sum_prize_money'];
echo $sum;
Do you get a result if you do this:
$result = mysqli_query("SELECT SUM(prize_money) FROM cards");
$rows = mysqli_fetch_array($result);
echo $rows
As good practice, you should learn to aliase your sql variables e.g. SUM(prize_money) AS total etc

Is there a way to access a row column via index and not name it?

The code I have is this
$sql = "SELECT * FROM user_buildings WHERE player_id = '$id'";
$result = mysqli_query($conn, $sql);
$amounts = array();
while ($row = $result->fetch_assoc()) {
$amounts[0] = $row['cursor_amount'];
$amounts[1] = $row['grandma_amount'];
}
However what I would like to be able to do is, instead of naming the column like I do here 'cursor_amount' and 'grandma_amount' is do the following:
$sql = "SELECT * FROM user_buildings WHERE player_id = '$id'";
$result = mysqli_query($conn, $sql);
$amounts = array();
while ($row = $result->fetch_assoc()) {
$amounts[0] = $row[0];
$amounts[1] = $row[1];
}
Although when I have tried to do this I've received the undefined offset error.
Any help would be greatly appreciated and yes I have tried looking for the answer already. I'm not exactly sure of the key terminology I need to make my searches more specific so if the answer for this does already exist I do apologise, feel free to post the link to the correct answer if that is the case instead of explaining it yourself.
Fetch the results with a different function:
$result->fetch_array(MYSQLI_NUM);

PHP - Select a unique mysql line without while [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 6 months ago.
I want to select only unique values with php/mysql.
I can do it with many line, but I forget how to do it without while... :)
Thanks a lot.
Here is the code that I want to do without while.
$request_1m = "SELECT date1, date2 from mytable";
$result_1m = mysql_query($request_1m,$db);
while($row = mysql_fetch_array($result_1m))
{
/* Get the data from the query result */
$date1_1m = $row["date1"];
$date2_1m = $row["date2"];
}
mysql_fetch_assoc + SELECT with DISTINCT
I'm not sure I understand your question, but here's what I think you want to do :
$request_1m = "SELECT date1, date2 from mytable";
$result_1m = mysql_query($request_1m,$db);
list($date1_1m, $date2_1m) = mysql_fetch_row($result_1m);
Note that this will only get the first row from the result set (just as if you LIMIT 1)
like this?
$dbresult = mysql_query("SELECT DISTINCT field FROM table");
$result = array();
while ($row = mysql_fetch_assoc($dbresult))
{
$result[] = $row;
}
This gets you all unique values from "field" in table "table".
If you really wish to avoid the while loop, you can use the PHP PDO objects, and in particular call the PDO fetchAll() method to retrieve the complete results array in one go. PDO fetchAll() documentation
$db = new PDO('dblib:host=your_hostname;otherparams...');
$db->query("SELECT DISTINCT col FROM table");
$results = $db->fetchAll();
// All your result rows are now in $results
Heres how I do it and Json encode after. This will ensure it will encode only UNIQUE json Values (Without duplicates) as an example
$tbl_nm = "POS_P";
$prod_cat = "prod_cat";
//Select from the POS_P Table the Unique Product Categories using the DISTINCT syntax
$sql = "SELECT DISTINCT $prod_cat FROM $tbl_nm";
//Store the SQL query into the products variable below.
$products = mysql_query($sql);
if ($products){
// Create an array
$rows = array();
// Fetch and populate array
while($row = mysql_fetch_assoc($products)) {
$rows[]=$row;
}
// Convert array to json format
$json = json_encode(array('Categories'=>$rows));
echo $json;
}
//Close db connection when done
mysql_close($con);
?>
That is very easy, take out the while, like below
$row = mysqli_fetch_assoc($result);
$date1_1m = $row["date1"];

Categories