'if' inside 'while' statement in php - 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";
}

Related

Parsing an Object with PHP

I have the following format:
{ "_id" : { "$oid" : "61f41a529210000060005487" }, "number" : "3", "name" : "Honduras", "description" : "1500m height farming, price per 200gr", "price" : 7, "stock" : 10, "stars" : "Rated with 4.0 stars by users." }
I need to parse a few entries like the above in PHP. I am using foreach for that purpose. Everything except {"_id": {"$oid": ... }} field seems to be parsed correctly. I get the following error:
Fatal error: Uncaught TypeError: Cannot access offset of type string on string
PHP script:
$products = json_encode($cursor['products']);
$products = json_decode($products, true) ;
foreach ($products as $product) {
$stringID = (string)$product['_id'];
echo '<tr>';
echo '<td>' . $stringID . '</td>';
echo '<td>' . $product['number'] . '</td>';
echo '<td>' . $product['name'] . '</td>';
echo '<td>' . $product['description'] . '</td>';
echo '<td>' . $product['price'] . '</td>';
echo '<td>' . $product['stock'] . '</td>';
echo '<td>' . $product['stars'] . '</td>';
echo '</tr>';
}
I have tried many solutions can't parse it though. Any suggestions?
$product is a string, not an object. You should json_decode($product) before to access to properties.
foreach ($products as $product)
{
$product = json_decode($product); // << decode here
$stringID = $product['_id']['$oid']; // << access to ID
// echo row :
echo '<tr>';
echo '<td>' . $stringID . '</td>';
echo '<td>' . $product['number'] . '</td>';
echo '<td>' . $product['name'] . '</td>';
echo '<td>' . $product['description'] . '</td>';
echo '<td>' . $product['price'] . '</td>';
echo '<td>' . $product['stock'] . '</td>';
echo '<td>' . $product['stars'] . '</td>';
echo '</tr>';
}

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 - json - function call issue

I am having two functions printBefore(json1) and printAfter(json2).
Both are having json object as parameter.jsons are coming from database. They are parsing json and displaying it in correct format.
But it is taking more than 30 seconds.
When I removed functon and displays json as it is. It is not taking time more than second.
I am not able isolate problem. Please Help.
foreach ($records as $record) {
echo '<tr>';
echo '<td>' . $userNames['users'][$record->uid] . '</td>';
echo '<td>' . $userNames['users'][$record->uid] . '</td>';
echo '<td>' . $record->val . '</td>';
echo '<td>' . $record->mi. '</td>';
echo '<td>' . $record->created_on . '</td>';
echo '<td>' . printBefore($record->newData) . '</td>';
echo '<td>' . printAfter($record->oldData) . '</td>';
echo '</tr>';
}
Code for printAfter($oldData)
$oldData = json_decode($oldData, true);
if (isset($OldData['sub_category'])) {
$str = $str . "|Category : " . $this->category[$OldData['sub_category']] . "|";
}
code for PrintBefore($newData)
$newData = json_decode($newData, true);
if (isset($newData['sub_category'])) {
$str = $str . "|Category : " . $this->category[$newData['sub_category']] . "|";
}

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>';
}
}

Which of these two IF Blocks is better coding practice?

User 2 offers to buy an item from User 1. User 1 can accept or reject. If User 1 accepts, then they will both be able to offer feedback about the transaction.
I have 2 blocks of IF statements. They both work and do the same thing but which is better coding practice?
IF BLOCK 1 checks if which user is there first and then checks if the transaction was accepted or if its still pending
if ($_SESSION['user_id'] == $seller) {
if ($row['status'] == 'P') {
echo '<p>' . get_username_by_id($row['buyer']) . ' has made a bid of ' . $row['price'] . ' for your ' . $row['title'] . '
Accept / Reject<br />';
} else if ($row['status'] == 'A') {
echo '<p>' . get_username_by_id($row['buyer']) . ' paid ' . $row['price'] . ' for your ' . $row['title'] . '</p>';
echo 'Give Feedback</p>';
}
} else if ($_SESSION['user_id'] == $buyer) {
if ($row['status'] == 'P') {
echo '<p> You have made a bid of ' . $row['price'] . ' for ' . $row['title'] . '</p>';
} else if ($row['status'] == 'A') {
echo '<p> You have paid ' . $row['price'] . ' for ' . $row['title'] . '</p>';
echo 'Give Feedback</p>';
}
}
Or
IF BLOCK 2 has only 4 if statements and checks both user and status of transaction at same time
if ($_SESSION['user_id'] == $seller && $row['status'] == 'P') {
echo '<p>' . get_username_by_id($row['buyer']) . ' has made a bid of ' . $row['price'] . ' for your ' . $row['title'] . '
Accept / Reject<br />';
} else if ($_SESSION['user_id'] == $buyer && $row['status'] == 'P') {
echo '<p> You have made a bid of ' . $row['price'] . ' for ' . $row['title'] . '</p>';
} else if ($_SESSION['user_id'] == $seller && $row['status'] == 'A') {
echo '<p>' . get_username_by_id($row['buyer']) . ' paid ' . $row['price'] . ' for your ' . $row['title'] . '</p>';
echo 'Give Feedback</p>';
} else if ($_SESSION['user_id'] == $buyer && $row['status'] == 'A') {
echo '<p> You have paid ' . $row['price'] . ' for ' . $row['title'] . '</p>';
echo 'Give Feedback</p>';
}
The first one shows you the path: if the statuses were to increase in number, you could abstract the functionality into a function with little work. It looks and is cleaner.
I'd also prefer to separate the actual HTML from PHP. Instead of
echo '<p>' . get_username_by_id($row['buyer']) . ' has made a bid of '
. $row['price'] . ' for your ' . $row['title'] . '
Accept /
Reject<br />';
I'd prefer
<p>
<?= get_username_by_id($row['buyer']) ?> has made a bid of
<?= $row['price'] ?> for your <?= $row['title'] ?>
Accept /
Reject
</p>
But to each his own.
This is subject to opinion, but I'm sure that most people will agree that the first one is cleaner because you're removing duplication (the check to see if they are buyer or seller). This will be even more apparent if you had more status types.
I would say block 1 is better coding practice in general, since you do not duplicate information. Having said that, Block 2 more accurately describes the set of Strategy patterned objects which might arise in a different language environment and which could reduce the complexity of your code further.
As a personal choice I prefer the structure of option 1 because of the lower number of conditions. But I would change each else if to elseif to prevent errors because of omitted braces.
To let the code show some common data is used in the output, and the differences in the closing </p> tag of each choice, I would change it into something like this:
$buyerName = get_username_by_id($row['buyer']);
$price = $row['price'];
$title = $row['title'];
if ($_SESSION['user_id'] == $seller) {
if ($row['status'] == 'P') {
echo "<p>$buyerName has made a bid of $price for your $title"
. " <a href='transactions.php?id=$transactionid&action=accept'>Accept</a> /"
. " <a href='transactions.php?id=$transactionid&action=reject'>Reject</a><br />";
} elseif ($row['status'] == 'A') {
echo "<p>$buyerName paid $price for your $title</p>"
. "<a href='feedback.php?id=$transactionid&action=givefeedback'>Give Feedback</a></p>";
}
} elseif ($_SESSION['user_id'] == $buyer) {
if ($row['status'] == 'P') {
echo "<p> You have made a bid of $price for $title</p>";
} elseif ($row['status'] == 'A') {
echo "<p> You have paid $price for $title</p>"
. " <a href='feedback.php?id=$transactionid&action=givefeedback'>Give Feedback</a></p>";
}
}

Categories