Stop table from being generated IF less then X - php

I have a table that is generated upon REST API, I generate for the first 50 in the result. My issue is if the response from REST is less then 50 the table still make the table for 50, just with empty rows on the X amounts that is not available in the response.
So e.g I get result of 47 , then my code generates for 50 still only so last three rows is empty. How do I avoid this ?
for($x=0;$x<50;$x++)
echo "<table><tr><td>" . "<img style='width:200px; height:150px;' src='" . $imagehost . $newImgUrl = preg_replace($pattern, $replacement, $hotelSummary[$x]['thumbNailUrl']) . "'/>" . "</td><td>" . $hotelSummary[$x]['name'] . "</td><td>" . $hotelSummary[$x]['hotelId'] . "</td><td>" . $hotelSummary[$x]['city'] . "</td><td>" . $hotelSummary[$x]['RoomRateDetailsList']['RoomRateDetails']['RateInfos']['RateInfo']['ChargeableRateInfo']['#total'] . "</td><td><button type='button'>Hotel Info</button><td><a href='" . $hotelSummary[$x]['deepLink'] . "' ><button type='button'>Book Now</button></a></td></tr></table>";
So if the response is less then 50 only create for the x amount found, and if the amount is less then 1 echo out e.g No results matches your search.
Can I implement an if sentence in this or how should I do this ?

Don't compare
$x<50
but
$x < $responseFromRest && $x < 50

You could add an if to check to see if the sizeof your response is bigger than $x, if so, echo your line else break. Example:
$reponse = $data;
for($x=0;$x<50;$x++) {
if($x > sizeof($respnse)) {
break;
}
echo "<table><tr><td>" . "<img style='width:200px; height:150px;' src='" . $imagehost . $newImgUrl = preg_replace($pattern, $replacement, $hotelSummary[$x]['thumbNailUrl']) . "'/>" . "</td><td>" . $hotelSummary[$x]['name'] . "</td><td>" . $hotelSummary[$x]['hotelId'] . "</td><td>" . $hotelSummary[$x]['city'] . "</td><td>" . $hotelSummary[$x]['RoomRateDetailsList']['RoomRateDetails']['RateInfos']['RateInfo']['ChargeableRateInfo']['#total'] . "</td><td><button type='button'>Hotel Info</button><td><a href='" . $hotelSummary[$x]['deepLink'] . "' ><button type='button'>Book Now</button></a></td></tr></table>";
}

Related

How can i put an href link in my foreach statement?

For starters i am fairly new at this.
I am trying to figure out how to a href link my row 'inspection_files' and i have tried just about everything. Is there anybody who could help me?
<?php
$i = 0;
foreach ($result as $r) {
echo "<tr>";
echo "<td>" . $r['last_inspection'] . "</td><td>" . strtolower(trim(($r['inspected_by_company']))) . "</td><td>" . strtolower(trim($r['inspection_files'])) . "</td>";
echo "</tr>";
$i++;
}
?>
Hey you can directly use <a> tag inside the <td>, just like below
echo "<td>" . $r['last_inspection'] . "</td><td>" . strtolower(trim(($r['inspected_by_company']))) . "</td><td><a href='" . strtolower(trim($r['inspection_files'])) . "'>" . strtolower(trim($r['inspection_files'])) . "</a></td>";
I hope $r['inspection_files'] this is your URL if this is not your redirect URL then just replace with your actual URL.

php add random array not repeating most recent 5

