Set a limit in the results (no mysql) - php

Can I put a limit to show in a list of images extracted from a folder? I should point out that I do not mean with mysql but simple php.
Practically from a folder I extract all the images, here, I would like to set a limit. is it possible? or must necessarily the database?

You mention "extracted from a folder" and also "or must necessarily the database" so I'm not sure what your source is.
If you are getting the list of images them from a folder, presumably using something like glob() or readdir() or scandir() then you end up with an array. If you only want to display a certain number of those images then simply stop after that number of iterations...
$imgs = glob('*.jpg');
$count = 0;
foreach ($imgs as $img) {
if ($count++ > 20) break; // place a limit of 20
echo "<img src='$img' alt='$img' />\n";
}
If you are using a database to obtain your list of image filenames then you would do something similar, controlling it within your loop:
$sql = "SELECT filename, alt_text FROM ...";
$conx = mysqli_connect($host, $user, $pass, $dbname, ...);
$results = mysqli_query($conx, $sql);
$count = 0;
while ($row = mysqli_fetch_assoc($conx, $results)) {
if ($count++ > 20) break; // place a limit of 20
echo "<img src='$row[filename]' alt='$row[alt_text]' />\n";
}
mysqli_free_results($results);
If I have not yet answered your question then please clarify. If I have, please vote for the answer.
Thanks!

Try
array_slice(scandir($dir), 0, $limit);

Related

Images upload in the wrong order

