In my mysql tables I have for example a row that holds values, lets call this table "days" and the row "haircuts".
So I have 5 rows all with "1","2","3","4","5" under "haircuts". What I want to do, in php, is add them all together and echo. So it would maybe look like this:
echo "Total haircuts: ",$haircuts;
Which would hopefully show:
Total haircuts: 15
I can't figure out how, though. Here's how I'm currently doing it.
$getstats = mysqli_query($con,"SELECT * FROM stats");
$gotstats = mysqli_fetch_array($getstats);
$haircuts = $gotstats['haircuts'];
But it only echoes the "haircuts" of the first row? :(
I have multiple columns I would like to total and echo too if that is possible?
You can use the MySQL statment SUM in your query, just change your code by this one:
$getstats = mysqli_query($con,"SELECT SUM(haircuts) AS totalhaircuts FROM stats");
$gotstats = mysqli_fetch_array($getstats);
$totalhaircuts = $gotstats['totalhaircuts'];
echo "Total haircuts: ",$totalhaircuts;
You probably should use MySQL SUM().
SELECT SUM(haircuts) as tot_cuts FROM stats;
$gotstats['tot_cuts'];
You need to use loop for getting all rows. Example:
$getstats = mysqli_query($con,"SELECT * FROM stats");
while($gotstats = mysqli_fetch_array($getstats)){
$haircuts = $gotstats['haircuts'];
echo $haircuts . '<br />';
}
Related
Lets say I have an email. Then I have an input with like 6, on database should be now 6, then I add another value like 11 and now it should be 17. I have like no ideia on how to do this.
The closest thing I did was sum the entire column but that only works for 1.
<?php
$conn = mysqli_connect('localhost','root','','form');
$result = mysqli_query($conn, "SELECT sum(sumemail) FROM data");
$lines = mysqli_num_rows($result);
while($lines = mysqli_fetch_array($result)){
echo "<br><br>Total de fotocópias:";
echo $lines['sum(sumemail)'].'<br/>';
}
?>
I wanted to use this code but i dont know how
UPDATE sumemail = sumemail + $value
I expect to have like 10 emails, all with different values each.
So you just need to know how to use the UPDATE query:
UPDATE <Table> SET sumemail = sumemail + '$value'
hi i have a backend with php in cpanel and i have a problem with one of jsons . this is part of my php code :
...
}elseif ($work == "dollardate") {
$query3 = "SELECT * FROM tabl_dollar_date";
$result3 = $connect->prepare($query3);
$result3->execute();
$out3 = array();
while ($row3 = $result3->fetch(PDO::FETCH_ASSOC)) {
$record3 = array();
$record3["dollar"] = $row3["dollar"];
$record3["date"] = $row3["date"];
array_push($out3, $record3);
}
echo json_encode($out3);
}
?>
this code show this in json :
[
{
"dollar":"15000",
"date":"1397-12-12"
}
]
how can remove array from json and show the json like this :
{
"dollar":"15000",
"date":"1397-12-12"
}
Easiest way (according his code):
change line
echo json_encode($out3);
to
echo json_encode($out3[0]);
One solution is that if you just want the latest value (in case there are multiple records in the table), then change the SELECT to order by date descending also set LIMIT to 1 to only get the 1 record anyway, and remove the loop to fetch the data and just fetch the 1 record...
$query3 = "SELECT `date`, `dollar`
FROM `tabl_dollar_date`
ORDER BY `date` desc
LIMIT 1";
$result3 = $connect->prepare($query3);
$result3->execute();
$row3 = $result3->fetch(PDO::FETCH_ASSOC);
echo json_encode($row3);
As you know which fields you want from the SELECT, it's good to just fetch those fields rather than always using *. This also means that as the result set only contains the fields your after, you can directly json_encode() the result set rather than extracting the fields from one array to another.
What I am trying to do is:
I have a table called Stations, and it has 100 columns. I want to select all records from Stations and randomly select 1 record and echo the random record.
Here is what I have got so far:
<?PHP
$connect = mysql_connect("***", "****", "****") or die("Connection Failed");
mysql_select_db("***");
$query = mysql_query("SELECT * FROM Stations ORDER BY RAND() LIMIT 1");
WHILE($rows = mysql_fetch_array($query)):
$Station = $rows['Station1'];///seems it will only show Station1 Column I have Station1 to Station100 was not sure how to add rest of Stations
endwhile;
?>
Since you're limiting the result set to only one row, you don't need that while() loop. Just fetch the row from the result set and use it afterwards, like this:
$rows = mysql_fetch_array($query);
Now comes to your question,
... it will only show Station1 Column I have Station1 to Station100 was not sure how to add rest of Stations
To display all hundred column values, it's better to use a for loop like this,
for($i = 1; $i <= 100; ++$i){
// display $rows['Station' . $i] as per your choice. Below is one way.
echo $rows['Station' . $i] . '<br />';
}
Update:
From your comment,
... I need it to randomly choose 1 value out of all 100 columns and echo that value please
After fetching the row from the result set, use array_rand() function to get a random key out of the array, and then use that key to display the column value, like this:
$randKey = array_rand($rows);
echo $rows[$randKey];
Sidenote: Don't use mysql_* functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli or PDO extensions instead. Also read, why shouldn't I use mysql_* functions in PHP?.
Already solved. I just used WHERE MONTH(due_date) = $month in the SQL clause. Never knew it would just be like that. Thank you for all your answer!
We have a table called bills. We do not delete a bill even if it is paid already for record purposes.
So our goal is to only display The Bills for this Month. I have a $cur_month = current month value. I know how to extract the month value from a field using MONTH(), using a loop to run though the table, but when I try to echo MONTH(date) the value through out the displayed series is just the MONTH VALUE of the very first row. It seems it failed to get the MONTH VALUE of the other rows.
Fixed code below
$query = "SELECT * FROM bill WHERE MONTH(due_date)=$month";
$bresult = mysql_query($query);
while($brow = mysql_fetch_array($bresult, MYSQL_ASSOC))
{
$bdata = mysql_fetch_assoc(mysql_query("SELECT MONTH(due_date) AS M FROM `bill`"));
if($bdata['M'] == $month)
{
echo "<tr>";
echo "<td>".$brow['room_id']."</td>";
echo "<td>".$brow['tenant_id']."</td>";
echo "<td>".$brow['due_date']."</td>";
echo "</tr>";
}
}
$month there is the holder of the current month
$bdata['M'] there is the holder of the month extracted. We just displayed it to check.
So if extracted_month is equls to current_month then display bill
I hope you can help me in this.
PS: Still an amateur. This is not yet an online website. We only need help for the purpose of having it work.
1) Use a WHERE statement in your first SQL to only fetch those rows from the table.
Like this:
$query = "SELECT *, MONTH(due_date) as M FROM bill WHERE MONTH(due_date)=" . $month;
$bresult = mysql_query($query);
while($brow = mysql_fetch_array($bresult, MYSQL_ASSOC)) {
echo "<tr>";
echo "<td>".$brow['M']."</td>";
echo "<td>".$brow['tenant_id']."</td>";
echo "<td>".$brow['due_date']."</td>";
echo "</tr>";
}
2) I find it good practice to always check if the result object is created and if so, to check if it returned matches (with mysql_num_rows($result)). That way you can show an error if something goes wrong (most likely in the SQL statement) or show the user that there are no matches (bills in this case).
3) Try to use MYSQLI to connect to your database instead of MYSQL, since the latter is deprecated. (See: http://php.net/manual/en/mysqli-result.fetch-assoc.php for an example.)
Try solving this problem using SQL.
SELECT b.amount_paid
FROM bills b
WHERE MONTH(b.due_date) = 3
Using the result of this query you would have all of the amounts for this month. Sum your result and you are done.
I'm creating a small project with PHP/MYSQL but i can't get my query working the way i need it. I have 2 tables
Table 1 (char):
Id, name.
Table 2 (spells):
Id, char, spell_name.
I'm getting the output:
Name Spell1
Name Spell2
Name Spell3
But I need it to be:
Name Spell1
Spell2
Spell3
Here's my query:
$query = "SELECT char.name AS name, spells.spell_name AS spell
FROM char, spells
WHERE (char.id = spells.spell_name)";
Any ideas?
I think you're gonna have to first get the ID of the character to query, and then pull the spells s/he has access to. Example:
$char_id = 0; // value would be assigned arbitrarily.
$query = "SELECT *
FROM 'spells' s
WHERE s.char = $char_id;";
$result = $pdo->query($query);
while($row = $result->fetchObj()){
// do something with the spells obj here
}
With SQL, you need to grab full rows at a time, so I believe the situation you want isn't possible.
As Goldentoa11 wrote. Make two selects, or create query with two result sets (more selects in one command), or accept current state (is normal and you can verify data consistency). I prefer current state, but sometimes use any of described solution (based on query frequency, size of result etc.).
If you need to list such data, you can than use something like this:
$currentName = null;
while ($row = mysql_fetch_object($result))
{
if ($currentName != $row->name)
{
echo "<b>" . $row->name . "</b><br />";
$currentName = $row->name;
}
echo $row->spell_name . "<br />";
}