Get sum of each row added together in while loop - php

So I have a mysql table that contains an integer in each row. What I am trying to do is get the sum of the integers. Here is what I currently have that is working.
$cn = 0;
$sql = mysqli_query($con,"SELECT * FROM members WHERE member='$userid'");
while($row = mysqli_fetch_array($sql)) {
$i = $row['number'];
$cn = $cn + $i;
}
echo $cn;
So I make $cn equal zero then each time it goes through the loop it will add the number from the matching row.
Does anyone have a better idea on how to accomplish this? Thanks!

You don't need to use PHP or here a loop for that, because your database can do the job for you.
$sql = mysqli_query($con,"SELECT sum(number) FROM members WHERE member='$userid'");

If you want the sum of the column number for each member with a particular user id
$sum = 0;
$sql = mysqli_query($con,"SELECT SUM(number) as number_total FROM members WHERE member='$userid'");
while($row = mysqli_fetch_array($sql)) {
$sum = $row['number_total'];
}
$sum will have the total

Related

I want to retrieve data from mysql php

$query_importer1 = "SELECT * FROM items where item_id ='".$row1["item_id"]."'limit 5 ";
$result_importer1 = mysqli_query($conn,$query_importer1);
for ($i=0; $i<=mysqli_num_rows($result_importer1); $i++)
{
$row = mysqli_fetch_assoc($result_importer1);
echo ''.$row['item_name'].'<br>';
}
i want all item name but its printing only one
You do not need to execute for loop on records, You can get all records using while loop, Plz refer below code
$query_importer1 = "SELECT * FROM items where item_id ='".$row1["item_id"]."' limit 5 ";
$result_importer1 = mysqli_query($conn,$query_importer1);
while($row = mysqli_fetch_assoc($result_importer1)){
echo $row['item_name'];
}

How can i print how many Id's i have in my database in php

I don't understand why this isn't working and i don't know how to fix it:
$sum=0;
$queryone="SELECT SUM(ID) FROM seriestwo";
$result = mysqli_query($link,$queryone);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
while($row = $result->fetch_assoc()){
$sum = $sum + 1;
}
echo $sum
it always prints 0.
What you are doing is wrong because the $result stores only 1 row, that is the sum of ID. You can try two things:
Method 1: Use COUNT() in mysqli. Check MySQL Reference
For eg. check: select count(*) from table of mysql in php
$queryone="SELECT COUNT(ID) as total FROM seriestwo";
$result = mysqli_query($link,$queryone);
$row = mysqli_fetch_assoc($result, MYSQLI_NUM);
echo $row['total'];
Method 2: Use this code:
$sum=0;
$queryone="SELECT `ID` FROM seriestwo";
$result = mysqli_query($link,$queryone);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
while($row = $result->fetch_assoc()){
$sum = $sum + 1;
}
echo $sum;
Which Method to Use
The first method is the one you should be using right now, in this case. You can use second when you want to add extra things, like print every ID
You may be overthinking this.
It's as simple as the following and using an alias while using only 3 lines of code:
$query = $link->query("SELECT SUM(`ID`) as `total` FROM seriestwo");
$row = $query->fetch_assoc();
echo $row['total'];

Trying to randomize where a name is inserted into a table using PHP and SQL

What I'm trying to accomplish is randomize elements of an array which contain column names. Then use those randomized columns names to insert a name into a table.
Here is the code I have and its causing a Internal Server Error.
$sql3 = "SELECT * FROM players";
$result3 = $con->query($sql3);
while ($row3 = $result3->fetch_assoc()) {
$num_bracket1 = $row3["num_bracket"];
$name = $row3["name"];
$y = 1;
while ($y <= $num_bracket1) {
shuffle($bracket_array);
shuffle($player_array);
$sql4 = "UPDATE brackets SET ".$player_array[0]."='".$name."' WHERE bracket_num='".$bracket_array[0]"'";
$result4 = $con->query($sql4);
}
}
It's an obvious infinite loop, you forgot to increment $y inside the while and it never ends.