I am aware it's an old script (an old way of doing things). The script works, however, the images do not upload in the right order. I am not exactly sure but it looks to me they upload from last to first instead of from first to last. What makes it do that?
if (count($_FILES['pic']['tmp_name']))
{
$ipval = ipval();
$uploaderror = 0;
$uploadcount = 0;
$errorMessages = array();
foreach ($_FILES['pic']['tmp_name'] as $k=>$tmpfile)
}
if ($tmpfile)
{
$thisfile = array("name"=>$_FILES['pic']['name'][$k],
"tmp_name"=>$_FILES['pic']['tmp_name'][$k],
"size"=>$_FILES['pic']['size'][$k],
"type"=>$_FILES['pic']['type'][$k],
"error"=>$_FILES['pic']['error'][$k]);
if ($_FILES['pic']['size'][$k] > $pic_maxsize*1000)
{
$errorMessages[] = $thisfile['name'] . " - " . $lang['ERROR_UPLOAD_PIC_TOO_BIG'];
$uploaderror++;
}
elseif (!isValidImage($thisfile))
{
$errorMessages[] = $thisfile['name'] . " - " . $lang['ERROR_UPLOAD_PIC_BAD_FILETYPE'];
$uploaderror++;
}
else
{
$newfile = SaveUploadFile($thisfile, "{$path_escape}{$datadir['adpics']}", TRUE, $images_max_width, $images_max_height);
if($newfile)
{
$sql = "INSERT INTO $t_adpics
SET adid = $adid,
picfile = '$newfile'";
mysql_query($sql);
if (mysql_error())
{
...
If by "order" you mean the order that you selected the images in a multiple file input, you cannot rely on that order being consistent on the back end. It varies by browser and server: does multiple upload follow the same order of uploading in which we select the images?
If you are always seeing the order reversed, perhaps you need to change some code in the script that serves them up (ASC instead of DESC).
One way you could keep the order consistent is by sending another variable to the server on upload that contains an array of the file names in order, then base your INSERT order off of that array, not the order of the $_FILES array.

How do I scan an array and stop the scan when the number becomes false, and echo what number made the loop false in PHP

Basically I am creating a simple music player in PHP and I am setting the id of each song that is played in an array. I have a script which pulls a random number and plays the song with the corresponding id. I want to make it so that if the song has already played that it wont play again.
Currently I have it generate a random number, and if that number has already been played then it adds 1 to the random number.
The problem is if the number that is the result of adding 1 to the random number, it will then play that song again. I was attempting to store the songs played in an array and just increment the number until it doesn't exist in the array but I am struggling to find a solution to the problem.
My code is as follows:
<?php
session_start();
$con=mysqli_connect("blah blah blah");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (!isset($_SESSION['played'])) {
$_SESSION['played'] = array();
}
$result = mysqli_query($con,"SELECT * FROM Data") ;
$num_rows = mysqli_num_rows($result);
$numsongs= .20 * $num_rows;
$numsongs=floor($numsongs);
$music = rand(1,$numsongs);
if (in_array($music, $_SESSION['played'])) {$music = $music+1;};
/* goes on to play music below */
$_SESSION['played'][] = $music;
?>
I didn't put my whole script in, the script works minus the repeating of songs. I only included a snippet of how I wrote the repeating script to give an idea of how I attempted it.
Thanks in advance!
I think you are looking for this...
$music = rand(1,$numsongs);
while(in_array($music, $_SESSION['played'])){
$music = $music+1;
echo 'in array '.$music;
}
echo 'Not in array '.$music;
AHAAA!! I figured it out! I ended up using switch() but in a different form.
if (empty($_SESSION['played1'])) {
for ($i = 1; $i <= $numsongs; ++$i) {
$_SESSION['played1'][] = $i;}}
shuffle($_SESSION['played1']);
$music1= $_SESSION['played1'][0];
$result = mysqli_query($con,"SELECT * FROM Data WHERE position = '$music1'") ;
while($row = mysqli_fetch_array($result)){
$del_val=$row[position];
if(($key = array_search($del_val, $_SESSION['played1'])) !== false) {
unset($_SESSION['played1'][$key]);}
Basically created an array between 1 and 10. Then used switch() to randomize the array. Then picked the first number in the array, used it in mysqli query, and then removed it from the array. Problem Solved!!

PHP link only passing part of a mysql result

OK i have a php link which is made up of several variables
<a href=\year.php? manufacturer='.$manufacturer.'&fuel_type='.$fuel_type.'&model_type='.$model_type.'>'.$model_type.'</a>
The whole code is really long as it has a lot of pagination, so i will just include the basic query and the loop part.
$query1 = "SELECT Distinct model_type from $tableName where manufacturer='$manufacturer' AND fuel='$fuel_type' LIMIT $start, $limit";
$result = mysql_query($query1);
And then the bottom part where i get and show the results.
$count = 0;
$max = 2;
while($row = mysql_fetch_array($result))
{
$model_type = $row['model_type'];
$count++;
echo '<td class="manu"><div align="center">'.'<a href=\year.php? manufacturer='.$manufacturer.'&fuel_type='.$fuel_type.'&model_type='.$model_type.'>'.$model_type.'</a>'.'</div></td>';
if($count >= $max){
//reset counter
$count = 0;
//end and restart
echo '</tr><tr>';
}
}
now this works fine except when i take the mode type variable from the database it shows as 1 series, however when it is passed in this link it only gets the 1 and doesn't pick up the series.
Thanks
try to pass it like:
'.urlencode($model_type).'
Try To access it on next page with urldecode($_REQUEST['$model_type'])
I am not shure but you probably have a missing encoding Problem.
try this:
'.$model_type.'
Its url_encoding the values so your url doesnt get broken by ',",spaces and so on.
additional Hint:
Enclose your URL with " or ' so you do not get problems at the end.

Delete files that are not in my database

I'm trying to delete photos from a folder, which is called, "photos", that are NOT currently in my database. (These are all photos that have stacked up as I've been building the website and testing it and such, so now it's time to take the site live and I don't want all this waste in it)
I have three tables with photo information in them, and a number of columns throughout. Below is a mockup query of about what I THINK it should look like.
SELECT left_image, right_image, photo1, photo2, photo3, photo4, home_photo
FROM about_photos, facilities, home
left_image and right_image go with about_photos.
photo1, photo2, photo3 and photo4 go with facilities.
home_photo goes with home.
Also, I need to use a wildcard for the end of the photo, because the files have thumbnails, so for instance the original photo would be called, abcimage.jpg but there would be abcimage.jpg, abcimage_medium.jpg, abcimage_thumb.jpg also in the database I only store, photos/abcimage and add the rest of the filename depending on where it goes.
$directory = "../path/to/photos_directory/";
//get all image files with a .jpg extension.
$images = glob($directory . "*.jpg");
foreach($images as $image)
{
$name = explode('_',$image);
$name = 'photos/' . $name[0];
$sql = mysql_query("SELECT id FROM table WHERE photo1='$name' OR photo2='$name'");
if(mysql_num_rows($sql) == 0)
unlink($directory . $image);
}
You have two options:
One:
With an SQL query, get a complete list of all the photos referenced in your database
iterate through the files in your directory
if the file is an image AND it is not in your list, delete the file.
Two:
iterate through the files in your directory
if the file is an image
query the database for that filename
if the response is empty, delete the file
The exact SQL query depends on your table structure, which you have not provided.
The best option depends mostly on scale. If there are lots of images in the database, then the first option involves having a very large list in memory. However the second version involves many more database queries. So it's a tradeoff.
There are more sophisticated options involving caching and pre-emptive queries, but I imagine you don't want to go that deep yet.
Something like the following. I've also got original files in the folder and I limit to 500 deletions at a time. Tweak as you need. Hope it saves somebody time...
<?php
require 'session.php';
require 'settings.php';
/* Execute the query. */
$DBH = new PDO($mssql_driver.'='.$mssql_server.';'.$mssql_dbkey.'='.$mssql_database, $mssql_username, $mssql_password);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$tsql = 'select * from ProductImage';
$PRE = $DBH->prepare($tsql);
$PRE->execute();
$pictures =$PRE->fetchAll(PDO::FETCH_ASSOC);
$directory = $_SERVER["DOCUMENT_ROOT"]."\..\..\products\pictures/";
//get all image files with a .jpg extension.
$images = glob($directory . "*.jpg");
$counter =0;
foreach($images as $image)
{
$name = explode('pictures/',$image);
$name = $name[1];
$foundImage = false;
print "checking: ".$name;
foreach ($pictures as $picture){
$original_file = explode('.', $picture['Image_Big']);
$original_file = $original_file[0].'-original.'.$original_file[1];
if ( ($picture['Image_Small'] == $name)|| ($picture['Image_Big'] == $name) || ( $original_file == $name) || ($picture['Image_Thumb'] == $name) || ($picture['Image_PriceList'] == $name)){
$foundImage = true;
break;
}
}
if (!$foundImage) {
unlink($directory . $name);
print "....deleting";
$counter += 1;
}
print "<br />";
if ($counter> 500){
exit;
}
}
?>

When listing information from a database using php and mysql how would you make the first row look different to the rest?

Basically I have articles in my database and I want to alter the way the first record displays. I want the lastest (Posted) article to be the focus and the older article just to list, (see F1.com). I need to know how to get the first of my values in the array and get it to display differently but I am not sure how to do this, I can do it so all rows display the same just not how to alter the first row. I also need to know how to tell the rest of the rows to display the same afterwards im guessing you use an if statement there and before that some kind of count for the rows.
Current code:
$result = mysql_query("SELECT * FROM dbArticle WHERE userID='".$_SESSION["**"]."' ORDER BY timestamp DESC");
while($row = mysql_fetch_array($result))
{
echo "<h2 class=\"heading1\">". $row['title'] ."</h2>";
echo "By: ".$row['username']." Type: ".$row['type']." Posted: ".$row['timestamp']."
$body = $row['body'];
echo "<br/><p>";
echo substr("$body",0,260);
echo "...<span class=\"tool\"><a class=\"blue\" href=\"index.php?pageContent=readArticle&id=".$row['id']."\">Read More</a></span></p><hr/>";
}
mysql_close($con);
Ok I have taken Luke Dennis's code and tried to test it, but I am getting this error: Warning: Invalid argument supplied for foreach() this is the line of the foreach statment. Something that has just come to mind is that I will only want 5 or so of the older articles to display. This is what I have thats creating the error:
<? $con = mysql_connect("localhost","****","***");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("******", $con);
$result = mysql_query("SELECT * FROM dbArticle ORDER BY timestamp DESC");
$first = true;
foreach($result as $row){
if($first)
{
echo"".$row['title']."";
echo"this is the headline";
$first = false;
}
else
{
echo"".$row['title']."";
}
}
?>
Do I need to add mysql_fetch_array somewhere to set the array up?
I would just iterate through the results and apply a css class to the first entry:
$first = true;
while ($row = mysql_fetch_assoc($result)) {
$cssClass = '';
if ($first) {
$cssClass = 'highlight';
}
echo '<p class="' . $cssClass . '">' . $row['text'] . '</p>';
$first = false;
}
It's a bit crude, but I often hard-code a variable to designate the first run through a loop. So something like:
$first = true;
foreach($list_of_items as $item)
{
if($first)
{
// Do some stuff
$first = false;
}
else
{
// Do some other stuff
}
}
A simple if statement when looping through your results will usually do the trick. You can use a boolean to indicate if you've output the first row of results or now. If you haven't then give it a particular style and then set the boolean to true. Then all subsequent rows get a different style.
All of the above are correct. Luke Dennis' post is of course fleshed-out a bit more.
As Brian Fisher said, add some CSS styling to the first link when you encounter it per Luke's post.
I took a look at the article list on the F1 website. Pretty well constructed site - "One would expect that." :-)
Anyway, the article listings are contained within a two row table (summary="Latest Headlines") in descending order (newest first).
Just place a class in the second column (<td class="first-news-article">). Then add the class name and appropriate styling values in the css file - probably your' modules.css. There's already quite a few class values associated with articles in that file, so you may be able to just use an existing value.
That should be about it - other than actually doing it!
By the way, judging by the quality of the underlying html, I'm assuming there's already an "article list emitter." Just find that emitter and place the appropriate conditional to test for the first record.
Darrell
I just noted your code addition. I assume that you were showing the F1 site as an example. Anyway, I think you're on your way.
I presume you have some code that loops through your resultset and prints them into the page? Could you paste this code in, and that might give us a starting point to help you.
I don't know PHP, so I'll pseudocode it in Perl. I wouldn't do it like this:
my $row_num = 0;
for my $row ($query->next) {
$row_num++;
if( $row_num == 1 ) {
...format the first row...
}
else {
...format everything else...
}
}
The if statement inside the loop unnecessarily clutters the loop logic. It's not a performance issue, it's a code readability and maintainability issue. That sort of thing just BEGS for a bug. Take advantage of the fact that it's the first thing in the array. It's two different things, do them in two different pieces of code.
my $first = $query->next;
...format $first...
for my $row ($query->next) {
...format the row...
}
Of course, you must make the first row stand out by using tags.
I'd use array_shift():
$result = mysql_fetch_assoc($resultFromSql); // <- edit
$first = array_shift($result);
echo '<h1>'.$first['title'].'</h1>';
foreach ($result as $row) {
echo '<h2>'.$row['title'].'</h2>';
}
The best way to do this is to put a fetch statement prior to the while loop.
Putting a test inside the while loop that is only true for one iteration can be a waste of time for a result of millions of rows.

Categories