How to add together the values in an array from MySQL query - php

I'm trying to add together values generated from a MySQL query but the total I'm getting doesn't seem to add up. Here's my code:
$top_score = mysql_fetch_array(mysql_query("SELECT 1ET FROM scoring_data WHERE
Competition='$competition' AND Club='$row[Club]' AND Team='$row[Team]' ORDER BY
1ET DESC LIMIT 0, 3"));
echo (array_sum($top_score)/10) ;
I have two values entered into 1ET for that specific query (competition, club and team): 6 and 3. The total I should get is 9, but the total is coming out as 12...
Any suggestions gratefully received!

The array isn't structured how you expect it to be:
print_r($top_score);
Maybe do it in the query:
SELECT SUM(1ET)/10 AS top_score FROM scoring_data WHERE
Competition='$competition' AND Club='{$row['Club']}' AND Team='{$row['Team']}'
ORDER BY 1ET DESC LIMIT 0, 3

Related

Display N number of records from a PDO MySQL query

I'm trying to figure out how to only display the 1st 10 records (1-10) or the 2nd 10 records (11-20), or etc...
The code below does a great job of pulling all records, but I can't figure out how to modify it to only show N number of records. Any help is greatly appreciated.
include 'database.php';
$pdo = Database::connect();
$sql = 'SELECT * FROM trail101 ORDER BY id DESC';
foreach ($pdo->query($sql) as $row) {
//my code
}
Use limit to define the offset and number of records you want. To get the first 10 use:
SELECT * FROM trail101 ORDER BY id DESC LIMIT 0, 10
to get the next 10:
LIMIT 10, 10

Return list of member_number count in table

Consider the following table
I need to return a list in descending order with the count of the member_nr's who is appearing the most frequent in the table where tournament = 'EPL' AND ROUND = '12'
EXAMPLE
The script should return the following results:
I thought about the problem and my logic for the problem reads like this
STEP1: GET member_nr one by one
$sql = "SELECT DISTINCT *
FROM winners
WHERE tournament='$tour' AND round='$round'";
LOOP(){ //get 1 member number
$mem_nr = ['mem_nr']; //assign mem_nr to variable
STEP2: GET the count(number of times) ^ABOVE^ member number appears in table
"$sql="SELECT *, count(member_nr) as nrWins
FROM winners
where member_nr ='$memNr' and tournament='$tournament' AND round='$round'";"
LOOP(){//get count
STEP 3: DISPLAY DATA
echo $row=['nrWins'] //Display Number Wins
echo $memNr
}//END LOOP
}//END LOOP
My Problem:
The above does not seem very efficient to me, im looking for the shortest most efficient way to return the count of member numbers in table above, any ideas / suggestions are welcomed
Try something like this:
SELECT *, COUNT(*) AS `wins`
FROM `winners`
WHERE `tournament` = '$tournament'
AND `round` = '$round'
GROUP BY `member_nr`
ORDER BY `wins` DESC
select tournament,round,member_nr,count(*)
from table
where tournament = 'EPL'
and round = 12
group by tournament,round,member_nr
order by count(*) desc

Can't retrieve zero values when using COUNT and GROUP together

I'm struggling with a MYSQL query, when using COUNT and GROUP together it's excluding any rows that have a count of 0. I understand why this is happening but can't work out how to get around it. I've read up on potential solutions presented to those with a similar problem but I cannot see the link between the two that would allow me to solve it.
Can anybody help?
$query = "SELECT id, class_date, class_id, COUNT(*) AS reserve_count
FROM bookings
WHERE booking_status='#RESERVE#'
GROUP BY class_date, class_id
ORDER BY class_date ASC, class_id ASC" ;
$result = mysqli_query($sql,$query);
while($row = mysqli_fetch_assoc($result)) {
$bookings[$row['id']] = array('class_date' => $row['class_date'], 'class_id' => $row['class_id'], 'reserve_count' => $row['reserve_count']);
}
Logically, there shouldn't be any row with zero count because booking table should only have classes that are booked.

Get total rows count of table

I want to get all rows count in my sql.
Table's first 2 columns look like that
My function looks like that
$limit=2;
$sql = "SELECT id,COUNT(*),dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$stmt->bind_result($id, $total, $datetime, $title, $content);
$stmt->store_result();
$count = $stmt->num_rows;
if ($count > 0) {
while ($stmt->fetch()) {
Inside loop, I'm getting exact value of $total, but MySQL selects only 1 row - row with id number 1. (and $count is 1 too)
Tried this sql
SELECT id,dt,title,content FROM news ORDER BY dt DESC LIMIT 2
All goes well.
Why in first case it selects only 1 row? How can I fix this issue?
for ex my table has 5 rows. I want to get 2 of them with all fields, and get all rows count (5 in this case) by one query.
Remove COUNT(*). You will only ever get 1 row if you leave it in there.
Try adding GROUP BY dt if you want to use COUNT(*) (not sure why you're using it though).
EDIT
Fine, if you insist on doing it in a single call, here:
$sql = "SELECT id,(SELECT COUNT(id) FROM news) as total,dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
This is likely cause by the variable $limit being set to 1, or not being set and mysql defaulting to 1. Try changing your first line to
$sql = "SELECT id,COUNT(*),dt,title,content FROM news ORDER BY dt DESC";
EDIT
Change to:
$sql = "SELECT SQL_CALC_FOUND_ROWS,id,dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
And then use a second query with
SELECT FOUND_ROWS( )
to get the number of rows that match the query
This totally wreaks of a HW problem... why else besides a professor's retarded method to add complexity to a simple problem would you not want to run two queries?
anyways.... here:
SELECT id, (SELECT COUNT(*) FROM news) AS row_count, dt, title, content FROM news ORDER BY dt DESC LIMIT

How to retrieve first 2 results from mysql array without querying again?

Each page lists all the coupons available for a specific retailer. I query the database for all the coupon codes in the header since I count the number of rows returned and use that info in the meta title of the page. I now also want to display the titles of the first 2 coupons in the array. How would I go about extracting the first 2 results from the array without querying the database again?
This is what I have so far:
$retailer_coupons = "select C.couponid,C.fmtc_couponid,C.merchantid,C.exclusive,C.label,C.shoppingtip,C.restrictions,C.coupon,C.custom_order,C.link,C.image,C.expire,C.unknown,M.name,M.approved,M.homepageurl,M.category from tblCoupons C,tblMerchants M where C.merchantid=M.merchantid and C.begin < ".mktime()." and C.expire > ".mktime()." and C.merchantid=".$merchantid." and M.display='1' and C.user_submitted='' order by C.custom_order desc, C.coupon desc";
$retailer_coupons_result = mysql_query($retailer_coupons) or die(mysql_error());
$count_coupons=mysql_num_rows($retailer_coupons_result);
$meta_title = ''.$name.' Coupon Codes ('.$count_coupons.' coupons available)';
Suppose I have 3 records in my table. If I execute below query, I will get 2 results however the count(*) will give me 3 as output
SELECT count(*) FROM temp.maxID limit 2
In your case it will be
$retailer_coupons =
"select C.couponid,C.fmtc_couponid,C.merchantid,C.exclusive,C.label,C.shoppingtip,C.restrictions,C.coupon,C.custom_order,C.link,C.image,C.expire,C.unknown,M.name,M.approved,M.homepageurl,M.category
from tblCoupons C,tblMerchants M
where C.merchantid=M.merchantid
and C.begin < ".mktime()." and C.expire > ".mktime()."
and C.merchantid=".$merchantid." and M.display='1'
and C.user_submitted=''
order by C.custom_order desc, C.coupon desc
limit 2";
limit 2 will do the magic... Cheers!!!
Good Luck!!!
Something like this:
$res = mysql_fetch_assoc($retailer_coupons_result);
$i = 0;
while ($i < 2){
echo $res[$i]['label']."\n";
$i++;
}

Categories