Printing Duplicate Records In PHP / Mysql

I am trying to print the duplicate records of the table but only the single row is getting
echoed.However in mysql this query results all the duplicate records. Here is the query:
$q = mysql_query("SELECT * FROM add WHERE cust_id = '144' GROUP BY cust_id");
$r = mysql_fetch_array($q);
$s = mysql_num_rows($q);
while($s !=0)
{
echo $r;
$s=$s-1;
}
Whats wrong with the code?
$q = mysql_query("SELECT * FROM add WHERE cust_id = '144' GROUP BY cust_id");
while($r = mysql_fetch_array($q))
{
print_r($r);
}
You need to loop through the entire record set... you are only grabbing the first row:
$resultset = mysql_query("select * from add where cust_id = '144' group by cust_id");
while($row = mysql_fetch_assoc($resultset))
{
echo $row['column_name'];
}
Your SQL query will in practice only ever return 0 or 1 rows, due to the GROUP BY clause. Are you absolutely sure that that's the query you were executing in mysql?
well, if you want to get duplicate values, then this query will serve you well:
T = the table
f = the field to check for duplicates
id = the rows id
select id,f from T group by f having count(f)= 2;
or >2 if you want every value in f that occurs in more than one row.
having is like where but evaluated after group by.
Try the following:
$q = mysql_query("SELECT * FROM add WHERE cust_id = '144'");
while($r = mysql_fetch_array($q))
{
echo $r;
}

Checking to see if a MySQL row is populated

I have a page that writes to a MySQL table. The table has a set amount of rows (24).
I have an $id variable that's set by a rand() function. I basically want to pull the row at that $id, so if $id was 3, I want to pull the third row. Then, I want to check if there is a price set at that row (indicating that the row is being used). If there is no price, I want to keep $id at the value it has been set at and proceed with the query. If there is a price, I want to re-randomize the $id variable, and check again if that row is used up. When it finds an empty row, proceed with the query.
My solution semi-works, but it seems to have a <10% chance of overwriting a used row, for some reason. I want it to never overwrite a used row.
Here's my code:
mysql_select_db("delives0_booklet", $con);
$query = "SELECT * FROM booklet WHERE id = '$id'";
$res = mysql_query($query,$con);
$newId = $id;
while($row = mysql_fetch_array($res))
{
if($row['price'] != 0)
{
do{
$newId = rand(1, 24);
}while($newId == $id);
}
}
$id = $newId;
mysql_query("UPDATE booklet SET price = '$price', advertiser = '$advertiser', image = '$image', monthsRemaining = '$monthsRemaining', availability = 1 WHERE id = '$id'");
Edit
I had the idea to do this. I loop through the table and I put the 'id' of each unfilled spot into an array. Then I pick randomly from that array. However, there seems to be a bug that I can't find, since the array keeps showing as having nothing in it, even after the loop is run, and $i is the correct figure.
mysql_select_db("delives0_booklet", $con);
$query = "SELECT * FROM booklet";
$res = mysql_query($query,$con);
$i = 0;
$isEmpty = array();
while($row = mysql_fetch_array($res))
{
if($row['price'] == 0)
{
$isEmpty[i] = $row['id'];
$i = $i + 1;
}
}
echo $i . " unfilled spots.";
$n = 0;
while($n<$i)
{
echo $isEmpty[$n];
$n = $n + 1;
}
if($i > 0)
{
$id = $isEmpty[rand(0, $i)];
}
if($i == 0)
{
echo 'All spots have been filled.';
}
I think it is a top level logic problem. Because you populate with random ids, you can get duplicate ids, and so when you update "WHERE id = '$id'" you may be picking up rows already populated.
I don't know your goal, but perhaps using an auto-increment id, and dropping rows that you want to get rid of, is the way to go. A rolling set of rows (24 at a time) but with ever increasing ids, would prevent mistaking one for the other.
If I understand the problem correct, this should work:
SELECT *
FROM booklet
WHERE price = 0 OR price IS NULL
ORDER BY RAND()

Categories