Display mysql in separate tables - php

Hi I am just a beginner with phpmysql and trying to display result in separate table by a row.
I have this query:
$albania = mysqli_query($con,"SELECT * FROM `data` ORDER BY citid ASC");
while($row = mysqli_fetch_array($albania))
I know that this will output all results onto 1 table. I want to put results onto separate tables dependent on the $row['citizenship']
I have about 40 different results in that row, so I want to separate it by that row and output separately.

If you order by the field you want to split on (citizenship) and keep track of the current value (done below with $currentCitizenship), then you should be able to just look for changes in that value and start a new table when the next section starts.
$albania = mysqli_query($con,"SELECT * FROM `data` ORDER BY citizenship ASC, citid ASC");
$currentCitizenship = ""
while($row = mysqli_fetch_array($albania)){
//handle the first time through the loop and start the first table
if ($currentCitizenship = ""){
//Start the first table
echo "<table>";
$currentCitizenship = $row['citizenship'];
}elseif ($currentCitizenship != $row['citizenship']){
//change to next citizenship table
echo "</table><table>";
$currentCitizenship = $row['citizenship'];
}
/*
Your current row printing code
*/
}
//close off the last table
echo "</table>"

What you wrote will not output anything yet. It will just fetch all rows from the database. You need to add code in PHP to diplay it in the screen.
Something like this. Need to put the correct php syntax:
$albania = mysqli_query($con,"SELECT * FROM `data` ORDER BY citid ASC");
while($row = mysqli_fetch_array($albania))
{
if($row['citizenship'] equals 'valuea')
print in one table
else
print in another table
}

Related

Best way to identify a mysql changed "group by" field value in a statement fetch in php?

I have a sql query in my php:
$sql = "SELECT * FROM orderTaken WHERE orderStatus='10' GROUP BY orderId ORDER BY orderTakenTime DESC";
Now, I have to echo back several HTML tables based on different orderIds, so basically if the orderId is changed, a new HTML table will be created and contains the info of all the things under this orderId. This is what I have done(kinda pseudocode, please ignore the syntax error. My real code is far more complicated but the idea is here: set an oldOrderId and check it with the newly fetched orderId and see if the orderId is changed):
$sql = "SELECT * FROM orderTaken WHERE orderStatus='10' GROUP BY orderId ORDER BY orderTakenTime DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$count = $stmt->rowCount();
for ($i = 0; $i<$count + 1; $i++ ){
if ($row = $stmt->fetch()){
$orderId = $row["orderId"];
$2ndField = $row["2ndField"];
$3rdField = $row["3rdField"];
...
// check if $oldOrderId is set
if (isset($oldOrderId)){
// and compare, if the orderId changes, end the table and create a new one
if ($oldOrderId != $orderId){
echo "</table><br>";
echo "<table><tr><th>...</th></tr>";
...
//UPDATE old orderId
$oldOrderId = $orderId;
// if orderId doesn't change, continue echo table content
} else {
echo "<table><tr><td>...</td></tr>";
}
// if the oldOrderId is not set, it means this is the first fetched row, and the very first table will be created
} else {
echo "<table><tr><th>...</th></tr>";
...
echo "<table><tr><td>...</td></tr>";
...
//SET oldOrderId
$oldOrderId = $orderId;
}
}
if ($i == $count) {
//End the last table
echo "</table><br>";
}
}
The code can run but will be buggy sometimes and I don't think this is a smart way to identify it. Is there any existed method like
$row = $stmt->fetch().prev()
to get the last row's orderId's value? Or if there's any better way to perform it?
Thanks!
The problem is your inclusion of GROUP BY orderId in your query. What this does is give you one row per each orderId in your table.
Since you are using SELECT *, then all you are getting back is one row for each orderId and one of the other values in the table for each of the other fields.
When using GROUP BY, you usually want to add a "group function" - like SUM(), COUNT(), GROUP_CONCAT(), etc. - to your query.
Your approach with the $oldOrderId is fine and could work if you change your query to something like:
SELECT * FROM orderTaken
WHERE orderStatus='10'
ORDER BY orderID DESC, orderTakenTime DESC

add one (+1) to a field in mysql database using php

I have a php script that displays records from a database. It's probably not the best script, as I'm very new to php.
I've added an additional column in my table and would like to keep a count in that column to show me how many times each of the records have been viewed.
Heres the part of the code I think i need to add the code to... if i need to post the entire page i will, but i just figured i could add the line to this part.
//Get the details from previous page
$SelectedCounty = $_POST["result"];
//set variable for next SEARCH
$option = '';
// Get the county names from database - no duplicates - Order A-Z
$query = "SELECT DISTINCT tradingCounty FROM offers ORDER BY tradingCounty ASC";
// execute the query, $result will hold all of the Counties in an array
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)) {
$option .="<option>" . $row['tradingCounty'] . "</option>";
}
}
the new column name is 'views' and i just want to add 1 to it each time a record from the database is viewed.
any help greatly appreciated.
Add a new field views to the table.
When, user views the page, fire the SQL.
$query = "UPDATE offers SET views = views + 1";
mysqli_query($con,"update offers set views = views + 1");
If you have added the column, it probably has a NULL value. Either set the value to 0, by doing:
update offers
set views = 0;
Or use:
update offers
set views = coalesce(views, 0) + 1;
You can change your code with this rewritten code assuming that your Table has a column views (datatype int).
//Get the details from previous page
$SelectedCounty = $_POST["result"];
//set variable for next SEARCH
$option = '';
// Get the county names from database - no duplicates - Order A-Z
$query = "SELECT DISTINCT tradingCounty FROM offers ORDER BY tradingCounty ASC";
// execute the query, $result will hold all of the Counties in an array
$result = mysqli_query($con,$query);
if($result){
$query2 = "UPDATE offers SET views=views+1;
mysqli_query($con,$query2);
}
while($row = mysqli_fetch_array($result)) {
$option .="<option>" . $row['tradingCounty'] . "</option>";
}
Or if you need to track the view counts for individual records, you need to modify your code a bit. And probably you need to add one more field in the database for eg. id (datatype int) which can distinguish between different records.
Please clear your problem properly.
As far as i have analysed your code it brings out the following case.
There are different records for tradingConty, and whenever a user views that particular record(one of the tradingCounty record) by clicking that or any other action specified, the php script is set to increament the view count for that particular entry(we can get that by id) in the database.
If thats the scenario, we can easily generate a code accordingly.