I'm trying to re-write this code so that it goes with the columns that are going to be user-defined. With this, my challenge consists of
a) Needs to select random starting item from array
b) Select the next random color from the original array that is not equivalent to the most recent items selected based the number: $intNotesColumn + 1
I was thinking a do-while statement nested inside another was appropriate for this but am unsure how to go about this. Here is my code so far:
$metroUIcolors = array( "#A30061", "#8200CC", "008987", "#A05000", "#B85A93", "#C07807", "#E51400", "#297A29" );
$metroUIcolorsLength = count($metroUIcolors);
$intNotesColumn = 3; // This will be user-defined later
// Now I query the SQL database to get my base-code
if ($result->num_rows > 0) {
// output data of each row
echo '<table border=0 valign=top>'
. '<tr>'
. '<td colspan=' . $intNotesColumn . '>' . '<h1>header</h1>' . '</td>'
. '</tr>'
. '<tr>';
$counterRank = 1;
while($row = $result->fetch_assoc()) {
echo "<td bgcolor=" . $metroUIcolors[rand(0, $metroUIcolorsLength - 1)]. ">"
. "<h2>" . $row["username"] . '</h2><br />'
. "<p class='notes'>" . $row["notes"] . "</p>"
. "<p class='footnotes'>"
. "<br />Last Reset: " . $row["lastReset"]
. '<br />Last Update: ' . $row['lastUpdate']
. '<br />SessionID: ' . $row["sessionID"]
. "<br />Counter = " . $counterRank . "</td>". '</p>';
if ($counterRank % $intNotesColumn == 0)
{
echo '</tr><tr>';
}
$counterRank++;
}
echo '</tr></table>';
} else{
echo "No Notes Found in databases";
}
Then, why don't you do it order picking one color at a time. You could use shuffle() so that there will be a different starting color everytime.
<?php
$counterRank = 1;
// shuffle the array
shuffle($metroUIcolors);
while($row = $result->fetch_assoc()) {
$rand_color = $counterRank % $metroUIcolorsLength;
echo "<td bgcolor=" . $metroUIcolors[$rand_color]. ">";
// everything else
$counterRank++;
}
?>
If you insist on doing the way you said, you may create an array $colorCount which has color codes as keys and count as values.
<?php
$counterRank = 1;
$colorCount = array_fill_keys($metroUIcolors, 0);
while($row = $result->fetch_assoc()) {
do {
$rand_color = $metroUIcolors[rand(0, $metroUIcolorsLength - 1)];
} while ($colorCount[$rand_color] > 5);
echo "<td bgcolor=" . $rand_color. ">";
// everything else
$counterRank++;
$colorCount[$rand_color] += 1;
}
?>

Using arrays in PHP

I am working on my first program written in PHP. This is a basic question. I am trying to print a string stored in an array. I have two arrays. One array, $content, stores a number at $content[$i][15] (i am using arrays in arrays, and looping through it with a for loop). Lets say this number is 3. I now want to access a string in another array, called $type. This string is at position $type[3]. Logically, I think, $type[3] should print the same thing as $type[$content[$i][15]]. But, when I call $type[$content[$i][15]], it doesn't print anything, but when i print $type[3] it works fine. Is this type of call not allowed in PHP?
$type = array();
$typetemp = readfile("type.csv");
foreach ($typetemp as $sa){
$type[$sa[0]] = $sa[1];
}
$content = readfile("content.csv");
for($i=0; $i<sizeof($content); $i++){
if($content[$i][15] == 3){
if($content[$i][4] == 1){
$temp = $content[$i][15];
echo "id is " . $content[$i][0] . "title is " . $content[$i][1] . "introtext is " . $content[$i][2] . "restoftext is " . $content[$i][3] . "visible is " . $content[$i][4] . "category is " . $content[$i][5] . "creation_date is " . $content[$i][6] . "author is " . $content[$i][7] . "img is " . $content[$i][8] . "ordering is " . $content[$i][9] . "rank is " . $content[$i][10] . "vid is " . $content[$i][11] . "start_date is " . $content[$i][12] . "stop_date is " . $content[$i][13] . "event_date is " . $content[$i][14] . "type is " . $content[$i][15] . "thumb is " . $content[$i][16] . "type name is " . $type[$temp] . "<br/>";
}
}
}
function readfile($filename) {
$line_of_text = array();
$file_handle = fopen($filename, "r");
while (!feof($file_handle) ) {
array_push($line_of_text, fgetcsv($file_handle, 1024));
}
fclose($file_handle);
return $line_of_text;
}
You are missing a $ sign before content:
$type[$content[$i][15]]
This accesses the value in $type with index $content[$i][15]

