I am trying to read images stored in the directory in PHP by getting only part of its name. The images are named as follows,
AT-1410f1654.jpg
AT-1410_1655.jpg
AT-1410_1656.jpg
AT-1410_1657.jpg
AT-1410_1658.jpg
AT-1410_1659.jpg
I have tried the following code below but it does not work even if I use the PHP substr() method but it also did not work,
$dbImage=$row["pref"];
$imageName=$dbImage;
$extension=".jpg";
$filename=$imageName.$extension;
echo "$filename+<img src='proppics/$filename'>";
Any ideas on how this could be done
The Full Code
$limit=10;
$con=mysql_connect("localhost","root","");
mysql_select_db("movedb") or die("Unable to select database");
$query="select * FROM properties where `name`='Beata Grande 1' & `catergory`='Villas'& `price`=202800 & `area`='Arenas'& `bedrooms`=2 & `region`='Axarquia'";
$numresults=mysql_query($query,$con);
$numrows=mysql_num_rows($numresults);
$result = mysql_query($query) or die("Couldn't execute query");
echo "<center>";
echo "<p>You searched for: "" . $properties . ""</p>";
echo "<form name=payment action='properties_details.php'>";
echo "Results <br>";
while ($row= mysql_fetch_array($result)) {
$id=$row['id'];
$pid=$row['pref'];
// Retrieve the balance database fields
echo "<p>Property ID  ".$pid;
echo "<br> <p> Name  ";
echo $row["name"];
echo "<br> Properties  ";
echo $row["catergory"];
echo "<br> Description  ";
// Print results
echo "<br>";
echo "<input type=submit name=btnbuy value=MoreDetails> ";
First, list all files in your dir using scandir
http://php.net/manual/en/function.scandir.php
then check for existing prefix using strpos
http://php.net/manual/en/function.strpos.php
$dir = 'propix';
$files = scandir($dir);
$prefix = '1410';
foreach($files as $file) {
if(strpos($prefix) !== FALSE) { //here you are supposed to add more...
echo $file;
}
}
How about glob?
Your question isn't clear enough to provide a more comprehensive answer
I am not 100% sure what you're trying to achieve.
But if you want to select only part of the filename either after the "_" or before for whatever reason, you could use PHPs explode() function.
In your case writing:
print explode("_", $dbImage);
Would have an output similar to this:
Array(
[0] => AT-1410
[1] => 1655.jpg
)
Related
I am newer to PHP and I am able to get the desired output but I am doing it one index position at a time. I am returning data from a .txt file and I need to insert this data into an HTML table I am creating using PHP. BUT FIRST I need to be able to get the same output without typing out every index position. I tried to use a forloop but it kept outputting only one line.
I manually outputted the lines from the file and it works. What loop in PHP would be best to achieve the same results and output these elements? IMPORTANT, as is I am able to sort and rsort (I want to be able to do this so if it can be implemented in the loop that would be awesome) any help is more than I have right now.
PHP
$books = array();
if ($fp)
{
while(true)
{
$lines_in_file = count(file($filename));
$line = fgets($fp);
if (feof($fp))
{
break;
}
$line_ctr++;
list($title, $author, $pubdate, $isbn) = explode('*', $line);
$new_line = explode('*', $line);
for($ii= 1; $ii <= $lines_in_file; $ii++){
$lines = fgets($fp); //Read each line
$member = trim($lines);
array_push($books, $member);
}
//This foreach only brings back the first like in the txt file, why?
$cntr = 0;
foreach($books as $element){
$cntr++;
$table .= "<tr>";
$table .= "<td>".$title."</td>";
$table .= "<td>".$author."</td>";
$table .= "<td>".$pubdate."</td>";
$table .= "<td>".$pubdate."</td>";
$table .= "<td>".$isbn."</td>";
$table .= "</tr>\n"; //added newline
echo $element;
}
//sort($books);
// rsort($books);
echo $books[0];
echo "<br>";
echo $books[1];
echo "<br>";
echo $books[2];
echo "<br>";
echo $books[3];
echo "<br>";
echo $books[4];
echo "<br>";
echo $books[5];
echo "<br>";
echo $books[6];
echo "<br>";
echo $books[7];
echo "<br>";
echo $books[8];
echo "<br>";
echo $books[9];
echo "<br>";
echo $books[10];
echo "<br>";
echo $books[11];
echo "<br>";
echo $books[12];
echo "<br>";
echo $books[13];
echo "<br>";
echo $books[14];
echo "<br>";
echo $books[15];
echo "<br>";
echo $books[16];
echo "<br>";
echo $books[17];
}//END WHILE LOOP
fclose($fp ); //Close file
}
Having to make a few guesses here but i believe the file is going to look like:
title*author*pubdate*isbn
title*author*pubdate*isbn
title*author*pubdate*isb
if this is wrong, let me know
as long as the fie is not to large read it in to an array:
$book_array=file('book_file.txt');
//print_r($book_array); //is it an array of the books, one book per array key
now to separate each line:
foreach($book_array as $line){
$line_sep=explode('*',$line);
// with no sorting option you could just echo inside the loop
//if you want to keep sorting options we have to keep the separated lines
$new_book_array[]=$line_sep;
}
unset($book_array);//free up memory if needed
//print_r($new_book_array);//is it a multi-d array, book then the 4 elements
to sort our new multidimensoanl array:
usort($new_book_array, function($a, $b) {
return strcmp($a['0'], $b['0']);;
}); //this sorts on key 0 in your case title:
//print_r($new_book_array); // has it sorted properly
for display:
loop again
echo '<table><tr><th>Title</th><th>Author</th><th>Pub Date</th><th>ISBN</th></tr>';
foreach($new_book_array as $book){
//print_r($book); //is it each indervidual book array with 4 elements
echo '<tr><td>'.$book[0].'</td><td>'.$book[1].'</td><td>'.$book[2].'</td><td>'.$book[3].'</td></tr>';
}
echo '</table>';
i am currently having problem with searching through json file, and i am searching and showing faculties based on searched word but it only shows the value when i type in the full name, how can i get search to work if i like only type first few characters and show the results with name starting with it.
here is my code:
<?php
if(isset($_GET['search_word']))
{
$search_word=$_GET['search_word'];
$string = file_get_contents("faculty_info.json");
$jfo = json_decode($string);
// copy the posts array to a php var
$posts = $jfo->faculty_info;
// listing posts
foreach ($posts as $post) {
if($post->name == "$search_word"){
echo $post->name;
echo "<br>";
echo $post->division;
echo "<br>";
echo $post->school;
echo "<br>";
echo $post->designation;
echo "<br>";
echo $post->email;
echo "<br>";
echo $post->room;
echo "<br>";
echo "<br>";
}
}
}
?>
Try this
$post->name = 'How are you?';
$search_word = "How";
$pos = strpos($post->name, $search_word);
if ( $pos !== false && $pos == 0) {
echo 'found';
//do your script
}
You may also want to replace strpos with stripos in case you need to handle case insensitive searches.
I am attempting to create an ordered list from a text file. As my code currently stands, it modifys the original text file with the input all on the same line(list number). e.g if I input "mercury" it will come out as 1. mercury, but if I input "venus", it will appear as 1.mercuryvenus
I am trying to get it to work so that if I input some text such as "mercury" and hit the submit button, it will appear as
1. mercury. If I input some more text such as "venus", it will appear as 2. venus, all in ordered list format. I assume that explode may be used for this, but I am unsure of how to implement this properly. Another option would be to create a new text file for each input if that were to be more efficient.
echo "<form method='post'>
<label>Enter some text</label><br>
<textarea name='textbox' cols='60' rows='5' required></textarea>
<br>
<input type='submit' name='submit' value='Submit'/>
<input type='hidden' name='step' value=''/>
</form>";
echo "<section>";
echo "<h3>Current tasks</h3>";
$text = ("text.txt");
$extract = (isset($_POST['textbox']) ? $_POST['textbox'] : null);
$file = fopen($text,"a");
fwrite($file,$extract);
fread($file,filesize("text.txt"));
fclose($file); #Not sure where this should really go
$c = array(file_get_contents('text.txt'));
$x = explode(" ",$c); #Could be wrong format
echo "<ol>";
foreach($c as $r) {
echo "<li>" . $r. "</li>", "<br>";
}
echo "</ol>";
echo "</section>";
Here is the solution
echo "<section>";
echo "<h3>Current tasks</h3>";
$text = "text.txt";
$extract = (isset($_POST['textbox']) ? $_POST['textbox'] : null);
$file = fopen($text,"a+");
fwrite($file," ".$extract);
#fread($file,filesize("$text"));
$x = explode(" ",file_get_contents($text));
if(isset($_POST['submit'])) {
echo "<ol>";
foreach ($x as $r) {
echo "<li>" . $r . "</li>", "<br>";
}
echo "</ol>";
echo "</section>"
First, the "a" in fopen($text,"a") means append. Which means if you already have the text "mercury" in your file and your run your program again with "venus", you will be appending "venus" on the end of "mercury" to get "mercuryvenus". If you want a space between the two, you will have to add it when your write it to file: fwrite($file, " ".$extract);
Second, you do $x = explode(... and then do not use $x in your foreach statement. Use $x instead of $c in your foreach.
Basically the code below reads in a text file and diplays it on the screen with checkboxes near each line. But now I want the user to be able to check any box and then display the selected results in a new PHP file - I thought I would have to read in the text file again and somehow refer it to the array, but I'm still stuck, so any help would be appreciated.
Thank you.
First php file
<?php
$filename = "file.txt";
$myarray = file($filename);
print "<form action='file2.php' method='post'>\n";
// get number of elements in array with count
$count = 0; // Foreach with counter is probably best here
foreach ($myarray as $line) {
$count++; // increment the counter
$par = getvalue($line);
if ($par[1] <= 200) {
// Note the [] after the input name
print "<input type='checkbox' name='test[$count]' /> ";
print $par[0]." ";
print $par[1]." ";
print $par[2]." ";
print $par[3]."<br />\n";
}
}
print "</form>";
Second php file which should display the selected results
<?php
$filename = "file.txt";
$myarray = file($filename);
?>
I think you're over complicating the problem. You can just give the checkboxes a value atribute and read the array from the second page. Start with kus print_r ($_POST) on the second page to help you see what you have to work with.
1) Think of format of your text file (could be something like "Name1-Value 1-true\nName1-Value2-false")
2) Learn this function
3) Create a file with the default options
4) Make a PHP script that opens the file, makes an array and prints the resoult - for example:
$handle = fopen('./file.txt','r');
$fileString = fread($handle,filesize('./file.txt'));
$handle = null; //Similar to unset($handle);
$array = explode($fileString, "\n");
echo '<form action="./script2.php">';
foreach ($array as $value) {
$value = explode($value, "-");
echo '<input type="checkbox" name="'.$value[1].'" value="'.$value[2].'" checked="';
if ($value[3]==true) {
echo 'checked" /><br />';
} else {
echo '" /><br />';
}
}
5) Make the second script that edits the file - for example:
if ($_GET == null;) {exit("He's dead, Jim!");}
$handle = fopen('./file.txt','r');
$fileString = fread($handle,filesize('./file.txt'));
//Do something with the string :D
$handle = fopen('./file.txt','w');
fwrite($handle,$fileString);
I am trying to convert a pre-existing site that had html and php intermingled into a Smarty template based site. I never used Smarty before so this is proving very difficult for me. I get that you can assign a variable like so:
$smarty->assign('number_of_items_in_cart', $number_of_items_in_cart);
and use it in the tpl file like so:
{$number_of_items_in_cart}
but what about more complex things like this block of code that I had on the old site:
$query = mysql_query(" SELECT * FROM products WHERE id = '$pid' ");
if (mysql_num_rows($query) == 1) {
while ($row = mysql_fetch_array($query)) {
extract($row);
echo "<h2>$name</h2>";
echo "<img src='images/product_images/$image' alt='' width='100' />";
echo $description;
echo '<p>'.money($price).'</p>';
echo "<input type='text' value='1' class='qty-$id' />";
echo "Add to Cart";
}
} else {
redirect('404.php');
}
How can I work with this in a Smarty template, since the output is within a while loop?
Instead of echoing this, you can append it in a string variable then pass it to smarty:
$string = "";
while ($row = mysql_fetch_array($query)) {
extract($row);
$string .= "<h2>$name</h2>";
$string .= "<img src='images/product_images/$image' alt='' width='100' />";
$string .= $description;
$string .= '<p>'.money($price).'</p>';
$string .= "<input type='text' value='1' class='qty-$id' />";
$string .= "Add to Cart";
}
Now u can pass it to smarty
$smarty->assign('place_holder', $string);
I hope this is what you are looking for
You can use the foreach builtin function to iterate over an array containing your query results.
You could also use foreachelse to display an alternate message (though in this case you're redirecting).
See example 7.9 in http://www.smarty.net/docsv2/en/language.function.foreach .
Edit: there's also a while function if that's what you really want.