MySql SUM not returning any results [duplicate] - php

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

Related

Add values from MySQL result together from array [duplicate]

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.

Display MySQL column value count only [duplicate]

This question already has answers here:
How to get count of rows in MySQL table using PHP?
(3 answers)
Closed 2 years ago.
How do I display this query result:
from MySQL onto a webpage, just like this:
?
I want to display the count only. I did run the same query through PHP but its returning '2'. The PHP code is below
<?php
//Connection for database
$conn = mysqli_connect("localhost", "root", "aaaaa", "db");
$query = "SELECT `gender`,COUNT(`gender`) FROM `reg` GROUP BY `gender`";
$result = mysqli_query($conn, $query);
if ($result)
{
// it return number of rows in the table.
$row = mysqli_num_rows($result);
if ($row)
{
printf("" . $row);
}
// close the result.
mysqli_free_result($result);
}
// Connection close
mysqli_close($conn);
?>
Please note that I have gone through other answers like this one but I can't really find my way through, I want the value count only not the total number of all rows in the table, .e.g. count for 'Male'.
You're using mysqli_num_rows(), which returns the number of rows in the result, not the actual data in the result. For that you need to use mysqli_fetch_assoc().
Your could would become:
$query = "SELECT `gender`,
COUNT(`gender`) AS `count`
FROM `reg`
GROUP BY `gender`";
$result = mysqli_query($conn, $query);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$gender = $row['gender'];
$count = $row['count'];
echo "$gender = $count<br>";
}
mysqli_free_result($result);
}
Note that I slightly changed your query to make the count accessible.

MySQL Select statement not functioning if there are alphabetic characters [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
How can I prevent SQL injection in PHP?
(27 answers)
Closed 2 years ago.
Expected result:
Loop through all entries in the checkedout table, and select the entry from the game table where the barcode field is the same.
Actual behaviour / issue:
For the most part, this is working as intended. If I set the barcode field to a numerical value in the game table, and then "checkout" that barcode, everything works as intended. The barcodes I'll be using are in the format of ABC12345678. Once I change the values in the barcode field, in the game table to the alphanumeric version, it no longer runs the secondary select statement and displays this error: Fatal error: Call to a member function fetch_assoc() on boolean which refers to the following line: while ($row2 = $result2->fetch_assoc()) {
Oddly enough, if I run the exact same select statement SELECT * FROM game WHERE barcode = 'ABC12345678' on the MySQL instance, it returns the proper results.
Question
Do I need to be using a different method to select based on the value now being alphanumeric? Do I need to manipulate the data in some way?
Code:
$sql = "SELECT * FROM checkedout";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$userid = $row["userid"];
$barcode = $row["barcode"];
echo "$userid </br>";
echo "$barcode </br>";
$sql2 = "SELECT * FROM game WHERE barcode = " . $barcode . "";
$result2 = $conn->query($sql2);
while ($row2 = $result2->fetch_assoc()) {
$title = $row2["title"];
$console = $row2["console"];
echo "$title </br>";
echo "$console </br>";
}
checkedout table:
game table:

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()

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