random images from db, with links trough id - php

Having some issues, basically I have a random image gallery.
This is the code for the random thumbnails:
<?php
include('../../connect.php');
$result = mysql_query("SELECT *
FROM picture AS r1
JOIN
(
SELECT ROUND(RAND() * (SELECT MAX(id)
FROM picture) ) AS id
) AS r2
WHERE r1.id >= r2.id
AND public_approved=1
ORDER BY r1.id ASC
LIMIT 4;")
or die(mysql_error());
while($row = mysql_fetch_array( $result ))
{
echo "<div style='float:left; margin:2px;' >";
echo '<a href="pictures.php?id=' . $row['id'] .'"><img src="../../files/small/thumb0_'. $row['file_name'] . '.' . $row['file_extension'] . '" border="0"></br>';
echo "</div>";
}
?>
When one of the thumbnails is clicked the page reloads and uses the following command to load the main content:
<?php
include('../../connect.php');
$passed_id = $_GET['id'];
$result1 = mysql_query("SELECT * FROM picture where id='$passed_id' ")
or die(mysql_error());
while($row = mysql_fetch_array( $result1 ))
{?>
This continues on through a table displaying the larger image and title and so on.
I'm experiencing two problems:
1 - Even though I specify 4 in the limit, sometimes only 1 2 or 3 thumbs are displayed.
2 - Sometimes when I click on a thumbnail the wrong id is used, i.e. thumbnail id 2 but firing id 8.

The reason why you are getting 1,2 or 3 thumbs is because r1.id >= r2.id where r1.public_aprove 1 only has a result set 1 or 2 or 3. The reason is your RAND().
For problem 2 which row[id] are you using r1.id or r2.id - I suspect its r2.id.

Suppose X is the number of images you want to display, you should really take [MAX(id) - X] as the RAND() multiplier. This way the result set will have enough results.
Second problem seems simple, someone will probably post a good answer, but keep in mind it's usually a column/parameter confusion in your php/html code.
Good luck!

Related

How to limit all columns in a database using mysql

I am working on an image gallery system, and I want to know how to limit/show all image uploaded into the gallery/database table. I normally don't know how this is done so I usually use a number greater than the number of columns in the database to show all my columns. I will love to know how this is done in other to change my method of doing this.
HERE IS MY CODE BELOW;
<?php
$image_id = $the_image = $image_des = $time_uploaded = "";
$gallery = mysqli_query($connect, "SELECT * FROM gallery ORDER BY time_uploaded DESC LIMIT 9000");
while ($pick = mysqli_fetch_array($gallery, MYSQLI_BOTH)) {
$image_id = $pick['id'];
$the_image = $pick['image'];
$image_des = $pick['description'];
$time_uploaded = $pick['time_uploaded'];
echo '<div class="nicdark_margin100">';
echo '<img alt="" class="nicdark_radius nicdark_opacity" src="../img/gallery/'.$the_image.'" width="100" height="100" /> ';
echo ' </div>';
}
?>
MySQL doesn't require a LIMIT field in the query. So to get all results
SELECT * FROM gallery ORDER BY time_uploaded DESC
However, if you're trying to do pagination, you can combine LIMIT and OFFSET
## First Page of 25 images
SELECT * FROM gallery ORDER BY time_uploaded DESC LIMIT 25 OFFSET 0
## Second Page of 25 images (offset by 25)
SELECT * FROM gallery ORDER BY time_uploaded DESC LIMIT 25 OFFSET 25
For more info, see
https://www.w3schools.com/php/php_mysql_select_limit.asp

Next and previous buttons

I know there are libraries etc that I could use to get this sorted but Im almost there with my code.
A little about the code and what it's trying to do. I have a mysql table where there are various news articles and grouped in categories of news.
I have managed to get a forward button working. So it looks for the next news article that is in the same category. This works and the code is below.
//Gets the next story from the same story type in line.
$query= "SELECT * FROM news WHERE storytype2 = '$storytype2' AND id > '$currentid'";
$result = mysql_query($query) or die ("Error in query: $query " . mysql_error());
$row = mysql_fetch_array($result);
$num_results = mysql_num_rows($result);
if ($num_results > 0){
echo "<td width=\"20%\"align=\"right\"><img title=\"Next News\" src=\"webImg/forwardarrow.png\"/></td></tr>";
}else{
echo "<td width=\"20%\"align=\"right\"></td></tr>";
}
//End of the next button
However, when I try do the same for the previous button. All I ever seem to get back is the first id of that category regardless of where my iteration is. For example, if I am on news article 10 and try to go to previous one which say has an id of 7 it will automatically show the first news article within that category, say id 4.
Below is the code.
//Gets the next story from the same story type in line.
$query= "SELECT * FROM news WHERE storytype2 = '$storytype2' AND id < '$currentid'";
$result = mysql_query($query) or die ("Error in query: $query " . mysql_error());
$row = mysql_fetch_array($result);
$num_results = mysql_num_rows($result);
if ($num_results > 0){
echo "<td width=\"20%\"align=\"left\"><img title=\"Previous News\" src=\"webImg/backarrow.png\"/></td>";
}else{
echo "<td width=\"20%\"align=\"left\"></td>";
}
//End of the next button
What have I done wrong?
Thanks
Neither of your queries is correct. Your "Next" code selects any row whose ID is higher than the current, not necessarily the next one; if you get the next one, it's just by accident.
You should use ORDER BY and LIMIT to control which row is selected:
Next:
SELECT *
FROM news
WHERE storytype2 = '$storytype2' AND id > '$currentid'
ORDER BY id
LIMIT 1
Previous:
SELECT *
FROM news
WHERE storytype2 = '$storytype2' AND id < '$currentid'
ORDER BY id DESC
LIMIT 1
Without any further information, I don't think you can assume that the first row of your queries will be the ID you're looking for. Ordering by ID first will probably solve your problem; you can also limit your query to one row, since it's the only one you're looking at. Something like the following would probably solve your problem (where x is $storytype2 and y is $currentid:
SELECT * FROM news
WHERE storytype2 = x
AND id < y
ORDER BY id DESC /* <-- THIS */
LIMIT 1
Use ORDER BY id ASC for the other case.
Note that the MySQL family of PHP is deprecated and support thereof will disappear, if it hasn't yet. Please look into PDO or MySQLi.
Note also that you are inserting a variable into SQL code directly, which is never a good idea. I hope you have some good input checks on your variables.
Let's look at the PDO way to get the previous article ID:
$dbh = new PDO(..);
// Use ? where dynamic input will come
$sql = $dbh->prepare('SELECT * FROM news
WHERE storytype2 = ?
AND id < ?
ORDER BY id DESC
LIMIT 1');
// Fill the ? safely with PDO's execute function
$sql->execute(array($storytype2, $currentid));
$result = $sql->fetch(PDO::FETCH_ASSOC);
if($result && isset($result['id'])) {
// Process previous ID
}

php database table select limited

im new on php programming and i've searched the function that i need but didn't found it.
here what exactly i want to do :
i want to select 2 columns from a table
set the order by descending by 1 column that is numeric
and then show in php the first 100 rows that were selected
Here is my code right now php shows all the columns i want it to show the first 100
$result = mysqli_query($con,"SELECT pvpkills,char_name FROM characters ORDER BY pvpkills DESC");
while($row = mysqli_fetch_array($result))
{
echo $row['pvpkills'] . "&nbsp " . $row['char_name'];
echo "<br>";
}
SELECT pvpkills,char_name FROM characters ORDER BY pvpkills DESC LIMIT 0,100

numbering an output in order

i have made a image slider(or what ever you want to call it) and it displays the 6 latest images. Under the current bigger image you have all 6 of the most recent images , and the process works all fine but when you click the smaller image, it doesn't bring up the big image straight away. Because the very latest image is first its 'active' and has its own <a href="#1> and so the href="#1" is entered as i can manipulate the a tag as it is there. But as i used a foreach to bring up the next 5 images from 2nd to 6th in descending order from date submitted, i cant give each individual result there own href"#number" so they can link up with the bigger images, is there a way to assign each result a number by taking what position it sits within the query then adding 1or2 to the answer which would then give the corresponding number in the href so when clicked, the larger image which is linked to the href number too, it will make the larger image appear straight away.
the code from the tutorial that i have amended looks like this ..
<?php
$latest_headlines = get_latest_headlines();
foreach ($latest_headlines as $latest_headline) {
?>
<img src="img/<?php echo $latest_headline['img_title'].'.'.$latest_headline['img_ext']; ?>" class="nav-thumb" alt="<?php echo $latest_headline['title']; ?>" />
<?php
}
?>
<div id="movers-row">
<?php
$recent_headlines = get_recent_headlines();
foreach ($recent_headlines as $recent_headline) {
?>
<div><img src="img/<?php echo $recent_headline['img_title'].'.'.$recent_headline['img_ext']; ?>" class="nav-thumb" alt="<?php echo $recent_headline['title']; ?>" /></div>
<?php
}
?>
</div>
And here are my two functions to get the results, and before people start picking at all the problems ive done, just want to say this is the way ive learnt it im new, it maybe all wrong but its what stuck in my head to do things this way and its worked(ish) so far....
function get_recent_headlines() {
$sql = "SELECT *
FROM `story`
ORDER BY `submit_date` DESC
LIMIT 1, 5 ";
$result = mysql_query($sql) or die(mysql_error());
$recent_headlines = array();
while (($row = mysql_fetch_array($result)) !== false) {
$recent_headlines[] = array(
'title' => $row['title'],
'img_title' => $row['img_title'],
'img_ext' => $row['image_ext']
);
}
return $recent_headlines;
}
function get_latest_headlines() {
$sql = "SELECT *
FROM `story`
ORDER BY `submit_date` DESC
LIMIT 1 ";
$result = mysql_query($sql) or die(mysql_error());
$lastest_headlines = array();
while (($row = mysql_fetch_array($result)) !== false) {
$latest_headlines[] = array(
'title' => $row['title'],
'img_title' => $row['img_title'],
'img_ext' => $row['image_ext']
);
}
return $latest_headlines;
}
change your query of your function get_recent_headlines()
it uses a variable, and increment it in the SELECT statement:
`$sql = "SELECT *,(#row:=#row+1) AS rowno
FROM `story` inner join (SELECT #row:=0) AS row_count
ORDER BY `submit_date` DESC
LIMIT 1, 5 ";`
You can use a user variable to get a sequence number within MySQL.:-
SELECT Sub1.*,#aCount:=#aCount+1 AS aSequence
FROM (SELECT *
FROM `story`
ORDER BY `submit_date` DESC) Sub1
CROSS JOIN (SELECT #aCount := 0) Sub2
LIMIT 1, 5

mysql + php: Selecting multiple random results

I've been looking for this for a while but with no success.
I am trying to implement a recomendation bar, for example like in youtube, when you are seeing a video it shows the list or recommended videos on the right.
At this moment I am using this method:
$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `$tablename` ");
$offset_row = mysql_fetch_object($offset_result );
$offset = $offset_row->offset;
$result_rand = mysql_query( " SELECT * FROM `$tablename` LIMIT $offset, 9 " );
This works fine, but sometimes doesn't show any result, and the problem is also that its not completely random, because it shows for example the first ID as 200, so the next result will be id 201 and then 202 and so.
I would like to know if there is a way to show this 9 randon results, for example 1º result id 500, 2º result id 10, 3º result id 788, etc etc?
Thank you
Not entirely sure this answers what you are looking for, but try:
$result_rand = mysql_query("SELECT * FROM " . $tablename . " ORDER BY RAND() LIMIT 9");
You can use php rand() function to create 5 numbers and save them in an array:
http://php.net/manual/en/function.rand.php
<?php
$rand_array = array();
for($i=1;$i<5;$i++) {
$rand_array[$i] = rand(0,500);
}
?>
and after that create a query with every int with a foreach loop and work with your data.
<?php
foreach ($rand_array as $integer) {
$q = "SELECT * from $tablename WHERE id='$integer';";
}
?>
Does this helps?
First you should use mysqli_ functions instead of mysql_ because the latter is deprecated. Second use order by rand() to get random rows:
$rand_result = mysqli_query( "SELECT * FROM $tablename ORDER BY RAND() LIMIT 9;" );
UNTESTED:
SELECT id, #rownum:=#rownum+1 AS rownum, name
FROM users u,
(SELECT #rownum:=0) r
THis will give a unique number to each row in sequence. Now if you create a temp table with 9 random numbers between 1 and count(*) of your table and JOIN those two together...
Not sure about performance but seems like it might be faster than Rand and order by since I only need 9 random numbers

Categories