Which is the query i should do so that i could fetch the previous from last row?

I want to read the last 3 rows of my table seperate and then place them in 3 different div's of a slider. The problem is that i cant use 'where id=xxx' because i insert rows dynamically every time that i make a post item.
if i use query('select * from news order by id desc limit 3') and then a loop while ($result->fetch_assoc()) then i have the last 3 rows.
My problem is that i want to place every row in a different div so that i will have 3 divs.
I suppose i must do 3 different queries for that but i dont know how.
I have this one right now.
$result = $myDb->query('select * from news order by id desc');
while ($nI = $result->fetch_assoc()) {
$title = $nI['title'];
$date = $nI['date'];
$author = $nI['author'];
$mainobjective = $nI['mainobjective'];
$contents = $nI['contents'];
$keywords = $nI['keywords'];
and then i have my html where with the use of echo i place every variable in the div i want.
It sounds like the problem you are describing is more with your PHP code, that you haven't posted, than your MySQL. Don't read them separately. Use a single query to get all 3 and then iterate through them separately with PHP.
You can use the query you already had:
$result = $myDb->query('SELECT * FROM news ORDER BY id DESC LIMIT 0,3');
Make sure you are placing the results in separate containers in PHP:
foreach($result as $row)
{
echo "<div>".$row."</div>";
}

echo updated values instead of old values

How do I echo the latest values in column1? The below code echos the values before the update.
while($line = mysql_fetch_array($result)) {
$Student = $line["calss8"];
$querySf = "SELECT SUM(ABC) AS val1 FROM tbl1 WHERE student = '$Student'";
$resultSf = mysql_query($querySf);
$rSf = mysql_fetch_array($resultSf);
$totalSf = $rSf['val1'];
$totTMonth = $totalSf;
mysql_query("UPDATE tbl4 SET column1 = $totTMonth WHERE student = '$Student' LIMIT 1");
}
echo $line["column1"].",,";
As far as I know, you'll have to make a separate query to see what was just updated. I mean, run your select, perform your update, then do another select. You can get general information like how many rows were updated, but I don't think you can get specific information like the changed values in a column. Phil was right in suggesting that you should just print out the '$totTMonth' value since that is what you are updating your column with. That would be less overhead than doing another query to the database.
I think that problem starts before the code above. This code line will display the select results :echo $line["column1"].",,";. The variable $line is set before the code above. My solution is to do the following:
$result1 = mysql_query("SELECT column1 FROM student ..."); /* I insert the select query here */
While($row= mysql_fetch_array($result)) {
echo $row['column1'].",,";
}

Counting from field in table then updating to a different field in a different table

Quite a complex question:
At the moment I have a table called "timetable". This is updated when someone books a slot (this is for a radio booking system). What I would like is a PHP file that I can have run every 15 minutes as a cron job. In PHP script what I'd like it to do is count how many slots a radio presenter has booked via the "username" field in the "timetable" table. Then I would like it to update a field in another table called "users" in a field called "slot_count" with the amount of slots which were found in the "timetable" table under their "username".
At the moment I have a script which pulls all the booked slots with their presenter "username"'s into a table:
<?php
include("../config.php");
include("functions.php");
if($logged["level"] == "HDJ" OR $logged["level"] == "SA") {
echo "<table width=\"580px\" class=\"board\" border=\>";
$order = "SELECT * FROM timetable WHERE username <> 'No DJ'";
$result = mysql_query($order);
// Error checking
if (!$result) {
// output error, take other action
}
else {
while ($row=mysql_fetch_array($result)){
// Append all results onto an array
$rowset[] = $row;
}
}
foreach ($rowset as $row) {
echo "<tr><td>" . htmlspecialchars($row['username']) . "</td></tr>";
}
} else {
echo ("<div class=\"caution\">Access is denied.</div>");
}
?>
Any ideas?
Storing this redundant data in your users table is unnecessary. As long as the tables are indexed appropriately the join and count are trivial -
SELECT users.*, COUNT(timetable.username) AS num_slots
FROM users
LEFT JOIN timetable
ON users.username = timetable.username
GROUP BY users.id
Can't it be done using one sql statement doing both COUNT() and UPDATE:
UPDATE users
SET slot_count = (SELECT COUNT(*) FROM timetable WHERE timetable.username = users.username)
Assumption: the username field contains the same value for the same radio presenter in both users and timetable tables. Otherwise they wouldn't match. You should be able to run this query directly against MySQL from the cron job (instead of doing the PHP script).

Categories