mysql & php search highlighting

Wondering if someone could help give me a push in the right direction, I am building a search function (php and mysql) which will display search results and highlights keywords that the user has searched for. at the moment I grab the search criteria that the user has entered and query that against the database which works fine to get the desired results. the problem I have is
$highlight = preg_replace("/".$_GET['criteria']."/", "<span class='highlight'>".$_GET['criteria']."</span>", $_row['name']);
This will only highlight a phrase and not individual keywords. so for example if the document was called "Hello world" and the user typed this exactly it would highlight no problem however if the user typed "world hello" it will not highlight anything. I thought it would be a good idea to take the search criteria and use explode and check each word individually but this seems to fail as well. here is my query and how I am displaying results
$sql = "SELECT *
FROM uploaded_documents
WHERE dept_cat = 'procedures'
AND cat =:cat
AND keywords REGEXP :term ";
$result->execute(array(':cat' => $_GET['category'],':term' => $_GET['criteria']));
//display results
while($row = $stmt->fetch()){
$explode_criteria = explode(" ",$_GET['criteria']);
foreach($explode_criteria as $key){
$highlight = preg_replace("/".$key."/", "<span class='highlight'>".$key."</span>", $row['name']);
echo '<td><a target="_blank" href="'.$row['url'].'">'.$highlight.'</a></td>';
echo '<td>'.$row['version'].'</td>';
echo '<td>'.$row['cat'].'</td>';
echo '<td>'.$row['author'].'</td>';
echo '<td>'.$row['added'].'</td>';
echo '<td>'.$row['auth_dept'].'</td>';
echo '<td>';
}
}
For the sake of length I have omitted code here and tried to keep it minimal, I have been trying to base my work on the following post
highlighting search results in php/mysql
I think my first problem is the foreach loop in the while loop duplicating results but I cant think of a way around it.
Thanks in advance
In this block of code:
//display results
while ($row = $stmt->fetch())
{
$explode_criteria = explode(" ", $_GET['criteria']);
foreach ($explode_criteria as $key)
{
$highlight = preg_replace("/" . $key . "/", "<span class='highlight'>" . $key . "</span>", $row['name']);
echo '<td><a target="_blank" href="' . $row['url'] . '">' . $highlight . '</a></td>';
echo '<td>' . $row['version'] . '</td>';
echo '<td>' . $row['cat'] . '</td>';
echo '<td>' . $row['author'] . '</td>';
echo '<td>' . $row['added'] . '</td>';
echo '<td>' . $row['auth_dept'] . '</td>';
echo '<td>';
}
}
The loop is constantly referring to $row['name'], so the replacement is done, but the next time the loop happens it is replacing the next word on the original unmodified $row['name']
I think this should help you:
//display results
while ($row = $stmt->fetch())
{
$explode_criteria = explode(" ", $_GET['criteria']);
$highlight = $row['name']; // capture $row['name'] here
foreach ($explode_criteria as $key)
{
// escape the user input
$key2 = preg_quote($key, '/');
// keep affecting $highlight
$highlight = preg_replace("/" . $key2 . "/", "<span class='highlight'>" . $key . "</span>", $highlight);
echo '<td><a target="_blank" href="' . $row['url'] . '">' . $highlight . '</a></td>';
echo '<td>' . $row['version'] . '</td>';
echo '<td>' . $row['cat'] . '</td>';
echo '<td>' . $row['author'] . '</td>';
echo '<td>' . $row['added'] . '</td>';
echo '<td>' . $row['auth_dept'] . '</td>';
echo '<td>';
}
}

'if' inside 'while' statement in php

