I want to sort my result form mysql by date. I use the query like this:
<?php
$date = $db->get_query("select distinct created_date from comments");
$condate = '';
for($i=0; $i < count($date); $i++)
{
$condate = $date[$i]['created_date'];
$data = $db->get_query("select id,created_date from comments where created_date='$condate' order by created_date");
?>
<table border='1' style="float: left; margin-left: 5px;">
<?php
for($j=0; $j<count($data); $j++)
{
echo '<tr><td>';
echo $data[$j]['id'] ;
echo '</td><td>';
echo $data[$j]['created_date'];
echo '</td></tr>';
}
?>
</table>
<?php
}
?>
This query produce result like this:
2009-07-10
2009-07-10
2009-08-21
2009-07-29
2009-08-15
The result is not sorted.
I want to see the result is:
2009-07-10
2009-07-10
2009-07-29
2009-08-15
2009-08-29
with separated table order by created-date.
I want to know sorting date in mysql result .In this case $condate is variable for validate condition.The value of $condate is all created_date in comments table. I produce this as within loop and set the value is.
Please help me!
If you're only selecting results from a single date, then there's nothing to sort by. What exactly is the WHERE condition doing?
Edit: Now that you've posted your code, I can offer a suggestion. Your original code is running a separate query for each different date. What you really want is a single query that returns the results for all dates, but in a specific order, which is what the query in the code below does. Try this instead:
<?php
$data = $db->get_query("select id,created_date from comments order by created_date");
?>
<table border='1' style="float: left; margin-left: 5px;">
<?php
for($j=0; $j<count($data); $j++)
{
echo '<tr><td>';
echo $data[$j]['id'] ;
echo '</td><td>';
echo $data[$j]['created_date'];
echo '</td></tr>';
}
?>
</table>
Note that you already had all of this in your original code! You just managed to convince yourself that the task was more complicated than it actually was. :)
Because you put = in the where clause, so all the records will be in the same day and the sort will not be useful.
Edit
Are you using date field type for created_date field or string? if it's string so that may cause your problem...
Maybe you have your date field is stored as a "string" and not something like datetime?
If you check with:
describe table_name;
How is your date stored?
You are looping through results that aren't ordered to generate the dates you are asking for in the second query. Up near the top you were querying:
$date = $db->get_query("select distinct created_date from comments");
// should be (and excuse the keyword capitalization, I just think its easier to read)
$date = $db->get_query("SELECT DISTINCT created_date FROM comments ORDER BY created_date");
You just put your ORDER BY clause on the wrong query.
I dont think you need to execute 2 queries.
Try executing
$data = $db->get_query("select DISTINCT id,created_date from comments where created_date='$condate' order by created_date");
I think you had all built-in in your code but you just got confused a little.
Do let me know whether this solved your problem or not.
Related
I'm having some trouble with my php / mysqli code, hopefully you can help me.
I'm currently working on an online shop for a school project. Customers are able to buy things, they get an order number and I'm writing their user_id, the order number, the different products and some other things in a relation.
now the administrator should be able to see all orders.
right now it looks like this (I copied my table into a word table, so it's easier to see the structure):
part of the table
So the problem is that I have two different order numbers (80425 and 14808) and I want to show each number (and the name and adress of the custumer, too) only one time, but for each order number all different ordered products.
I imagine it like this:
part of the table (more organised)
(it's german, I hope you still get what I mean)
So this is the code right now for getting all the information and show them in a table:
$selection = "SELECT * FROM kundenbestellungen, zahlart, produkte, user, status_bestellung, wohnsitz, kontodaten
WHERE b_zahlung_id = z_id
AND b_produkte_id = p_id
AND b_user_id = u_id
AND b_status_id = sb_id
AND w_user_id = u_id
AND d_user_id = u_id";
$sql = mysqli_query ($dblink, $selection) OR die (mysqli_error($dblink));
if (mysqli_num_rows ($sql) > 0) {
while ($row = mysqli_fetch_assoc($sql)) {
?>
<tr>
<td>
<?php /*Change the status to sent*/
if ($row['b_status_id'] == '0') {
echo $row['sb_status'];
?>
<form action="admin-bestellungen.php" method="POST">
<input type="hidden" name="id" value="<?php echo $row['b_id']?>">
<input type="submit" name="versenden" value="versenden">
</form>
<?php
} else {
echo $row['sb_status'];
}
?>
</td>
<td> <?php echo $row['b_nummer'];?></td>
<td><?php echo $row['u_vorname']." ".$row['u_nachname'];?></td>
<td><?php echo $row['p_produktname'];?></td>
<td><?php echo $row['b_menge_produkt'];?></td>
<td><?php echo $row['b_einzelpreis'];?></td>
<td><?php echo $row['z_art'];?></td>
<td><?php echo $row['b_zeitpunkt'];?></td>
</tr>
<?php
}
}
I'm really confused. I tried this below the $selection part, just to start with something:
$anzahl_bestellungen = "SELECT COUNT(DISTINCT b_nummer) AS nr FROM kundenbestellungen";
$anzahl_bestellungen = mysqli_query ($dblink, $anzahl_bestellungen) OR die (mysqli_error($dblink));
$bestell = mysqli_fetch_array($anzahl_bestellungen);
print_r($bestell['nr']);
and the code counts the amount of the different order numbers (8). But if I use it without COUNT, it shows only the first order number (80425) and also counts only 1 result and doesn't get the other 7 numbers.
$anzahl_bestellungen = "SELECT DISTINCT b_nummer FROM kundenbestellungen";
$anzahl_bestellungen = mysqli_query ($dblink, $anzahl_bestellungen) OR die (mysqli_error($dblink));
$bestell = mysqli_fetch_array($anzahl_bestellungen);
print_r($bestell['b_nummer']);
$b = count($bestell['b_nummer']);
echo "<br>".$b;
I also tried to work something out with GROUP, but then the code shows only one item for each order number.
I tried to work with a for-loop as well, but that didn't work out either.
I thought about a multidimensional array, but I wasn't able to think through that whole thing, I'm not very good at php / mysqli.
So I have no idea how to go on. Maybe you can help me. This is my first question, so please let me know if I need to be more specific or you need more code or anything.
thanks a lot!
I have a while/for loop with thousands results. Since it contains several fields, I use table to display it. However, with thousands results being displayed at the same time, it will definitely slow down the performance. How can I display it in pagination?
<table>
<?php $count = 1000;
for($a=1;$a<=$count;$a++) { ?>
<tr>
<td><?php echo $a; ?></td>
<td>This is number <?php echo $a; ?></td>
</tr>
<?php $i++;
} ?>
</table>
My only solution without having a DB with the data would be to pass the array key you are on to the next page. For example:
$start = 1;
$end = 1000;
if(isset($_GET['record_number'])){
$start = $_GET['record_number'];
$end = $_GET['record_number'] + 1000;
}
for($a=$start; $a<=$end; $a++){
//code here
}
Other than that, you might consider creating a list of files in a DB engine so you can use the LIMIT parameter.
If the data comes from a database you can limit the result set. If you are using MySQL you use the LIMIT clause. This will allow you to only fetch the specified number of rows.
SELECT title, description FROM posts LIMIT 25
This will only fetch 25 rows. Then if you want to fetch the results after row 25 you can provide an offset. This is done a little different since the offset comes first in the LIMIT clause. Only one argument is provided MySQL assumes its the limit instead. To select the next 50 rows you use.
SELECT title, description FROM posts LIMIT 25, 50
This can be useful to reduce the result set fetched and help increase performance/load times due to a smaller amount of data that needs to be processed.
I hope this can help you, happy coding!
Update
This is a little tutorial in using the LIMIT clause in MySQL
Here is my example, it's similar to the answer from #AnotherGuy
<form method="GET">
<input type="text" name="rowsPerPage">
<?php
for($i = 1; $i+1 < $count/$rowsPerPage; $i++){
echo '<input type="submit" name="page" value="'.$i.'">';
}
?>
</form>
<?php
$begin = (int)$_GET['rowsPerPage']*$_GET['page'];
$take = (int)$_GET['rowsPerPage'];
$sql = "SELECT ... LIMIT {$begin}, {$take}";
?>
It's possible that the code contains "typos", but I hope it will give you new ideas.
I would recommend you to use GET instead of POST. GET will be saved in the URL, in this way, it will be easier to reload the page without losing the page-settings.
www.example.com?rowsPerPage=150&page=2
My connection to my database was successful. I now have all of the data from a table stored as an array in a php variable named $data. I am trying to extract three rows from this variable and display them with html.
Here is what my code looks like (with the exception of the connection info being removed):
<?php
$data = mysql_query("SELECT * FROM specs")
or die(mysql_error());
while ($row = mysql_fetch_assoc($data)) {
$rows[] = $row;
?>
I know that I can pull individual data from this variable and insert it into html successfully by entering code like this (for example):
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td>Model: <?php echo $row['name'];?></td>
</tr>
</table>
But my problem is that I want to display three separate rows of data from the database as three individual columns in a html table. (Hope that makes sense)
I've looked into how to do this with foreach and while but am not quite sure where I'm going wrong.
I'm hoping someone might be able to shed some light on this as I have read about foreach loops, while, and am still stuck! I'm also hearing that mysql_query is deprecated but ruled out not using this since our webserver is still using an old version of php and mysql and is not planning to update anytime soon.
Sorry if I'm not all here in my post - it's late and I'm tired. Thanks for your help in advance! I'll keep an eye on this in case anyone has questions.
This will print the array in a table with each row being 3 elements of the array.
echo "<table>";
for ($i = 0; $i < count($rows); $i += 3) {
echo "<tr>";
for ($j = 0; $j < 3; $j++) {
if (isset($rows[$i+$j]) {
echo "<td>Model: {$rows[$i+$j]['name']}</td>";
}
}
echo "</tr>";
}
echo "</table>";
It's simpler to limit the SQL to three rows, and then echo all incoming rows directly, without first adding to an array. That would waste resources.
<?php
echo "<table>";
$data = mysql_query("SELECT * FROM specs LIMIT 3")
or die(mysql_error());
while ($row = mysql_fetch_assoc($data))
echo '<tr></td>', $row['name'], '</td></tr>';
echo "</table>";
?>
Ah, but now I see it's a year old question. I hope you learned a lot in the meantime.
I am a neophyte programmer in php and I am always seeking for the solution of this problem. If anyone has an idea pls. post your answer and I am thankful for your great ideas to solve this stuff.
In my database table I have data like this:
In my php page I want to present in this way using html table.
Could anyone help me doing this stuff? Thank you very much…
I think you are searching for the functionality of GROUP_CONCAT in mysql (docs). You would get something like:
SELECT name, GROUP_CONCAT( week ), GROUP_CONCAT( there )
FROM presence
GROUP BY name;
which will return the following results you can parse using explode() in php (docs):
Andrew 4th,1st,3rd,2nd Present,Present,Present,Present
John 1st,4th,3rd,2nd Absent,Present,Present,Present
Mark 2nd,3rd,1st,4th Present,Present,Present,Present
Micheal 2nd,3rd,4th,1st Absent,Absent,Absent,Present
On a side note: If you haven't settled on a database scheme yet, it might be better to use an int for the week number column, as it is more reliable when sorting and easier to manipulate.
Sqlfiddle: http://sqlfiddle.com/#!2/fc785/1
Try this:
$SQL = "select NAME, WEEK, STATUS from tblattendance order by NAME, SUBSTRING(WEEK,1,LENGTH(WEEK) - 2) ASC";
$data = $db->query($SQL);
$last_name = "";
echo '<table><tr><th>NAME</th><th>1st WEEK</th><th>2nd WEEK</th><th>3rd WEEK</th><th>4th WEEK</th>';
while($row = $data->fetch_assoc()){
if($last_name != $row["NAME"]){
$last_name = $row["NAME"];
echo '</tr>';
echo '<tr>';
echo '<td>'.$row["NAME"].'</td>';
}
echo '<td>'.$row["STATUS"].'</td>';
}
echo '</tr></table>';
Try this :
$sql="select distinct name from tblattendance;";
$res=$mysqli->query($sql);
if($res){
while($row=$res->fetch_assoc()){
$name=$row['name'];
$sql="select week, status from tblattendance where name='$name';";
$res1=$mysqli->query($sql);
}
}
I'm working with symfony 1.4 and Doctrine. I'm writing an app about some pubs/bars, and I've got 4 tables:
products
orders
product_order
pubs.
I want to get the times all products have been ordered in the first pub (i.e. pubs.id = 1). This is what I've got, but I can only get the sum of the first product (products.id = 1) and I need the sum of all of them, in this case there are two different products in my db.
ProductOrderTable:
public function ordersGetCount(){
$q = Doctrine_Query::create()
->from('ProductOrder l')
->innerJoin('l.Order p ON l.id_order = p.id')
->select('SUM(l.amount) as units')
->andWhere('p.id_pub = 1')
->groupBy('l.id_product')
->orderBy('p.id');
return $q->execute();
}
Here my action class:
$this->resultCount= Doctrine_Core::getTable('productorder')->ordersGetCount();
And here my template:
for($i=0; $i<2; $i++){
echo "<tr>";
echo "<td>".$resultCount[0]->getUnits()[$i]."</td>";//
echo "<td>1</td>";
echo "<td>1</td>";
echo "</tr>";
}
Please need help :)
I think there's nothing wrong with your query, but you should have a look at how you display your results.
echo "<td>".$resultCount[0]->getUnits()[$i]."</td>";
Firstly, you're always referring to the first element in the $resultCount array. Secondly, I'm not sure if you can use a getter for a virtual column (you're not using a column which is mapped to your model.
So I would go with something like this:
In the ordersGetCount I would use
return $q->fetchArray();
This will return an array of arrays, not an array of objects, and will allow you to access the virtual column units.
To display the results:
<?php foreach ($resultCount as $row): ?>
<tr>
<td>
<?php echo $row['units']; ?>
</td>
<td>1</td>
<td>1</td>
</tr>
<?php endforeach ?>
EDIT:
This is quite strange ;) Can you try to build the query this way: (in theory it should be the same):
$q = $this->createQuery('l')
->select('l.id_product, sum(l.amount) as units')
->innerJoin('l.Order')
->where('p.id_pub = 1')
->groupBy('l.id_product')
->orderBy('p.id');
You must try remove
->groupBy('l.id_product')
it reduces you results to one product.