So I decided to finally move over to PDO instead of using the old mysql_
But I noticed my site is loading slower. It's a table with 500 lines, and with my mysql_ queries it loaded slightly faster (0.5-1 second faster).
I wonder if it's just the way PDO works or if I've made some mistake somewhere. I did not change much from MySQL to PDO.
Here is my original mysql_ code:
<?php
$sql = mysql_query("SELECT * FROM rookstayers ORDER BY level DESC LIMIT 0, 500");
$id = 1;
$last_player_lvl = '';
while($row = mysql_fetch_array($sql)){
$name = $row['name'];
$level = $row['level'];
$world = $row['world'];
$account = $row['accountstatus'];
$status = $row['onlinestatus'];
$country = $row['country'];
$lastlogindate = $row['lastlogin'];
$lastlogin2 = utf8_decode($lastlogindate);
$lastlogin = str_replace("?", " ", $lastlogin2);
$onrow = '';
$typeServ = '';
$Date = $lastlogin;
$Date = substr($Date, 0, strpos($Date, " CE"));
$now = date('Y-m-d');
$datetime1 = new DateTime($Date);
$datetime2 = new DateTime($now);
$interval = $datetime1->diff($datetime2);
$difference = $interval->format('%a days ago');
$player_name = urlencode($name);
if ($status == 1){
$status = 'Online';
$onrow = 'online';
} else {
$status = 'Offline';
$onrow = 'offline';
}
if ($account == 'Premium Account'){
$account = 'Premium';
} else {
$account = 'Free';
}
if ($world == 'Aurora' || $world == 'Aurera'){
$typeServ = 'activer';
} else {
$typeServ = '';
}
echo "<tr class=" . $typeServ . ">";
echo "<td align='right'>" . ( ($last_player_lvl == $row['level']) ? '' : $id ) . "</td>";
echo "<td align='center'><img src='../img/flags/" . $country . ".gif'></td>";
echo "<td><div class='". $onrow ."'></div></td>";
echo "<td><a href='../char/" . $player_name . "' class='playerlink'>" . $name . "</a></td>";
echo "<td>" . $level . "</td>";
echo "<td><a href='../world/" . $world ."' class='worldlink'>" . $world . "</a></td>";
echo "<td>"; if ($difference == 0){ echo "Today"; } elseif($difference == 1) { echo "Yesterday"; } else { echo $difference; } echo "</td>";
echo "<td>" . $account . "</td>";
echo "</tr>";
// Check if there are duplicate levels, if so, give them the same rank
if($last_player_lvl == $row['level']){
$id = $id;
}else{
$id++;
}
$last_player_lvl = $row['level'];
}
echo "</tbody>";
echo "</table>";
?>
and here is my PDO code
<?php
$sql = 'SELECT * FROM rookstayers ORDER BY level DESC LIMIT 0, 500';
$id = 1;
$last_player_lvl = '';
foreach ($db->query($sql) as $row) {
$name = $row['name'];
$level = $row['level'];
$world = $row['world'];
$account = $row['accountstatus'];
$status = $row['onlinestatus'];
$country = $row['country'];
$lastlogindate = $row['lastlogin'];
$lastlogin2 = utf8_decode($lastlogindate);
$lastlogin = str_replace("?", " ", $lastlogin2);
$onrow = '';
$typeServ = '';
$Date = $lastlogin;
$Date = substr($Date, 0, strpos($Date, " CE"));
$now = date('Y-m-d');
$datetime1 = new DateTime($Date);
$datetime2 = new DateTime($now);
$interval = $datetime1->diff($datetime2);
$difference = $interval->format('%a days ago');
$player_name = urlencode($name);
if ($status == 1){
$status = 'Online';
$onrow = 'online';
} else {
$status = 'Offline';
$onrow = 'offline';
}
if ($account == 'Premium Account'){
$account = 'Premium';
} else {
$account = 'Free';
}
if ($world == 'Aurora' || $world == 'Aurera'){
$typeServ = 'activer';
} else {
$typeServ = '';
}
echo "<tr class=" . $typeServ . ">";
echo "<td align='right'>" . ( ($last_player_lvl == $row['level']) ? '' : $id ) . "</td>";
echo "<td align='center'><img src='../img/flags/" . $country . ".gif'></td>";
echo "<td><div class='". $onrow ."'></div></td>";
echo "<td><a href='../char/" . $player_name . "' class='playerlink'>" . $name . "</a></td>";
echo "<td>" . $level . "</td>";
echo "<td><a href='../world/" . $world ."' class='worldlink'>" . $world . "</a></td>";
echo "<td>"; if ($difference == 0){ echo "Today"; } elseif($difference == 1) { echo "Yesterday"; } else { echo $difference; } echo "</td>";
echo "<td>" . $account . "</td>";
echo "</tr>";
// Check if there are duplicate levels, if so, give them the same rank
if($last_player_lvl == $row['level']){
$id = $id;
}else{
$id++;
}
$last_player_lvl = $row['level'];
}
echo "</tbody>";
echo "</table>";
?>
maybe something to improve when it comes to the PDO part?
You are executing the query on every iteration of your foreach loop. See update.
Try replacing
foreach ($db->query($sql) as $row) { ...
with
$result = $db->query($sql);
foreach ($result as $row) {
Update: #mario is right. The foreach does't evaluate the expression on each iteration. I can't seem to find a conclusive answer as to why this would have solved the OPs issue; I still think there is something to it, but even in my own tests it seems that using the variable doesn't seem to have any significant effect on performance. If anyone has any more details to add, please do. :)
Related
I need a help in a query rows creating a table through php. Here below is the rows in my mysql table named "routine".
Now i want to fetch through week days in a single loop creating a table like below:
Is it possible with a single loop? Here i want to separate the rows through week and auto columns through time.
Yes! It is possible with single loop but we use php array...
Try this...
Data insertion php coding - insert.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "my_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
$week = "Friday";
$subject = "Physics";
$time = 3;
$sql = "INSERT INTO routine (Week, Subject, Time)VALUES ('".$week."', '".$subject."', '".$time."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Php code for displaying rows through week and auto columns through time - view.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "my_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
//Initial Declarations
$data = [];
$data[0][0] = "<tr><td>Week</td>";
$data[0][1] = "<tr><td>Monday</td>";
$data[0][2] = 0;
$data[1][0] = "<tr><td>Week</td>";
$data[1][1] = "<tr><td>Tuesday</td>";
$data[1][2] = 0;
$data[2][0] = "<tr><td>Week</td>";
$data[2][1] = "<tr><td>Wednesday</td>";
$data[2][2] = 0;
$data[3][0] = "<tr><td>Week</td>";
$data[3][1] = "<tr><td>Thursday</td>";
$data[3][2] = 0;
$data[4][0] = "<tr><td>Week</td>";
$data[4][1] = "<tr><td>Friday</td>";
$data[4][2] = 0;
$sql = "SELECT * FROM routine";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result, MYSQLI_NUM)) // Table Fields - Week ($row[0]), Subject($row[1]), Time($row[2])
{
if($row[0] == "Monday")
{
$data[0][0] = $data[0][0] . "<td>" . $row[2] . "</td>";
$data[0][1] = $data[0][1] . "<td>" . $row[1] . "</td>";
$data[0][2] = intval($data[0][2]) + 1;
}
else if($row[0] == "Tuesday")
{
$data[1][0] = $data[1][0] . "<td>" . $row[2] . "</td>";
$data[1][1] = $data[1][1] . "<td>" . $row[1] . "</td>";
$data[1][2] = intval($data[1][2]) + 1;
}
else if($row[0] == "Wednesday")
{
$data[2][0] = $data[2][0] . "<td>" . $row[2] . "</td>";
$data[2][1] = $data[2][1] . "<td>" . $row[1] . "</td>";
$data[2][2] = intval($data[2][2]) + 1;
}
else if($row[0] == "Thursday")
{
$data[3][0] = $data[3][0] . "<td>" . $row[2] . "</td>";
$data[3][1] = $data[3][1] . "<td>" . $row[1] . "</td>";
$data[3][2] = intval($data[3][2]) + 1;
}
else if($row[0] == "Friday")
{
$data[4][0] = $data[4][0] . "<td>" . $row[2] . "</td>";
$data[4][1] = $data[4][1] . "<td>" . $row[1] . "</td>";
$data[4][2] = intval($data[4][2]) + 1;
}
}
//Final Assigning
$data[0][0] = $data[0][0] . "</tr>";
$data[0][1] = $data[0][1] . "</tr>";
$data[1][0] = $data[1][0] . "</tr>";
$data[1][1] = $data[1][1] . "</tr>";
$data[2][0] = $data[2][0] . "</tr>";
$data[2][1] = $data[2][1] . "</tr>";
$data[3][0] = $data[3][0] . "</tr>";
$data[3][1] = $data[3][1] . "</tr>";
$data[4][0] = $data[4][0] . "</tr>";
$data[4][1] = $data[4][1] . "</tr>";
// Display Result
if($data[0][2] > 0)
echo "<table border='1' cellspacing = 0 cellpadding = '4'>".$data[0][0] . $data[0][1] . "</table><br>";
if($data[1][2] > 0)
echo "<table border='1' cellspacing = 0 cellpadding = '4'>".$data[1][0] . $data[1][1] . "</table><br>";
if($data[2][2] > 0)
echo "<table border='1' cellspacing = 0 cellpadding = '4'>".$data[2][0] . $data[2][1] . "</table><br>";
if($data[3][2] > 0)
echo "<table border='1' cellspacing = 0 cellpadding = '4'>".$data[3][0] . $data[3][1] . "</table><br>";
if($data[4][2] > 0)
echo "<table border='1' cellspacing = 0 cellpadding = '4'>".$data[4][0] . $data[4][1] . "</table><br>";
?>
How can I put identical columns (sorted by "level" in this case) together? I am making a highscore where I list them by level from my database. I want them to have the same ID if they are the same level.
But I do not want to display the ID on the others. Only the first one.
Here is an example:
ID - Name - Level
1 - John - 5
2 - David - 4
3 - Josh - 3
- Sam - 3
4 - George - 2
So I want to put them together, but if they have the same level, only the first one displays the ID.
I don't want it to look like:
1 - John - 5
2 - David - 4
3 - Josh - 3
3 - Sam - 3
4 - George - 2
Right now, it is just listing everyone, and giving each one a unique ID. Even if they have the same "level".
How can I fix this? Here is my code:
<?php
$sql = mysql_query("SELECT * FROM rookstayers ORDER BY level DESC LIMIT 0, 500");
$id = 1;
while($row = mysql_fetch_array($sql)){
$name = $row['name'];
$level = $row['level'];
$world = $row['world'];
$account = $row['accountstatus'];
$status = $row['onlinestatus'];
$onrow = '';
$typeServ = '';
$player_name = urlencode($name);
if ($status == 1){
$status = 'Online';
$onrow = 'online';
} else {
$status = 'Offline';
$onrow = 'offline';
}
if ($account == 'Premium Account'){
$account = 'Premium';
} else {
$account = 'Free';
}
if ($world == 'Aurora' || $world == 'Aurera'){
$typeServ = 'active';
} else {
$typeServ = '';
}
echo "<tr class=" . $typeServ . ">";
echo "<td>" . $id . "</td>";
echo "<td>" . $name . " <a href='http://www.tibia.com/community/?subtopic=characters&name=" . $player_name . "' target='_blank'><img src='../../img/websites/tibia.png' title='Tibia Profile'></a><a href='http://www.pskonejott.com/otc_display.php?character=" . $player_name . "' target='_blank'><img src='../../img/websites/pskonejott.png' title='Pskonejott'></a>" . "</td>";
echo "<td>" . $level . "</td>";
echo "<td>" . $world . "</td>";
echo "<td>" . $account . "</td>";
echo "<td class=" . $onrow . ">" . $status . "</td>";
echo "</tr>";
$id++;
}
echo "</tbody>";
echo "</table>";
?>
you can create a temporary variable for the current level and check it to see if the id will be shown on the output or not.
$id = 1;
$last_player_lvl = '';
while($row = mysql_fetch_array($sql)){
///....
echo "<tr class=" . $typeServ . ">";
echo "<td>" . ( ($last_player_lvl == $row['level']) ? '' : $id ) . "</td>";
echo "<td>" . $name . " <a href='http://www.tibia.com/community/?subtopic=characters&name=" . $player_name . "' target='_blank'><img src='../../img/websites/tibia.png' title='Tibia Profile'></a><a href='http://www.pskonejott.com/otc_display.php?character=" . $player_name . "' target='_blank'><img src='../../img/websites/pskonejott.png' title='Pskonejott'></a>" . "</td>";
echo "<td>" . $level . "</td>";
echo "<td>" . $world . "</td>";
echo "<td>" . $account . "</td>";
echo "<td class=" . $onrow . ">" . $status . "</td>";
echo "</tr>";
if($last_player_lvl == $row['level']){
$id = $id;
}else{
$id++;
}
$last_player_lvl = $row['level'];
//....
I'm trying to change the output of a variable from 0 to display user or from 1 to display superuser,
<?php
$result = mysql_query("SELECT * FROM users ") or trigger_error(mysql_error());
$tv = nl2br($row['type']);
if ($tv == '0') {
$tv = 'user';
} elseif ($tv == '3') {
$tv = 'superuser';
} else {
$tv = 'N/A';
}
while($row = mysql_fetch_array($result)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
echo "<tr>";
echo "<td>" . nl2br( $row['name'] . "</td>";
echo "<td>" . nl2br( $row['email']) . "</td>";
echo "<td>" . $tv . "</td>";
echo "</tr>";
}
?>
i know I'm validating the data before i do the mysql_fetch_array and that should do it after, but i wasn't able to put the if statement in the echo
any help pls ?
You can't access $row before it is set, you can alter your echo line for $row['type'] like this:
if ($row['type'] == 0) { echo 'user'; } else if ($row['type'] == 1) { echo 'superuser';} else {echo 'NA'; }
<?php
$result = mysql_query("SELECT * FROM users ") or trigger_error(mysql_error());
while($row = mysql_fetch_array($result)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
echo "<tr>";
echo "<td>" . nl2br( $row['name'] . "</td>";
echo "<td>" . nl2br( $row['email']) . "</td>";
echo "<td>"; if ($row['type'] == 0) { echo 'user'; } else if ($row['type'] == 1) { echo 'superuser';} else {echo 'NA'; } echo "</td>";
echo "</tr>";
}
?>
I'm sure you have a reason for using nl2br, but I totally don't get it.
As #Zarathuztra has mentionend, please change to mysqli_ or PDO, mysql_ is not the way to go as it is deprecated
I want to print mysql_query result in a table. I know how to do it but I am just confused. I tried this.
<?php
mysql_connect("localhost","root","") or die("Could not Connect.");
mysql_select_db("check") or die("Could not Select DB");
$table = "cc";
$i = 1;
$query = "select * from $table";
$sql = mysql_query($query);
if($sql){
echo "<table border='5'><tr>";
while($i<=2 && $row = mysql_fetch_array($sql)){
echo "<td>" . $row[id] . " : " . $row[name] . "</td>";
++$i;
}
echo "</tr><tr>";
while($i<=4 && $row = mysql_fetch_array($sql)){
echo "<td>" . $row[id] . " : " . $row[name] . "</td>";
++$i;
}
echo "</tr><tr>";
while($i<=6 && $row = mysql_fetch_array($sql)){
echo "<td>" . $row[id] . " : " . $row[name] . "</td>";
++$i;
}
echo "</tr><tr>";
while($i<=8 && $row = mysql_fetch_array($sql)){
echo "<td>" . $row[id] . " : " . $row[name] . "</td>";
++$i;
}
echo "</tr><tr>";
echo "</tr></table>";
}
?>
As you can see it is written again and again with a slight change of 2,4,6,8 in the while loop. It works but the problem is I cant rewrite it again and again as when the website will go live it will have more than 1000 entries. Could You guys help me out by suggesting another way to do this?
""** I need it to be like these dots (dots represent records in the database) **"""
. . . .
. . . .
. . . .
THANKS in Advance.
Ramzy
<?php
mysql_connect("localhost","root","") or die("Could not Connect.");
mysql_select_db("check") or die("Could not Select DB");
$table = "cc";
$query = "select * from $table";
$sql = mysql_query($query);
if($sql){
echo "<table border='5'><tr>";
while($row = mysql_fetch_array($sql)){
echo "<td>" . $row['id'] . " : " . $row['name'] . "</td>";
}
echo "</tr></table>";
}
?>
while($row = mysql_fetch_array($sql)) {
echo "<td>" . $row['id'] . " : " . $row['name'] . "</td>";
}
I don't really see what's the problem here.
By the way you should never call you're array like this $row[id] but you should quote the key instead $row['id']; Because if a constant id exists it will screw up your code and also for performance reason.
Just use
$limit = 1000;//place any value you need here to limit the number of rows displayed
while ($i<=$limit && $row = mysql_fetch_array($sql)){
echo "<td>" . $row['id'] . " : " . $row['name'] . "</td>";
++$i;
}
Also, that limit is unnecessary if all you want is to flush every record to the output. You could just do
while ($row = mysql_fetch_array($sql)){
echo "<td>" . $row['id'] . " : " . $row['name'] . "</td>";
}
And it will stop as soon as there are no more records.
To print all database rows into an HTML-table, use:
echo '<table>';
$i = 0; // $i is just for numbering the output, not really useful
while($row = mysql_fetch_array($sql))
{
echo '<tr><td>' . $i . ' - ' . $row['id'] . ' : ' . $row['name'] . '</td></tr>';
$i++;
}
echo '</tr></table>';
here is a general function I use:
function query_result_to_html_table($res, $table_id = NULL, $table_class = NULL, $display_null = true)
{
$table = array();
while ($tmp = mysql_fetch_assoc($res))
array_push($table, $tmp);
if (!count($table))
return false;
echo "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" "
. ($table_id ? "id=\"$table_id\" " : "")
. ($table_class ? "class=\"$table_class\" " : "") . ">";
echo "<tr>";
foreach (array_keys($table[0]) as $field_name) {
echo "<th>$field_name";
}
foreach ($table as $row) {
echo "<tr>";
foreach ($row as $col => $value) {
echo "<td>";
if ($value === NULL)
echo "NULL";
else
echo $value;
}
echo "\n";
}
echo "</table>\n";
return true;
}
I Got The Answer.. I wanted it to be like this. I made this and It Actually Works.
<?php
$i = 1;
mysql_connect("localhost" , "root" , "") or die('Could not Connect.');
mysql_select_db("db") or die('Could not select DB.');
$query = "select * from `check`";
$sql = mysql_query($query) or die(mysql_error());
echo "<table border='5' width='50%'><tr><th>Name</th><th>Gender</th></tr></table><table border='5' width='50%'><tr>";
if($i<3){
echo "<td align='center'>".$row['name']."</td>";
echo "<td align='center'>".$row['gender']."</td>";
++$i;
} else {
echo "<td align='center'>".$row['name']."</td><td align='center'>".$row['gender']."</td>";
echo "</tr>";
$i = 1;
echo "<tr>";
}
}
echo "</table>";
?>
</div>
Thank You Guys For Your Support
Hey guys, first time using stackoverflow.
can you guys help me debug?
Heres the problem, this query is selecting all of the rows from my database, its only outputting the first one twice for some reason.
$top10_query = "SELECT * FROM kicks";
$result = mysqli_query($cxn, $top10_query) or die("Couldn't execute query.");
$row = mysqli_fetch_assoc($result);
$rating = $row['rating'];
$description = $row['description'];
$completed = $row['completed'];
$userid = $row['userid'];
$posted = $row['posted'];
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td class='rating'>" . $rating . "</td>";
echo "<td class='description'>" . $description . " </td>";
echo "<td class='completed_" . $completed . "'>" . $completed . "</td>";
echo "<td class='author'>";
echo "Posted by: <a href='profile?userid=" . $userid . "'>" . $userid . "</a><br />";
echo "on "; echo $posted;
echo "</td>";
echo "</tr>";
}
You are looping over the rowset, but never retrieving its value more than once. You pulled all of the values out of the first row, and cached them here:
$rating = $row['rating'];
$description = $row['description'];
$completed = $row['completed'];
$userid = $row['userid'];
$posted = $row['posted'];
Move this code into the loop, and remove the first fetch.
You need to update $rating, $description, etc. within the while loop:
<?php
$top10_query = "SELECT * FROM kicks";
$result = mysqli_query($cxn, $top10_query) or die("Couldn't execute query.");
while($row = mysqli_fetch_assoc($result)) {
$rating = $row['rating'];
$description = $row['description'];
$completed = $row['completed'];
$userid = $row['userid'];
$posted = $row['posted'];
echo "<tr>";
echo "<td class='rating'>" . $rating . "</td>";
echo "<td class='description'>" . $description . " </td>";
echo "<td class='completed_" . $completed . "'>" . $completed . "</td>";
echo "<td class='author'>";
echo "Posted by: <a href='profile?userid=" . $userid . "'>" . $userid . "</a><br />";
echo "on "; echo $posted;
echo "</td>";
echo "</tr>";
}
?>
Or, of course, you can inline $rating, etc., writing $row['rating'] instead.
Note: you probably want to run your variables through htmlspecialchars before inserting them into HTML. Otherwise, a description like <script>alert('hacked');</script> could execute a script, opening yourself up to XSS attacks.
You can also use extract. I do not recommend you do this, however, as it may cause problems and confusion for other developers:
<?php
$top10_query = "SELECT * FROM kicks";
$result = mysqli_query($cxn, $top10_query) or die("Couldn't execute query.");
while($row = mysqli_fetch_assoc($result)) {
extract($row);
echo "<tr>";
echo "<td class='rating'>" . $rating . "</td>";
echo "<td class='description'>" . $description . " </td>";
echo "<td class='completed_" . $completed . "'>" . $completed . "</td>";
echo "<td class='author'>";
echo "Posted by: <a href='profile?userid=" . $userid . "'>" . $userid . "</a><br />";
echo "on "; echo $posted;
echo "</td>";
echo "</tr>";
}
?>
The variables $rating etc are not "binded" to the expressions $row['rating'] etc. Once set, They will forever take these values unless you modify them again.
See PHP: Assignment Operators for detail.
Try to rewrite them as:
$top10_query = "SELECT * FROM kicks";
$result = mysqli_query($cxn, $top10_query) or die("Couldn't execute query.");
while($row = mysqli_fetch_assoc($result)) {
$rating = $row['rating']; // <-- use the new value every time a row is fetched.
$description = $row['description'];
$completed = $row['completed'];
$userid = $row['userid'];
$posted = $row['posted'];
echo "<tr>";
echo "<td class='rating'>" . $rating . "</td>";
echo "<td class='description'>" . $description . " </td>";
echo "<td class='completed_" . $completed . "'>" . $completed . "</td>";
echo "<td class='author'>";
echo "Posted by: <a href='profile?userid=" . $userid . "'>" . $userid . "</a><br />";
echo "on "; echo $posted;
echo "</td>";
echo "</tr>";
}