I've been working on getting an RSS feed setup and with the help of some people here I got it done. However, I really need some advice from some of you more experienced coders to show me what needs to be changed to keep the same functionality but speed up the page load.
It looks 30 RSS items and gets the URLs from my MySQL database. The problem is that it randomly selects 30 rows out of over 100 million rows in that table. That is what it's supposed to do, but with their being so many rows in the table, it's really slowing down the script and I need help!
<?php header("Content-type: text/xml"); ?>
<?php echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; ?>
<?php include('directory/database.php'); ?>
<rss version="2.0">
<channel>
<title>Website Reviews</title>
<link>http://www.mywebsite.com</link>
<description>Professional Services</description>
<pubDate><?echo date('Y/m/d H:i:s');?></pubDate>
<?php
foreach( range( 1, 30 ) as $i ):
$number = mt_rand( 1, 141754641 );
$query="SELECT * FROM `list` LIMIT $number , 1";
$result = mysql_query($query);
if($result == false)
{
user_error("Query failed: " . mysql_error() . "<br />\n$query");
}
elseif(mysql_num_rows($result) == 0)
{
echo "<p>Sorry, we're updating this section of our website right now!</p>\n";
}
else
{
while($query_row = mysql_fetch_assoc($result))
{
foreach($query_row as $key => $domain)
{
echo "$value";
}
}
}
?>
<item>
<title><?php echo $domain; ?> REVIEW</title>
<pubDate><?echo date('Y/m/d H:i:s');?></pubDate>
<link>http://www.mywebsite.com/review/<?php echo $domain; ?></link>
<description>Looking for a review on <?php echo $domain; ?>? We've got it!</description>
</item>
<?php endforeach; ?>
</channel>
</rss>
Thanks in advance for any help that anyone can give!
Limit has to do table scans, so what you want to do is use indexes to your advantage. So first, let's add an autoincrement ID field to the table named "id".
Then,
<?php
$result = array();
$maxRow = mysql_fetch_assoc(mysql_query("SHOW TABLE STATUS LIKE 'list';"));
$max = $maxRow["Auto_increment"];
$minRow = mysql_fetch_assoc(mysql_query("SELECT id FROM 'list' LIMIT 1;"));
$min = $minRow["id"];
while (count($result) < 30) {
$ids = array();
while (count($ids) < 100) {
$id = mt_rand($min, $max);
$ids[$id] = 1;
}
$res = mysql_query("SELECT * from 'list' WHERE id IN (" . join(',', array_keys($ids)) . ") LIMIT 30");
while (($row = mysql_fetch_assoc($result)) && (count($result) < 30)) {
$result[] = array( ... ); // stuff results here
}
}
// output
?>
You can still select all 30 at once. It shouldn't be that slow to get 30 records.
$numbers=array();
foreach( range( 1, 30 ) as $i ):
$numbers[] = mt_rand( 1, 141754641 );
endforeach;
$query="SELECT * FROM `list` WHERE `whatever_primary_key_is` IN (".implode(',', $numbers).")";
May i suggest a more robust approach.
You have to take in account that the number you go look for may not exist
Only using one MySql query is often faster
Base on url1 and url2
You can have this php code instead :
<?php
// Connecting, selecting database
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password') or die('Could not connect: ' . mysql_error());
mysql_select_db('my_database') or die('Could not select database');
$query = "SELECT `url`
FROM `liste`
ORDER BY RAND()
LIMIT 30" ;
$result = mysql_query($query);
if($result == false)
{
user_error("Query failed: " . mysql_error() . "<br />\n$query");
}
elseif(mysql_num_rows($result) == 0)
{
echo "<p>Sorry, we're updating this section of our website right now!</p>\n";
}
else
{ $query_row = array();
while($query_row = mysql_fetch_assoc($result))
{
echo $query_row['url']; // no need to do the extra foreach
}
}
?>
The values mysql_host,mysql_user,mysql_password,my_database should be replaced by your connection.
As long as you have 30 row in your title table your are ok.
Related
How can I add pagination to a search engine results page?
I have build a search engine but there are hundreds of thousands of results for every search so I want to add pages to it.
The results of the search engine are outputted in a table.
I have started to learn php and sql recently...
How can I add those pages?
I have tried this so far but with no success:
<?php
$con = mysqli_connect(xxxx);
mysqli_select_db($con, 'Data') or die("could not find the database!");
$output = '';
$results_per_page = 1000;
//positioning
if(isset($_GET['search']))
{
$starttime = microtime(true); //TIME
$searchkey = $_GET['search'];
$query = mysqli_query($con, "SELECT * FROM table1 WHERE email LIKE '%$searchkey%'") or die("Could not search") ;
$count = mysqli_num_rows($query);
// count number of pages for the search
$number_of_pages = ceil($count/$results_per_page);
// determine which page number visitor is currently on
if (!isset($_GET['page']))
{
$page = 1;
}
else
{
$page = $_GET['page'];
}
// LIMIT
$this_page_first_result = ($page-1)*$results_per_page;
if ($count == 0)
{
echo "</br>";
$output = 'There are no search results !' ;
}
else
{
echo '<table class="myTable">';
echo "<tr><th>aaa</th><th>bbb</th></tr>";
$query = mysqli_query($con, "SELECT * FROM table1 WHERE email LIKE '%$searchkey%' LIMIT " . $this_page_first_result . ',' . $results_per_page" ") or die("Could not search") ;
while ($row = mysqli_fetch_array($query))
{
$email = preg_replace('/(' . $searchkey . ')/i', '<mark>\1</mark>', $row["aaa"]);
$password = $row['bbb'];
echo "<tr><td>";
echo $aaa;
echo "</td><td>";
echo $bbb;
echo "</td></tr>";
$output = '</table>';
}
//echo "</table>";
$endtime = microtime(true);
$duration = $endtime - $starttime;
echo "</br>";
if ($count == 1)
{
echo "<div class=resinfo>";
echo '<div>'."1 result was found for '$searchkey' in $duration seconds.".'</div>'.'</br>';
echo "</div>";
}
else
{
echo "<div class=resinfo>";
echo '<div>'."$count results were found for '$searchkey' in $duration seconds.".'</div>'.'</br>';
echo "</div>";
}
}
echo $output;
}
//LINKS to other pages
for ($page = 1; $page<=$number_of_pages;$page++){
echo '' . $page . '';
}
?>
What have I done wrong, what can I improve to make it work?
Thanks a lot for your help!
It is not a good idea to build a pagination from scratch, instead use a lib like this: https://github.com/KnpLabs/knp-components/blob/master/doc/pager/intro.md
I want to display five record per page through pagination (mysql,php,html,css) until all the records are displayed, navigation to pages must be like, Page: 1 2 3 4 5 6 7 7 8... Last.
HERE IS MY CODE TO VIEW ALL THE RECORDS FROM emp_master table.
I am new to PHP so please write an easily understandable code for pagination. I have seen few examples but they are not working.
<?php
$con=mysqli_connect("localhost","user","password","dataplus");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM emp_master");
echo "<table border='1'>";
$i = 0;
while($row = $result->fetch_assoc())
{
if ($i == 0) {
$i++;
echo "<tr>";
foreach ($row as $key => $value) {
echo "<th>" . $key . "</th>";
}
echo "</tr>";
}
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
I want to display five record per page through pagination untill all the records are displayed, navigation to pages must be like, Page: 1 2 3 4 5 6 7 7 8... Last.
This code below is not working:
$dbhost="localhost";
$dbuser="10053";
$dbpass="n6867242";
$database="0368";
$rec_limit = 10;
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('1005368');
/* Get total number of records */
$sql = "SELECT count(emp_id) FROM emp_master ";
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
$row = mysql_fetch_array($retval, MYSQL_NUM );
$rec_count = $row[0];
if( isset($_GET{'page'} ) ) {
$page = $_GET{'page'} + 1;
$offset = $rec_limit * $page ;
}else {
$page = 0;
$offset = 0;
}
$left_rec = $rec_count - ($page * $rec_limit);
$sql = "SELECT emp_id, emp_name, e_mail ".
"FROM emp_master ".
"LIMIT $offset, $rec_limit";
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo "EMP ID :{$row['emp_id']} <br> ".
"EMP NAME : {$row['emp_name']} <br> ".
"EMP MAIL : {$row['e_mail']} <br> ".
"--------------------------------<br>";
}
if( $page > 0 ) {
$last = $page - 2;
echo "Last 10 Records |";
echo "Next 10 Records";
}else if( $page == 0 ) {
echo "Next 10 Records";
}else if( $left_rec < $rec_limit ) {
$last = $page - 2;
echo "Last 10 Records";
}
mysql_close($conn);
If you want just PHP MySQL code, I usually use something like the following.
$page=max(intval($_GET['page']),1); // assuming there is a parameter 'page'
$itemsperpage = 5;
$total=100; // total results if you know it already otherwise use another query
$totalpages = max(ceil($total/$itemsperpage),1);
$query = "SELECT * FROM emp_master LIMIT ".(($page-1)*$itemsperpage).",".$itemsperpage; // this will return 5 items based on the page
You can use a library called dataTables that will auto paginate the data and you can easily customize it to suit your needs with the look and how many records to show per page. It also has a search field which enables users to search your data without any extra code.
All you have to do is include a couple of cdn's and the following code and everything works fine
$(document).ready(function(){
$('#myTable').DataTable();
});
Some examples here
you just should remove spaces in href and also make $page = $page + 1 when page is 0
if( $page > 0 ) {
$last = $page - 2;
echo "Last 10 Records |";
echo "Next 10 Records";
}else if( $page == 0 ) {
$page = $page + 1;
echo "Next 10 Records";
}else if( $left_rec < $rec_limit ) {
$last = $page - 2;
echo "Last 10 Records";
}
Link is here for demo, click here to experience the result
Here is the code working for me, just change your db name, username and password
and get pagination done. You can change $rec_limit value to your desired no. of records per page.
<?php
$host="localhost";
$username="68";
$password="67242";
$database="68";
$rec_limit = 5;
$conn = mysql_connect($localhost,$username,$password);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('10');
/* Get total number of records */
$sql = "SELECT count(emp_id) FROM emp_master ";
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
$row = mysql_fetch_array($retval, MYSQL_NUM );
$rec_count = $row[0];
if( isset($_GET{'page'} ) ) {
$page = $_GET{'page'} + 1;
$offset = $rec_limit * $page ;
}else {
$page = 0;
$offset = 0;
}
$left_rec = $rec_count - ($page * $rec_limit);
$sql = "SELECT eid,ename, email, quali, gender, contactno, birthdate, joiningdate,CURDATE(), TIMESTAMPDIFF( YEAR, birthdate, CURDATE( ) ) AS age ".
"FROM emp_master ".
"LIMIT $offset, $rec_limit";
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
echo "<table border='1'>";
$i = 0;
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
if ($i == 0) {
$i++;
echo "<tr>";
foreach ($row as $key => $value) {
echo "<th>" . $key . "</th>";
}
echo "</tr>";
}
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
if( $page > 0 ) {
$last = $page - 2;
echo "Last 5 Records | ";
echo "Next 5 Records";
}else if( $page == 0 ) {
$page = $page + 0;
echo "Next 5 Records";
}else if( $left_rec < $rec_limit ) {
$last = $page - 2;
echo "Last 5 Records";
}
mysql_close($conn);
php?>
IF your are using mysqli the code is below
$conn=mysqli_connect("localhost","root","","ui");
$start=0;
$limit=5;
$t=mysqli_query($conn,"select * from form_table");
$total=mysqli_num_rows($t);
if(isset($_GET['id']))
{
$id=$_GET['id'] ;
$start=($id-1)*$limit;
}
else
{
$id=1;
}
$page=ceil($total/$limit);
$query=mysqli_query($conn,"select * from form_table limit $start, $limit");
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script s src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> </script>
</head>
<body>
<div class="container">
<h2>Table</h2>
<table class="table table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Gender</th>
<th>Hobbies</th>
<th>Course</th>
</tr>
</thead>
<tbody>
<?php
while($ft=mysqli_fetch_array($query))
{?>
<tr>
<td><?= $ft['0']?></td>
<td><?= $ft['1']?></td>
<td><?= $ft['2']?></td>
<td><?= $ft['3']?></td>
<td><?= $ft['4']?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<ul class="pagination">
<?php if($id > 1) {?> <li>Previous</li><?php }?>
<?php
for($i=1;$i <= $page;$i++){
?>
<li><?php echo $i;?></li>
<?php
}
?>
<?php if($id!=$page)
{?>
i Give you an example of my project of pagination. Just you have to put your values in the code
$sql="SELECT * FROM tblname LIMIT $next,5";
$results = mysqli_query($conn,$sql);
}
else if (isset($_POST['prev']))
{
$prev1=$_POST['prev'];
$next=$_POST['prev'];
$prev=$prev1;
$sql="SELECT * FROM tablename LIMIT $prev,5";
$prev=$prev1;
$results = mysqli_query($conn,"SELECT * FROM tablename LIMIT $prev,10");
if($prev==0)
{
$prev = 0;
}
else
{
$prev=$next-10;
}
}
else
{
$next=0;
$prev=0;
$results = mysqli_query($conn,"SELECT * FROM tablename LIMIT $next,10");
}
Im looking to add a simple pagination, but after changing from msql to mysqli i cant seem to get it right. I cant get my head around it yet, im just starting with it.
I followed the tutorial but still im getting errors.
sorry for my lack of knowledge but what am i missing?
<?php
$db = new mysqli("host", "username", "password", "mydatabase");
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$rec_limit = 10;
$sql = "SELECT COUNT(photo)FROM employees";
$retval = mysql_query( $sql, $db );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
$row = mysql_fetch_array($retval, MYSQL_NUM );
$rec_count = $row[0];
if( isset($_GET{'page'} ) )
{
$page = $_GET{'page'} + 1;
$offset = $rec_limit * $page ;
}
else
{
$page = 0;
$offset = 0;
}
$left_rec = $rec_count - ($page * $rec_limit);
$sql = "SELECT photo, link".
"FROM employees ".
"LIMIT $offset, $rec_limit";
$retval = mysql_query( $sql, $db );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
echo "<br /><br />";
echo '','<img src="/upload/' . $row->photo . '" border=0>';
echo '', $row->link;
if( $page > 0 )
{
$last = $page - 2;
echo "Last 10 Records |";
echo "Next 10 Records";
}
else if( $page == 0 )
{
echo "Next 10 Records";
}
else if( $left_rec < $rec_limit )
{
$last = $page - 2;
echo "Last 10 Records";
}
mysql_close($db);
?>
You are mixing mysqli_* and mysql_* functions.
Please choose which style you are going to use: the procedural style (mysqli_connect, mysqli_query) or the object style (new MySQLi, ect.)
You can't mix those 2 and you can't also mix 2 different libraries (mysql and mysqli)
Read more about the different styles on PHP.net (the examples also show how to use mysqli)
$sql = "SELECT COUNT(photo)FROM employees";
^--- missing a space here
and
$sql = "SELECT photo, link".
^--- missing space here
"FROM employees ".
if this code is from a tutorial, I suggest you ditch it. Your code has absolutely not error handling, and simply assumes everything succeeded. A properly written tutorial would have proper error detection/handling. And also suggest NOT musing the mysql_*() functions, as they're deprecated/obsolete.
I am fairly new to php so probably my question will sound simple for many, but here is my issue.
I have a table in MySQL holding scoreboard for users.
$connection = mysql_connect('localhost', 'root', '');
$select_db = mysql_select_db('score');
$sql = mysql_query("SELECT * FROM users ORDER BY >score");
function score_table() {
global $sql;
if ($sql) {
$rows_num = mysql_num_rows($sql);
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i <= $rows_num; $i++) {
echo $i;
}
echo $i.$row['name']." ".$row['score']."<br />\n";
}
}
}
the result im getting is :
123456Player1 3
123456Player2 400
123456Player3 784
123456Player4 1500
123456Player5 1642
So there is 5 players. Although firstly $i has 6 results and it is going through the entire loop for each player.
What i am trying to achieve is this:
1Player1 3
2Player2 400
3Player3 784
4Player4 1500
5Player5 1642
where first number is simply position. So whoever has less points is on the first place.
$connection = mysql_connect('localhost' ,'root', '');
$select_db = mysql_select_db('score');
$sql = mysql_query("SELECT * FROM users ORDER BY >score");
function score_table()
{
global $sql;
$i=1;
if($sql)
{
while($row = mysql_fetch_array($sql))
{
echo $i++ . $row['name'] . " " . $row['score'] . "<br />".PHP_EOL;
}
}
}
i'm trying to run this php code which should display a quote from mysql, but can't figure out where is it going wrong. the result variable is null or empty. can someone help me out. thanks!
<?php
include 'config.php';
// 'text' is the name of your table that contains
// the information you want to pull from
$rowcount = mysql_query("select count(*) as rows from quotes");
// Gets the total number of items pulled from database.
while ($row = mysql_fetch_assoc($rowcount))
{
$max = $row["rows"];
//print_r ($max);
}
// Selects an item's index at random
$rand = rand(1,$max)-1;
print_r ($rand);
$result = mysql_query("select * from quotes limit $rand, 1") or die ('Error: '.mysql_error());
if (!$result or mysql_num_rows($result))
{
echo "Empty";
}
else{
while ($row = mysql_fetch_array($result)) {
$randomOutput = $row['cQuotes'];
echo '<p>' . $randomOutput . '</p>';
}
}
$result = mysql_query("SELECT * FROM quotes ORDER BY rand() LIMIT 1") or die ('Error: '.mysql_error());
if (!$result || mysql_num_rows($result) == 0)
echo "Empty";
else {
while ($row = mysql_fetch_array($result)) {
$randomOutput = $row['cQuotes'];
echo '<p>' . $randomOutput . '</p>';
}
}
// your script probably can't go on without this file?
require 'config.php';
// I prefer to always pass the connection resource to mysql_query/mysql_real_escape_string
// assume $mysql = mysql_connect....
$result = mysql_query("SELECT Count(*) AS rows FROM quotes", $mysql)
or die(mysql_error());
// there's only one row with only one column, so mysql_result() is fine
$rowcount = mysql_result($result, 0, 0);
$rand = rand(0,$rowcount-1);
$result = mysql_query("SELECT cQuotes FROM quotes LIMIT $rand, 1", $mysql)
or die ('Error: '.mysql_error());
// there's either one or zero records. Again, no need for a while loop
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if ( !$row ) {
echo "Empty";
}
else{
// do you have to treat $row['cQuotes'] with htmlspecialchars()?
echo '<p>', $row['cQuotes'], '</p>';
}
if ($result && mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$randomOutput = $row['cQuotes'];
echo '<p>' . $randomOutput . '</p>';
}
} else {
echo "Empty";
}