I have this bit of code which loops through an array and echos out the result to the page thus:
while($row = mysqli_fetch_array($result)) {
echo '<tr><td><a target="_blank" href="' . $row['url'] . '">' . $row['name'] . '</a></td>' . '<td>' . $row['provider'] . '</td>' . '<td>' . $row['media'] . "</td></tr><br />\n";
}
It works just fine, but I was hoping to use an 'if' statement on the $row['media'] because it contains some NULL and some !NULL results.
I wanted to be able to echo a different response a little like:
if ($row['media'] != NULL){
echo 'Nope';
} else {
echo $row['media'];
}
Is this possible in this situation?
Thanks.
use:
if ( is_null( $row['media'] ) ) { ... } else { ... }
The best way to accomplish this is using ternary operators:
while (whatever)
{
echo 'foo'
.($statement ? 'bar' : '')
.'baz';
}
Yeah, you would just end the echo, perform the if statement, and then use another echo to finish the code off. When it is parsed, the HTML will still be usable.
while($row = mysqli_fetch_array($result)) {
echo '<tr><td><a target="_blank" href="' . $row['url'] . '">' . $row['name'] . '</a></td>' . '<td>' . $row['provider'] . '</td>' . '<td>';
if($row['media'] == NULL) { echo 'Nope'; } else { echo $row['media']}
echo "</td></tr><br />\n";
}
Well, a very simple solution would be to do this...
$media = $row['media'];
if ($row['media'] == NULL)
$media = 'nope';
echo '<tr><td><a target="_blank" href="' . $row['url'] . '">' .$row['name']. '</a></td>';
echo '<td>' . $row['provider'] . '</td>' . '<td>' . $media . "</td></tr><br />\n";
Yes, break your echo into two different echos:
echo "<tr><td><a target="_blank" href="'" ; // (etc etc)
if($row['media'] != NULL) {
echo "NOPE";
} else {
echo $row['media'];
}
echo " $row['url'] . '">'; // (etc etc)
The syntax isn't perfect but I'm pretty sure you'll get the idea :)
If I understand your question then this should work just fine:
if(is_null($row['media']) echo($row['media']) else echo('Nope');
you can always just use another variable and set it before your echo statement, then use that variable in your echo statement. if you want a one-liner, you can use shorthand syntax like this:
($row['media'] != null) ? 'Nope' : $row['media']
and insert that where you currently just have $row['media']
Why not do it this way?
while($row = mysqli_fetch_array($result)) {
$media = ($row['media'] != NULL) ? $row['media'] : "Invalid";
echo '<tr><td><a target="_blank" href="' . $row['url'] . '">' . $row['name'] . '</a></td>' . '<td>' . $row['provider'] . '</td>' . '<td>' . $media . "</td></tr><br />\n";
}
Have the value put into a temp variable before the echo:
$mediaVal = $row['media'];
if ($mediaVal == NULL) $mediaVal = 'Nope';
echo '<tr><td><a target="_blank" href="' . $row['url'] . '">' . $row['name'] . '</a></td>' . '<td>' . $row['provider'] . '</td>' . '<td>' . $mediaVal . "</td></tr><br />\n";
You might consider stripping each field out into a dedicated variable incase you would life to process them in a similar manner etc
You can do something like this in your select statement
select
CASE
WHEN media IS NULL THEN 'Nope';
ELSE media
END as media
from
table
where......
read more : link text
Yes you can do that. You might want to break the echo into multiple echos so its a little easier to see whats going on.
Also, you should check over your if statement. Be careful with your conditionals.
if ($row['media'] != NULL) {
echo 'Nope';
} else {
echo $row['media'];
}
That will output 'Nope' if $row['media'] is not null. I assume you want to output 'Nope' if $row['media'] is null. In that case you want to use == instead of !=.
You can put it in one statement:
while ( $row = mysqli_fetch_array($result) ) {
echo '<tr><td><a target="_blank" href="' . $row['url'] . '">' . $row['name'] . '</a></td>' .
'<td>' . $row['provider'] . '</td>' .
'<td>' . (is_null($row['media'])?"Invalid Value":$row['media']) . "</td></tr><br />\n";
}
while($row = mysqli_fetch_array($result)) {
echo '<tr><td><a target="_blank" href="' . $row['url'] . '">' .
$row['name'] . '</a></td>' . '<td>' . $row['provider'] .
'</td>' . '<td>' .
($row['media'] == NULL ? 'Not Assigned' : $row['media']).
"</td></tr><br />\n";
}

Categories