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>";
}
}
Related
I can't figure it out, why I get such a thing:
It is not infinite.
The workingList array has only 3 records:
if ($workerList) {
foreach ($workerList as $worker) {
$option .= '<option value="' . $worker["name"] . '" '
. ($worker["name"] === $b["worker"])
? "selected='selected'"
: "" . '>' . $worker['name'] . '</option>';
}
var_dump($option);
}
Did I mess up with quotes?
P.S. $b["worker"] can be null or a string.
Use the following.
if ($workerList) {
foreach ($workerList as $worker)
{
$selected_value = ($worker["name"] === $b["worker"]) ? "selected" : "";
$worker_name = $worker["name"];
$option .= '<option value="' . $worker_name . '" ' . $selected_value . '>' . $worker_name . '</option>';
}
echo $option;
}
The problem that you've experienced is an issue in the realm of "encapsulationg".
Your:
$option .= '<option value="' . $worker["name"] . '" ' . ($worker["name"] === $b["worker"]) ? "selected='selected'" : "" . '>' . $worker['name'] . '</option>';
Is the same as saying:
$option .= '<option value="' . $worker["name"] . '" ';
if ($worker["name"] === $b["worker"]) {
$option .= "selected='selected'";
} else {
$option .= "" . '>' . $worker['name'] . '</option>';
}
Because you didn't use parentheses to encapsulate the entire ternary expression, the "else" branch gobbled up all of the trailing text.
Put more simply, your code is this:
(condition) ? 'true branch' : 'false branch' . ' trailing text'
But your coding intent is:
(condition ? 'true branch' : 'false branch') . ' trailing text'
Your code could be corrected as:
$option .= '<option value="' . $worker["name"] . '" ' . ($worker["name"] === $b["worker"] ? "selected='selected'" : "") . '>' . $worker['name'] . '</option>';
But I have a strong distaste for messy concatenation/interpolation when adding multiple variables and/or conditions to a string.
Also, there is never any need to declare the value attribute of an option tag if it is identical to the option's visible text. All form submissions and javascript will work seamlessly.
I recommend the following:
$option .= sprintf(
'<option%s>%s</option>',
$worker['name'] === $b['worker'] ? ' selected' : '',
htmlspecialchars($worker['name'])
);
This one kills me every time it happens: something that worked just fine the last time it was run doesn't work the next time I try to run it and no changes were made anywhere in the script. Especially this issue because other times it had been awhile since I ran the script so changes had been made in included files that caused the script to not work, but this time, it worked yesterday when I logged off for the day but when I log back on today, it doesn't all of a sudden. Because that makes sense, right?!
The script's functionality is to display data for products stored in MySQL database along with search & sorting options for the more than 1600 products stored(this will be over 14,000 in the future so this needs to be fixed/optimized now to prevent future issues). It's largely unfinished but the main function, displaying the table and data, worked fine yesterday. Also, when I went to check for errors, I discovered an error_log with over 300MB-worth of two repeating errors:
mysqli_connect(): (HY000/1040): Too many connections in ...
mysqli_error() expects parameter 1 to be mysqli, boolean given in ...
I had received this error once before and did some searching to discover that I never closed any of my connections. After adding mysqli_close($db) to all of my functions that opened a connection, the error went away and everything was fine. Now it's throwing the error again even with mysqli_close($db) and I'm at a loss here. And on top of that, I don't understand why it throws this error and continuously repeats till I stop the page reloading instead of just ending the process with one error reported.
Products Table Script
function dispTable($var) {
require 'db-inc.php'; // << Database connection file
require 'dlc-forms.php'; // << Holds $search_bar and $view_per_page forms
// Define and validate variables
$currentpage=$order_by=$limit_view=$query=$column=$direction='';
getVars();
// Query
$sql="SELECT * FROM tbl" . $query . $order_by . $limit_view;
$res=mysqli_query($db, $sql);
$count=mysqli_num_rows($res);
// Display result count
if (($var == 'results') && (isset($_GET['q']))) {$res_count='Search returned ' . $count . ' results.';}
// Loop through result set
if ($var == 'table') {echo '
<table>
<thead>
<tr>
// Not sure about having 2 table headers, but I want
// the search bar to be right above the header row.
<th></th>
<th colspan="2">' . $search_bar . '</th>
</tr>
<tr>
<th>' . sortBtn('id') . '</th>
<th>' . sortBtn('title') . '</th>
<th>' . $view_per_page . '</th>
</tr>
</thead>
<tbody>';
while ($row=mysqli_fetch_assoc($res)) {
$id=$row['id'];
$title=$row['title'];
$link=$row['link'];
echo '<tr><td>' . $id . '</td><td>' . $title . '</td><td>' . $link . '</td></tr>';
} echo '
</tbody>
<tfoot>';
// Display pagination
if (($var == 'pages') && (isset($_GET['view']))) {pagination();}echo '
</tfoot>
</table>';
} mysqli_close($db);
}
Scripts For Reference
function getVars() {
$x='0'; $r='0'; $row=array(); $range='3';
$num='item_num'; $name='item_name'; $btn='item_btn';
if (isset($_GET['search'])) {
return $search=checkData(trim($_GET['search']));
return $query=" WHERE title LIKE '%" . $search . "%'";
}
if (isset($_GET['col'])) {
return $col=checkData(trim($_GET['col']));
}
if (isset($_GET['sort'])) {
return $dir=checkData(trim(strtoupper($_GET['sort'])));
return $order_by=" ORDER BY " . $col . " " . $dir;
}
if ((isset($_GET['view'])) && (is_numeric($_GET['view']))) {
return $view=checkData(trim($_GET['view']));
return $limit_view=" LIMIT 0," . $view;
}
if ((isset($_GET['page'])) && (is_numeric($_GET['page']))) {
return $page=checkData(trim($_GET['page']));
}
}
function pagination() {
$dbase='thesof73_dlc';
require 'inc/db-inc.php';
getVars();
$tbl_total=mysqli_num_rows(mysqli_query($db, "SELECT * FROM dlc_tbl"));
$total=ceil($tbl_total/$view);
$prev=$currentpage - 1;
$next=$currentpage + 1;
if ($currentpage > $total) {$currentpage=$total;}
if ($currentpage < 1) {$currentpage=1;}
if ($currentpage > 1) {echo '
<li>First</li>
<li>Back</li>';
}
for ($x=($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
if (($x > 0) && ($x <= $total)) {
if ($x == $currentpage) {
echo '<li>' . $x . '</li>';
} else {
echo '<li>' . $x . '</li>';
}
}
}
if ($currentpage != $total) {echo '
<li>Next</li>
<li><a class="material-icons" href="' . htmlspecialchars($_SERVER['PHP_SELF']) . '?page=' . $total . '">Last</a></li>';
} mysqli_close($db);
}
function sortBtn($var) {
if ($var == 'id') {$header='Item No.';}
elseif ($var == 'title') {$header='Product Name';}
getVars();
$asc='asc';
$desc='desc';
if ((isset($_GET['sort'])) && ($col == $var)) {
if ($dir == 'desc') {
return '<a id="sort" href="?q=' . $q . '&sort=' . $desc . '&col=' . $var . '">' . $header . ' <span class="fa fa-sort-' . $desc . '"></span></a>';
} elseif ($dir == 'asc') {
return '<a id="sort" href="?q=' . $q . '&sort=' . $asc . '&col=' . $var . '">' . $header . ' <span class="fa fa-sort-' . $asc . '"></span></a>';
}
} else {
return '<a id="sort" href="?q=' . $q . '&sort=' . $desc . '&col=' . $var . '">' . $header . ' <span class="fa fa-sort"></span></a>';
}
}
I know it's a mess to look at, even worse before I put pieces of the code into functions, but I'm only providing the code for reference seeing as it worked fine yesterday. Thanks in advance!
I am checking some conditional statements and finally outputting a value. I get the correct output. But when the $query is empty i want to return null. Otherwise it shows a php error. I want to get rid from the php error when the query is empty. I have no idea about this. If anyone has an idea it would be a great help.
here is my model method.
function get_calendar_data($year, $month) {
$query = $this->db->select('date_cal,title,type,description,telephone_number,advanced_payment_status')->from('reservations')->like('date_cal', "$year-$month", 'after')->order_by('date_cal', "asc")->get();
if ($query!='') {
$content = "";
$lastDay = -1;
$index = 0;
foreach ($query->result() as $row) {
if ($lastDay != intval(substr($row->date_cal, 8, 2))) {
if ($index > 0) {
if ($content != '') {
$cal_data[$lastDay] = $content;
$content = '';
}
}
$index = 0;
}
if ($row->title == 'RP' && $row->type == 'AM' && $row->advanced_payment_status=='yes') {
$content .= '<div class="rp_am_yes" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
} else if ($row->title == 'RP' && $row->type == 'AM' && $row->advanced_payment_status=='no') {
$content .= '<div class="rp_am_no" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
} else if ($row->title == 'RP' && $row->type == 'PM' && $row->advanced_payment_status=='yes') {
$content .= '<div class="rp_pm_yes" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
} else if ($row->title == 'RP' && $row->type == 'PM' && $row->advanced_payment_status=='no') {
$content .= '<div class="rp_pm_no" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
} else if ($row->title == 'GK' && $row->type == 'AM' && $row->advanced_payment_status=='yes') {
$content .= '<div class="gk_am_yes" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
} else if ($row->title == 'GK' && $row->type == 'AM' && $row->advanced_payment_status=='no') {
$content .= '<div class="gk_am_no" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
} else if ($row->title == 'GK' && $row->type == 'PM' && $row->advanced_payment_status=='yes') {
$content .= '<div class="gk_pm_yes" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
}else if ($row->title == 'GK' && $row->type == 'PM' && $row->advanced_payment_status=='no') {
$content .= '<div class="gk_pm_no" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
}else{
$content .='<div class="add"></div>';
}
$lastDay = intval(substr($row->date_cal, 8, 2));
$index++;
}
if ($lastDay != -1 && $content != '') {
$cal_data[$lastDay] = $content;
}
return $cal_data;
} else if($query==''){
return Null;
}
}
I am getting this php error when the $query is empty. It says about the return value which outputting when the $query is not empty.
Define $cal_data = NULL; at the top of the function. If the condition doesnot satisfied then $cal_data will never be defined.
If it is define as NULL then if the condition is satisfied it will return the proper data else NULL.
$cal_data = NULL;
... rest of the code ...
if ($lastDay != -1 && $content != '') {
$cal_data[$lastDay] = $content;
}
return $cal_data;
Make sure that you always write the DB related code in try..catch blocks. Assuming that the $db->select returns array, you can write the following:
try{
if(isset($query) && empty($query)){
return null;
}
<Code line 1>
<Code line 2>
<Code line 3>
...
}catch(Exception $e){
return null; //or what ever you want to return.
}
One more thing to remember your first try did not work since the query is never returned empty. If i write a query that returns zero rows from the database the $query will be like
CI_DB_mysql_result Object
(
[conn_id] => Resource id #40
[result_id] => Resource id #45
[result_array] => Array
(
)
[result_object] => Array
(
)
[custom_result_object] => Array
(
)
[current_row] => 0
[num_rows] => 0
[row_data] =>
)
The proper way for checking wether the array is empty is by calling the
result()
method for your query.
that is
$query->result();
will return an empty array for zero rows returned.
Or else you can try to check wether the
$query[num_rows]>0
Hope it helped.
User num_rows() functions to get number of rows in query.
function get_calendar_data($year, $month) {
$query = $this->db->select('date_cal,title,type,description,telephone_number,advanced_payment_status')->from('reservations')->like('date_cal', "$year-$month", 'after')->order_by('date_cal', "asc")->get();
$row_num=$query->num_rows();
if ($row_num>0) {
$content = "";
$lastDay = -1;
$index = 0;
foreach ($query->result() as $row) {
if ($lastDay != intval(substr($row->date_cal, 8, 2))) {
if ($index > 0) {
if ($content != '') {
$cal_data[$lastDay] = $content;
$content = '';
}
}
$index = 0;
}
if ($row->title == 'RP' && $row->type == 'AM' && $row->advanced_payment_status=='yes') {
$content .= '<div class="rp_am_yes" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
} else if ($row->title == 'RP' && $row->type == 'AM' && $row->advanced_payment_status=='no') {
$content .= '<div class="rp_am_no" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
} else if ($row->title == 'RP' && $row->type == 'PM' && $row->advanced_payment_status=='yes') {
$content .= '<div class="rp_pm_yes" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
} else if ($row->title == 'RP' && $row->type == 'PM' && $row->advanced_payment_status=='no') {
$content .= '<div class="rp_pm_no" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
} else if ($row->title == 'GK' && $row->type == 'AM' && $row->advanced_payment_status=='yes') {
$content .= '<div class="gk_am_yes" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
} else if ($row->title == 'GK' && $row->type == 'AM' && $row->advanced_payment_status=='no') {
$content .= '<div class="gk_am_no" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
} else if ($row->title == 'GK' && $row->type == 'PM' && $row->advanced_payment_status=='yes') {
$content .= '<div class="gk_pm_yes" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
}else if ($row->title == 'GK' && $row->type == 'PM' && $row->advanced_payment_status=='no') {
$content .= '<div class="gk_pm_no" id="' . $row->date_cal . '" title="Name :' . $row->description . ' Contact No : ' . $row->telephone_number . '">' . $row->title . ' ' . $row->type . '</div>';
}else{
$content .='<div class="add"></div>';
}
$lastDay = intval(substr($row->date_cal, 8, 2));
$index++;
}
if ($lastDay != -1 && $content != '') {
$cal_data[$lastDay] = $content;
}
return $cal_data;
} else {
return Null;
}
}
I'm using a script PHP to get all posts from a fan page. The code is this:
require_once("../facebook-sdk/src/facebook.php");
$config = array(
'appId' => '#############',
'secret' => '###############################',
'fileUpload' => false
);
$facebook = new Facebook($config);
$facebook->setAccessToken("###################################");
$pageid = "###############";
$pagefeed = $facebook->api("/" . $pageid . "/feed");
$i = 0;
foreach($pagefeed['data'] as $post) {
if ($post['type'] == 'video' || $post['type'] == 'link' || $post['type'] == 'photo') {
// open up an fb-update div
echo "<div class=\"fb-update\">";
// check if post type is a link
if ($post['type'] == 'link') {
echo '<img class="imagem-feed" src="' . $post["picture"] . '">';
$interno = "<p>" . $post['message'] . "</p><p>" . $post['link'] . "</p>";
}
// check if post type is a photo
if ($post['type'] == 'photo') {
$fotoAlta = $facebook->api("/" . $post["object_id"] . "?fields=source");
echo '<img class="imagem-feed" src="' . $fotoAlta["source"] . '">';
//interno
if (empty($post['story']) === false) {
$interno = "<p>" . $post['story'] . "</p>";
} elseif (empty($post['message']) === false) {
$interno = "<p>" . $post['message'] . "</p>";
}
$interno .= "<p>Ver no Facebook →</p>";
}
// check if post type is a video
if ($post['type'] == 'video') {
echo '<iframe class="imagem-feed" width="350" height="263" src="' . str_replace("&autoplay=1","",$post["source"]) . '" frameborder="0" allowfullscreen></iframe>';
//interno
if (empty($post['story']) === false) {
$interno = "<p>" . $post['story'] . "</p>";
} elseif (empty($post['message']) === false) {
$interno = "<p>" . $post['message'] . "</p>";
}
}
echo '<div class="cabecalho-fanpage"><a target="_blank" href="https://www.facebook.com/Angelameza.arquitetura"><img class="img-perfil-fanpage" width="50" height="50" src="http://profile.ak.fbcdn.net/hprofile-ak-ash1/373040_201176906637605_665931623_q.jpg"><h1>' . $post["from"]["name"] . '</h1><p>' . date("d/m/Y", (strtotime($post['created_time']))) . '</p></a></div>';
echo $interno;
echo '<div class="container-interacoes">';
$totalCurtidas = $facebook->api("/" . $post["id"] . "/likes/?summary=true");
$titulo = ($totalCurtidas["summary"]["total_count"] == 0 || $totalCurtidas["summary"]["total_count"] > 1) ? $totalCurtidas["summary"]["total_count"] . " pessoas curtiram isso." : "1 pessoa curtiu isso.";
echo "<span title='$titulo' class='icon-curtidas'>" . $totalCurtidas["summary"]["total_count"] . "</span>";
$compartilhamentos = (isset($post["shares"]["count"])) ? $post["shares"]["count"] : 0;
$titulo = ($compartilhamentos == 0 || $compartilhamentos > 1) ? $compartilhamentos . " pessoas compartilharam isso." : "1 pessoa compartilhou isso.";
echo "<span title='$titulo' class='icon-compartilhamentos'>" . $compartilhamentos . "</span>";
$totalComentarios = $facebook->api("/" . $post["id"] . "/comments/?summary=true");
$titulo = ($totalComentarios["summary"]["total_count"] == 0 || $totalComentarios["summary"]["total_count"] > 1) ? $totalComentarios["summary"]["total_count"] . " pessoas comentaram isso." : "1 pessoa comentou isso.";
echo "<span title='$titulo' class='icon-comentarios'>" . $totalComentarios["summary"]["total_count"] . "</span>";
echo "</div>";
echo "<div style='clear:both'></div></div>"; // close fb-update div
$i++; // add 1 to the counter if our condition for $post['type'] is met
}
} // end the foreach statement
Using this code, the page is very slow (50 seconds to load). I tested any thing for optimize and don't improve. Can someone help me?
You are making calls to graph API inside the for loop, i.e for every post, you are making additional calls. Obviously, this contributes towards your 50 secs. Your best bet is to arrange your code to use batch requests. Here is the documentation for batching calls.
https://developers.facebook.com/docs/graph-api/making-multiple-requests/
Note: You can make upto 50 calls in one go using a batch request.
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";
}