<?php
mysql_select_db($database_XXX, $XXX);
$result= mysql_query("SELECT COUNT(*) FROM news");
$total = mysql_result($result, 0, 0);
// create a random number
mt_srand((double)microtime()*1000000);
$number = mt_rand()%$total;
// get a random entry
$result= mysql_query("SELECT * FROM news LIMIT $number, 5");
$row = mysql_fetch_array($result);
?>
This is the PHP code I'm using and it pulls up random data from the table I want but I can't seem to figure out how to have it not show the current post it's on. Will I need to throw in an if statement in? If I do where would it go and how to impletment it. The only thing I can thing of is using if statements to check if the post_id on page matches the post_id posted. But I'm new to this and the only thing I can think of is.
if(!$row['post_id'] == $_GET['id']) {
}
I don't know what to make it do after. Also if anyone knows how or can help point me in the right direction that would be great. Thanks.
Here is the update of the total thing here. It still shows post it's already on. hope this helps. This is the php code for the page.
<?php
mysql_select_db($database_xxx, $xxx);
$result= mysql_query("SELECT COUNT(*) FROM news");
$total = mysql_result($result, 0, 0);
// create a random number
mt_srand((double)microtime()*1000000);
$number = mt_rand()%$total;
// get a random entry
$result= mysql_query(sprintf("SELECT * FROM news WHERE post_id <> %d LIMIT %d, 3", $post->post_id, $number));
$row = mysql_fetch_array($result);
?>
<?php
if (! isset($_GET['id']) || (int) $_GET['id'] === 0 ) {
echo "Incorrect input, aborting";
exit;
}
mysql_select_db($database_xxx, $xxx);
$sql = "SELECT * FROM news WHERE post_id = " . $_GET['id'];
// a line of debug to make sure things are as expected
$query = MYSQL_QUERY($sql);
// query your table for a match with post_id
if (mysql_num_rows($query) == "1")
// if a record is found, show the info
{
$fetch = mysql_fetch_array($query); // set $fetch to have the values from the table
} else {
echo "No match in database found."; // if no match is found, display this error
}
?>
Assuming that code is on the page where you view the main product:
$result= mysql_query(sprintf("SELECT * FROM news WHERE id <> %d LIMIT %d, 5", $post->id, $number));
Also, you should not be using mysql_* functions anymore as they are deprecated; checkout PDO
Related
I'm developing one API in php to display data on android app from my database using JSON.
In my app I want to display 20 records first, after display again 20 records once user scroll to top.
I'm requesting the last id of the record from app to show next 20 records from last id.
Here is my code
<?php
$last_movie = 0;
$genre = $_REQUEST['genre'];
$last_movie = $_REQUEST['lastid'];
require_once("connect.php");
$myArray = array();
if($last_movie == 0)
{
$result = $conn->query("SELECT * FROM my_movies WHERE genre = '$genre' ORDER BY year DESC LIMIT 20");
}
else
{
$result = $conn->query("SELECT * FROM my_movies WHERE genre = '$genre' ORDER BY year LIMIT ".$last_movie.",20");
}
if ($result) {
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
}
$result->close();
$conn->close();
?>
I'm getting values in some genres, but sometimes it show empty JSON.
I tried with this url
http://freemodedapk.com/bobmovies/by_genre.php?genre=Action
its working , whenever I try from last id
http://freemodedapk.com/bobmovies/by_genre.php?genre=Action&lastid=4714
It returns empty JSON. I have values in database.
But some genres working fine
http://freemodedapk.com/bobmovies/by_genre.php?genre=Drama
http://freemodedapk.com/bobmovies/by_genre.php?genre=Drama&lastid=865
I have total 4858 records in the database with all genres.
Anybody can help me to fix empty JSON problems in some of genres ?
Your main issue is in the wrong LIMIT usage: when you utilize 2 parameters for LIMIT keyword, the first one is for OFFSET value (not for IDs), the second one is to limit your result.
In short words: you should use LIMIT 0,20 to get the first 20 results, LIMIT 20,20 to show next 20 results and so on.
Also, your code is insecure - you have SQL injection. Try to not post direct urls on your sites with the source code which includes injection because some bad guys may drop your database or do some other harmful things.
Sample code is listed below (minor changes may be required):
<?php
require_once('connect.php');
$response = [];
$items_per_page = 20;
$page = (int) (($_REQUEST['page'] - 1) * $items_per_page);
$genre = $conn->escape_string($genre); # replace escape_string with proper method if necessary
$result = $conn->query("SELECT * FROM my_movies WHERE genre = '$genre' ORDER BY year DESC LIMIT $page,$items_per_page");
if ($result)
{
$response = $conn->fetch_all($result, MYSQLI_ASSOC); # replace fetch_all with proper method if necessary
}
echo json_encode($response);
$result->close();
$conn->close();
if you want to get last ID to ASC then use to
SELECT * FROM my_movies WHERE genre = '$genre' id<".$last_movie." ORDER BY year LIMIT 0,20
or if you want to get for pagination then your OFFSET value wrong,
you should be use LIMIT 0,20 to get the first 20 results, LIMIT 20,20 to next 20 , LIMIT 40,20
please check your SQL injection
look like Code
require_once('connect.php');
$result = [];
$limit = 20;
$pageNumber = (int) (($_REQUEST['pageNumber'] - 1) * $limit);
$genre = $conn->escape_string($genre);
$getDta = $conn->query("SELECT id,title,stream,trailer,directors,actors,quality,year,genre,length,translation,rating,description,poster FROM my_movies WHERE genre = '".$genre."' ORDER BY year DESC LIMIT $pageNumber,$limit");
if ($result)
$result =$conn->fetch_all($result, MYSQLI_ASSOC);
echo json_encode($result);
$result->close();
$conn->close();
I am trying to show some text depending upon what a status is set to in a db table.
See my code below:
$result=mysql_query("SELECT * FROM hr_recruitment_stages where vacancy_ref='$vacancyref' order by added_on DESC limit 0,1")or die('ERROR 315' );
$row = mysql_fetch_array($result);
$stage_name = $row ['stage_name'];
if($stage_name['stage_name'] == 'Shortlisting') { echo"Shortlisting"; } else { echo"Not Shortlisting"; } ?>
However this doesnt seem to be working properly as it is showing as Not Shortlisting even when stage_name equals Shortlisting.
Any ideas why?
Its variable type mistake. Check your assigned variable, you assigned the Array Element not the entire array. so try like below.
<?php
$result = mysql_query("SELECT * FROM hr_recruitment_stages where vacancy_ref='$vacancyref' order by added_on DESC limit 0,1") or die('ERROR 315' );
$row = mysql_fetch_array($result);
$stage_name = $row['stage_name'];
if($stage_name == 'Shortlisting') {
echo"Shortlisting";
} else {
echo"Not Shortlisting";
}
?>
Refer this Article for PHP Array understanding.
http://php.net/manual/en/language.types.array.php
I am trying to show a count of all applications stored in a database with the status of 1.
Here is my UPDATED code:
$result=mysql_query("SELECT * FROM member ")or die('You need to add an administrator ' );
$counter = mysql_query("SELECT COUNT(*) as personID FROM member where state='1' ");
$row = mysql_fetch_array($result);
$personID = $row['personID'];
$num = mysql_fetch_array($counter);
$countadmin = $num["personID"];
However this isn't showing anything when I echo `$countadmin'
Can anyone help
You may try this
$query = mysql_query("select count(*) from member where state='1'");
if ($query) {
$count = mysql_result($query, 0, 0);
echo $count;
}
Check mysql_result and also notice the Warning at top. Also make sure that, the field is state not status, it's confusing, you mentioned status in your question but used state in the query.
Also, following line is not required to get the count of your second query
$result=mysql_query("SELECT * FROM member ")or die('You need to add an administrator ' );
Also, make sure that, you have connected to a database and selected it.
You try to readout "ID", but you select COUNT as "personID"
You have two options here;
$result = mysql_query("SELECT * FROM `member` WHERE `Status`='1'");
$num_rows = mysql_num_rows($result);
or
$result = mysql_query("SELECT COUNT(`Status`) FROM `member` WHERE `Status`='1'");
while($row = mysql_fetch_array($result)){
$Count = $row['count(Status)'];
}
I am trying to create multiple pages from my query. If I have 100 results, and I want 10 results per page, I would like there to be ten pages created, with each page showing a different query. This is how my query is set up:
$sql ="SELECT * FROM Post WHERE (active ='1') ORDER BY PostID DESC ";
$result = mysql_query($sql,$db);
$numrows = mysql_num_rows($result);
while(($post = mysql_fetch_assoc($result))) {
$posts[] = $post;
}
<?php
if (!$numrows){ echo $errormessage;}
else{
foreach($posts as $post): ?>
echo stripslashes($post['text']);
<?php endforeach; }?>
This pulls each "post" from the database and puts displays them all out.
I would like to do something like this:
$results = mysql_num_rows($result);
$numpages = 10/$results; //gives the number of pages
while($numpages<$results)
{
//run code from above\\
}
What is the best way to do this with the method that I use? I appreciate your opinions because I'm at one of those stages where I'm lost in my own logic. Thank You!
Most pagination examples fail to meet real life requirements. A custom query string, for example.
So, here is a complete yet concise example:
<?
per_page=10;
// Let's put FROM and WHERE parts of the query into variable
$from_where="FROM Post WHERE active ='1'";
// and get total number of records
$sql = "SELECT count(*) ".$from_where;
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
$row = mysql_fetch_row($res);
$total_rows = $row[0];
//let's get page number from the query string
if (isset($_GET['page'])) $CUR_PAGE = intval($_GET['page']); else $CUR_PAGE=1;
//and calculate $start variable for the LIMIT clause
$start = abs(($CUR_PAGE-1)*$per_page);
//Let's query database for the actual data
$sql = "SELECT * $from_where ORDER BY PostID DESC LIMIT $start,$per_page";
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
// and fill an array
while ($row=mysql_fetch_array($res)) $DATA[++$start]=$row;
//now let's form new query string without page variable
$uri = strtok($_SERVER['REQUEST_URI'],"?")."?";
$tmpget = $_GET;
unset($tmpget['page']);
if ($tmpget) {
$uri .= http_build_query($tmpget)."&";
}
//now we're getting total pages number and fill an array of links
$num_pages=ceil($total_rows/$per_page);
for($i=1;$i<=$num_pages;$i++) $PAGES[$i]=$uri.'page='.$i;
//and, finally, starting output in the template.
?>
Found rows: <b><?=$total_rows?></b><br><br>
<? foreach ($DATA as $i => $row): ?>
<?=$i?>. <?=$row['title']?><br>
<? endforeach ?>
<br>
Pages:
<? foreach ($PAGES as $i => $link): ?>
<? if ($i == $CUR_PAGE): ?>
<b><?=$i?></b>
<? else: ?>
<?=$i?>
<? endif ?>
<? endforeach ?>
It would be hideous to extract all data from the database and manage it from PHP. It would kill the RAM, and the network.
Use the LIMIT clause for paging.
First, you need to see the total number of records. Use
$query = 'SELECT count(1) as cnt FROM Post WHERE active =1';
then,
$result = mysql_query($query, $db);
$row = mysql_fetch_assoc($result);
$count = $row['cnt'];
$pages = ceil($count/10.0); //used to display page links. It's the total number of pages.
$page = 3; //get it from somewhere else, it's the page number.
Then extract the data
$query = 'SELECT count(1) as cnt FROM Post WHERE active =1 LIMIT '.$page*10.', 10';
$result = mysql_query($query, $db);
while($row = mysql_fetch_assoc($result))
{
//display your row
}
Then output the data.
I'm using that similar code to do that:
$data = mysql_query("SELECT * FROM `table`");
$total_data = mysql_num_rows($data);
$step = 30;
$from = $_GET['p'];
$data = mysql_query("SELECT * FROM `table` LIMIT '.$from.','.$step.'"
That code get total rows
and that for creating links:
$p=1;
for ($j = 0 ; $j <= $total_data+$step; $j+=$step)
{
echo ' '.$p.' ';
$p++;
} ?>
You can also read about : pagination
I have the following inside a foreach loop (displaying my various videos), I'm trying to display some alternate text for the top three voted videos. What on earth am I doing wrong (a lot clearly)...
$sql = "SELECT video_id FROM videos WHERE displayable='y' ORDER BY votes desc LIMIT 0,3";
$result = mysql_query($sql);
$row = #mysql_fetch_array($result);
if(in_array($video->getProperty('video_id')) == $row['video_id']) {
do this...
} else {
do this..
}
Firstly replace your code with some error preventing techniques like so!
$sql = "SELECT video_id FROM videos WHERE displayable='y' ORDER BY votes desc LIMIT 0,3";
if(false != ($result = mysql_query($sql))
{
$row = mysql_fetch_assoc($result); //Dont need the # restraint as the result is not false above.
//Also to get associate keys you need to use mysql_fetch_assoc
if($video->getProperty('video_id') == $row['video_id'])) //Remove the in array as your directly comparing the to entities with ==
{
//Match
}else
{
//Video does not match
}
}
Your main problem was the mysql_fetch_array(), Please research the differences with mysql_fetch_array() and mysql_fetch_assoc();
--
Edit: The way i would go
//Change the query and the loop way.
$sql = "SELECT video_id FROM videos WHERE displayable='y' AND video_id != '".(int)$video->getProperty('video_id')."' ORDER BY votes desc LIMIT 0,3";
if(false != ($result = mysql_query($sql))
//Use the # restraint if you have E_NOTICE on within E_Reporting
{
while($row = mysql_fetch_assoc($result))
{
//Print the $row here how you wish for it to be displayed
}
}else
{
//We have an error?
echo '<strong>Unable to list top rated videos, please check back later.</strong>'
}
}
mysql_fetch_array only returns a single row, you need to loop through your results to build an array containing the top three ids.
$sql = "SELECT video_id FROM videos WHERE displayable='y' ORDER BY votes desc LIMIT 0,3";
$result = mysql_query($sql);
while($row = #mysql_fetch_array($result)) {
$topthree[] = $row["video_id"];
}
Then you can use in_array but with the correct syntax:
if(in_array($video->getProperty('video_id'), $topthree)) {
do this...
} else {
do this..
}