i am facing a hight load in my server ichecked all my code and all of it is OK but what i am not sure about it is the ( multiple columns ) code.
i use this one
$getpics = mysql_query("select id,image_thumb from pics order by id desc limit 0,10");
while ($result = mysql_fetch_assoc($getpics)) {
$data1[] = $result;
}
$data1 = array_chunk($data1, 5);
echo '<table width="100%" border="0" cellpadding="5">';
foreach ($data1 as $row1) {
echo '<tr>';
foreach ($row1 as $column1) {
echo '
<td align="center">
<div class="imagepic">
'.$column1[image_thumb].'
</div>
</td>
';
}
echo '</tr>';
}
echo '</table>';
mysql_free_result($getpics);
so now i am confuced is that code make load in my site.
regards
Instead of writing out each line, you could buffer the output.
$buf = "<table width="100%" border="0" cellpadding="5">";
foreach ($data1 as $row1) {
$buf .= "<tr>";
foreach ($row1 as $column1) {
$buf .= "<td align='center'>";
$buf .= "<div class='imagepic'>";
$buf .= $column1[image_thumb];
$buf .= "</div></td>";
}
$buf .= "</tr>";
}
$buf .= "</table>";
echo $buf;
The nested for loop probably doesn't help either. Directly accessing the columns by name or index is probably going to be faster.
I took the liberty of making some of the more modifications. I removed one of the loops, got rid of array_chunk, and some others. I didn't really see too much wrong with it, so the problem may very well be in something else, but let me know.
$getpics = mysql_query("select id,image_thumb from pics order by id desc limit 0,10");
$out = '<table width="100%" border="0" cellpadding="5">'; // Use a string and concat
$i = 0;
while ($row = mysql_fetch_assoc($getpics)) { // No need to loop twice. Once is fine,
if(!($i%5))$out .= '<tr>';
$out .= '<td align="center">
<div class="imagepic">
'.$row['id']. /*Do you REALLY want ID? That's what foreach will give you*/ '
</div>
</td>
<td align="center">
<div class="imagepic">
'.$row['image_thumb'].'
</div>
</td>';
$i++;
if(!($i%5))$out .= '</tr>'; // Inner loop removed. You're only selecting two columns!
}
if(($i%5))$out .= '</tr>'; // close the last row.
echo $out.'</table>';
mysql_free_result($getpics);
Obviously check for bugs before using.
You can buffer the output, but the PHP script is not the blocker here. The MySQL probably shouldn't be either, since you have a LIMIT set.
Can you run DESCRIBE SELECT on that query and report the load times? Do other pages load poorly on your host as well?
the php itself is not going to cause any load issues, unless there is something huge going on outside of the code you've shown here.
usually your query is the bottleneck, try running explain on your query eg. EXPLAIN SELECT ... in a tool like phpmyadmin or via the mysql command line, then post the output here.
your query is really simple though, and since you are ordering on id (primary key, auto increment I'm assuming) the issue is not likely mysql indexing.
IF the query is causing the issue, either check your indexes (could create an index on id,image_thumb) see http://dev.mysql.com/doc/refman/5.5/en/multiple-column-indexes.html , or use memcached as a temporary caching engine for your result set.
Related
Help me, i got stack when i want to make a dynamic table,
so the idea of the program is we can be costume a select field of database and can show it.
so if we have this field on table in database :
No
Name
age
Address
and we just want to show Name and Address, so i save the rule on the database (SELECT Name, Address)
but the problem is on the dynamic table when i show, how to make dynamic table when field always change (Example :Maybe the field just Age, or Name and age or we show all #its just from Configure that i make)
i have tried to make query result into an array and show it like this.
<table>
<?php for($x=0;$x<$length_array;$x++){ ?>
<tr>
<?php for($y=0;$y<$width_array;$y++){ ?>
<td><?php $result[$length_array][$width_array] ?></td>
<?php } ?>
</tr>
<?php } ?>
</table>
note : variable $result is from result query and i change it into an array, but the problem is i cann't count a length and width from array in this code.
It depends a bit on how your result set is returned, but based on your code above I'll assume your result is an array of arrays.
First think about what you want: you want an html table with a header that gives the name for each column, and then has a row for each record in your result set.
I very much dislike mixing php and html, so I will use a different syntax style, but the steps are the same no matter what style you use. This way makes the logic a lot easer to read.
First, make the table.
<?php
$html = '<table>';
Now you want to add a header to the table and create a cell for each column in your result. Before you do that, you need to answer: where are you going to get the names for you columns? There are two possible answers; 1) directly from the results of your query, or 2) hard-code them.
Getting them directly from the query results is much more flexible, but the names you give your database columns may not always be human-friendly.
$columnNames = ['Name', 'Address'];
---- OR ----
$firstRow = $result[0]; // of course we have checked that the result set is not empty!
$columnNames = array_keys($firstRow); // adjust if rows are objects instead of arrays
Now output the header:
$html .= '<thead>';
foreach($columnNames as $columnName) {
$html .= '<th>' . $columnName . '</th>';
}
$html .= '</thead>';
Now we can move on to the body, as in the answer to your previous question, creating a row in the table for each item in your result set. For each row you have an inner loop that creates the markup for each cell.
$html .= '<tbody>';
foreach($result as $row) {
$html .= '<tr>';
foreach($row as $cell) {
$html .= '<td>' . $cell . '</td>';
}
$html .= '</tr>';
}
$html .= '</tbody>';
$html .= '</table>';
print $html;
I'm attempting to create a dynamic table with MYSQL's function: while(mysql_fetch_assoc).. However, when it fetches more than one result, it doesn't create the table anymore (or fill in the tags. Excuse me for explaining this incorrectly)
This is my code. Ignore the Dutch words :)
$sql2 = mysql_query("SELECT * FROM kostendb WHERE ProjectID = '$_GET[id]'") or die (mysql_error());
echo '
<table border="1" style="width:60%">
<tr>
<th>Kostencode</th>
<th>Datum</th>
<th>Bedrag</th>
</tr>';
while($res = mysql_fetch_assoc($sql2))
{
echo '<tr>';
echo '<td>' .$res['KostenID']. '</td>';
echo '<td>' .$res['Datum']. '</td>';
echo '<td>' .$res['Bedrag']. '</td>';
echo '</tr>';
}
echo '</table>';
When it finds more than one result, the while-loop doesn't do anything. When it finds just one result, it works fine.
What is causing this, and how can I fix this?
I've checked out an example script, but it's exactly using my method.
Thanks
You might have mixed mysql with mysqli.
Choose one, don't mix and this might fix your problem.
make a variable like $project = $_GET['ID'];
then put in sql statement as ....WHERE Project_ID = $project");
Try this
I want to show the query results of mysql query in a table,
There are two tables, and some information has to be retrieved from the second table
I want to retrieve title, borrower name and borrower surname from other tables,
I tried to retrieve title, but I was unsuccessful,
Then I want to retrieve the borrower name and borrower surname from the users table
You may also offer a new way to put the results into a table
Here is the code
for($i=0;$i<999999999;$i++){
$sql="SELECT * FROM products WHERE product_id='$i' LIMIT 1";
//echo $sql;
$moviename="SELECT dbid FROM products WHERE product_id='$i'";
$dbid=mysql_query($moviename);
$movname="SELECT title FROM titles WHERE dbid='$dbid' ";
$name=mysql_query($movname);
$title=mysql_fetch_array($name);
print "<table border=1>
<tr><th>Product_ID</th>
<th>dbid</th>
<th>Title</th>
<th>Status</th>
<th>Date</th>
<th>Borrowe_id</th>
<th>Borrower Name</th>
<th>Borrower Surname</th></tr>";
$result=mysql_query($sql);
if($result==NULL){
continue ;
}
while ($row = mysql_fetch_array($result))
{
print "<tr><td>{$row[1]}</td>
<td>{$row[2]}</td>
<td>{$title[0]}</td>
<td>{$row[12]}</td>
<td>{$row[13]}</td>
<td>{$row[14]}</td>
<td>{$borrowername[0]}</td>
<td>{$borrowesurname[0]}</td></tr>";
}
print "</table>";
}
?>
There are a few things going on here which you should definitely not be doing.
Super insane loop with a query inside
for($i=0;$i<999999999;$i++){
// SELECT STATEMENT HERE!
}
Why are you looping potentially 999,999,999 times? And if you do you are going to hit your database 999,999,999 times? That is going to kill your database and it can be done much more efficiently.
Use joins over individual selects
$sql="SELECT * FROM products WHERE product_id='$i' LIMIT 1";
$moviename="SELECT dbid FROM products WHERE product_id='$i'";
$movname="SELECT title FROM titles WHERE dbid='$dbid' ";
Note:
product_id='$i' LIMIT 1
Usually you want your ids to be unique. Why do you need to LIMIT your query?
The query can be simplified to:
select
*
from
products p
left outer join titles t
on p.dbid = t.dbid
Note: SELECTING * IS BAD PRACTICE, BUT I DON'T KNOW WHAT YOUR STRUCT IS
Illogical logic
if($result==NULL){
continue ;
}
while ($row = mysql_fetch_array($result)) {...}
$result is null at this point, so your while loop will never happen.
So after killing that loop, simplifying the query, and revising logic... we can do:
$result_resource = mysql_query($sql);
echo"
<table border=1>
<tr>
<th>Product_ID</th>
<th>dbid</th>
<th> Title</th>
<th>Status</th>
<th>Date</th>
<th>Borrowe_id</th>
<th>Borrower Name</th>
<th>Borrower Surname</th>
</tr>";
while ($row = mysql_fetch_array($result_resource))
{
echo "
<tr>
<td>{$row['ProductID']}</td>
<td>{$row['dbid']}</td>
<td>{$row['Title']}</td>
<td>{$row['Status']}</td>
<td>{$row['Date']}</td>
<td>{$row['Borrowe_id']}</td>
<td>{$borrowername[0]}</td>
<td>{$borrowesurname[0]}</td>
</tr>";
}
echo "</table>";
Looking at $borrower.... I have a feeling you can also join your borrow table to the query to bring that in too.
I would also look into templating. It would definitely separate your data from your display and make your code a lot easier to read.
First,you should debug your code
one thing that pops up is the following error:
you should change the following from:
print "<tr><td>{$row[1]}</td>
<td>{$row[2]}</td> ..."
to:
print "<tr><td>{" . $row[1] . "}</td>
<td>{" . $row[2] . "}</td> ..."
Second, when you say " I was unsuccessful" - please add details, did you get an error ? what was the output ?
(Maybe your question is "too localize")
First I don't recommend this :
for($i=0;$i<999999999;$i++)
because it will take long for the server to compute, and generate a lot of mysql query.
Second, most (all?) of your mysql queries could be merge in only one query.
You can about query on more then one table here (dev.mysql.com) There's several way to join multiples tables, you could read about it
Third, in your code the table header will be repeated each time, because it's in your For loop.
here my suggest to improve your code :
//Print the header
print "<table border=1>
<tr><th>Product_ID</th>
<th>dbid</th>
<th>Title</th>
<th>Status</th>
<th>Date</th>
<th>Borrowe_id</th>
<th>Borrower Name</th>
<th>Borrower Surname</th></tr>";
//adapt the following sql with your tables name / fields
$sql="SELECT products.product_id, products.dbid, title.tiles, product.status, product.date, borrow.id , borrow.name, borrow.surname FROM products,titles,borrow WHERE product.dbid = titles.dbid && borrow.id = product.prodict_id LIMIT 1";
$result=mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
print "<tr><td>{$row[1]}</td>
<td>{$row[2]}</td>
<td>{$row[3]}</td>
<td>{$row[4]}</td>
<td>{$row[5]}</td>
<td>{$row[6]}</td>
<td>{$row[7]}</td>
<td>{$row[8]}</td></tr>";
}
print "</table>";
?>
I know that the sql query isn't the best one, but I think those suggestions could help you.
Here is a function for you to convert any MySQL select statement to a HTML table with table headings.
function createTable_from_sql_select_query($query) {
$sql_link = Connect_MySQLi_DB(); // Your Database Connection
$sql_link->set_charset("utf8");
$result = $sql_link->query($query);
// Adding Missing Array Column Function for Old PHP Versions (<5.5)
if (!function_exists('array_column')) {
function array_column($array, $column) {
$ret = array();
foreach ($array as $row)
$ret[] = $row[$column];
return $ret;
}
}
$headings = json_decode(json_encode($result->fetch_fields()), true);
$headings = array_column($headings, 'name');
$return = '<table>';
$return .= '<thead><tr>';
for ($x = 0; $x <= (count($headings) - 1); $x++) {
$return .= '<th>' . ucwords(str_replace('_', ' ', (strtolower($headings[$x])))) . '</th>';
}
$return .= '</tr></thead><tbody>';
while ($row = $result->fetch_object()) {
$return .= '<tr>';
for ($x = 0; $x <= (count($headings) - 1); $x++) {
$return .= '<td>' . $row->$headings[$x] . '</td>';
}
$return .= '</tr>';
}
$return .= '</tbody></table>';
return $return;
}
The code belows gives me only 18 records
<?php
$result4 = mysql_query("select Distinct Country from trendsmtable where WHORegionAC='Europe - all countries' GROUP BY Country ");
echo "<table width=880 align=center>";
echo "<tr><td colspan=4 style='font-family:Arial;'><b>European Region</b></td></tr>";
$num_columns4 = 4;
$num_rows4 = mysql_num_rows($result4);
$i=0;
while($row4 = mysql_fetch_assoc($result4)){
$results[$i] = $row4['Country'];
$i++;
}
unset($i);
$k=0;
for ($i=0;$i<=($num_rows4/($num_columns4+1));$i++){
echo '<tr>';
for($j=1;$j<=$num_columns4;$j++){
echo "<td width=220 style='font-family:Arial; font-size:12px'>".$results[$k].'</td>';
$k++;
}
echo '</tr>';
$k++;
}
echo "</table>";
?>
while the select statement
select Distinct Country from trendsmtable where WHORegionAC='Europe -
all countries'
returns 22 rows while I execute it in mysql which is correct!
Please help me to found the error.
Well, you have an extra $k++ in there that you don't need:
$k++; // keep this one
}
echo '</tr>';
$k++; // remove this one
}
Edit
I've gone through your code and I've made some edits. Hopefully they'll clean your issue along the way:
// got rid of group by. With a select distinct, it isn't necessary
$result4 = mysql_query("select Distinct Country from trendsmtable where ".
"WHORegionAC='Europe - all countries'");
// a good practice is to always double-quote your HTML attributes.
echo "<table width=\"880\" align=\"center\">";
echo "<tr><td colspan=4 style=\"font-family:Arial;\">".
"<b>European Region</b></td></tr>";
$num_columns4 = 4; // where does 4 come from.
// $results was never initialized before.
$results = array();
while($row4 = mysql_fetch_assoc($result4)){
// This is generally thought of as "cleaner" than using an index.
// And since there cannot be more than, say, 220 rows, cleanliness
// should be a high-priority standard.
$results[] = $row4['Country'];
}
// mysql_num_rows rarely provides any major benefit at all.
$num_rows4 = count($results);
foreach( $results as $key => $val )
{
// This happens every time we fill all columns and need a new row.
if( !( $key % $num_columns4 ) )
{
// makes it so that after the first time this closes the prev
// row before starting a new one.
if( $key ) echo '</tr>';
echo '<tr>';
}
// insert nag about CSS
echo '<td width="220" style="font-family:Arial; font-size:12px">'.
$val.
'</td>';
}
echo '</tr></table>';
I think the PHP looks a little odd, it looks like you are looping from 0 to (22 / 5)
then in the inner loop 4 times.
The group by should not make any difference as you are doing a select distinct
Your SQL code in the PHP file contains a GROUP BY clause, which can reduce the number of rows returned, if you have a country more than once in the db.
Running a mysql query that returns users with their daily highscores.
This is the php file that displays the highscore:
<table border="0" width="100%"><?php echo highscore()?>
</table>
This is the php that handles the mysql query (highscore function):
echo '<tr>';
echo '<td>'.$user.'</td><td align="right">'.$score.'</td>';
echo '</tr>';
The mysql query that I have results in the user with the highest score getting on top of the table that you see above.
Now I would like to add a crown to the user that has the most points.
The question is how to add an image(crown.png) to the first row which is the user with the highest score.
Thanks in advance.
I assume you order users by score DESC.
$set = 0;
while() {
echo '<tr';
echo '<td>';
if(!$set) {
echo '<img src="crown.png" alt="crown" />';
}
// ... the rest of the code
$set = 1;
}
if (empty($notfirst)){
echo "crown";
$notfirst=1;
}
i only see a quick and dirty solution, given the code you provide.
I guess you call this code in a loop?
echo '<tr>';
echo '<td>'.$user.'</td><td align="right">'.$score.'</td>';
echo '</tr>';
so just declare a variable before you start the loop:
$first = true;
then inside your loop, change your code to:
echo '<tr>';
echo '<td>'.$user.'</td><td align="right">'.$score.'</td><td>'.$first?'<img src=\"crown.png\" />':''.'</td>';
echo '</tr>';
$first = false;
If you wanted to do this sans PHP you could make your table and use CSS3's new :first-child pseudo-selector to add the crown as a background image to the first row.
table tr:first-child { background: url("crown.gif") no-repeat; }