PHP replacing blank images with a default one - php

Having one of those brain fade moments this morning. I have the following php:
$imgset = $result->fields[6];
if ($imgset = '')
{
$imgset = 'logo';
}
else
{
$imgset = $result->fields[6];
}
echo '<img id="imgdisp" src="/img/'.$imgset.'.jpg" />';
$imgset = '';
Where it looks to see if the result from the database is blank and if so, should put in logo.jpg instead of whatever the result is. For some reason though, it just does not want to work and I am probably being completely blind, but cannot see why not. I still get blank images in the HTML and filenames of "/img/.jpg" as though $imgset is still passing through a blank. The values are not NULL in the SQL either, they are most definitely blank entries inputted from an inputbox using a _POST in a form elsewhere.

This:
if ($imgset = '') {
Is always setting $imgset to empty. Use comparison instead:
if ($imgset == '') {
Your else is also not needed since in that case $imgset is already set as $result->fields[6];.

Try to verify if the image exists in your path as well
<?php
$imgset = $result->fields[6];
if ($imgset) {
$imgset = $result->fields[6];
$path ='pathtoimages';
if(!file_exists($path.'/'.$imageset.'.jpg'){
$imgset = 'logo';
}
}
else
{
$imgset = 'logo';
}
echo '<img id="imgdisp" src="/img/'.$imgset.'.jpg" />';
?>

You forgot to compare on the if condition and instead you are assigning an empty value to $imgset. if ($imgset = '') should be if ($imgset == '')

$imgset = $result->fields[6];
if ($imgset == '')
{
$imgset = 'logo';
}
echo '<img id="imgdisp" src="/img/'.$imgset.'.jpg" />';
$imgset = '';
you do not need the else part as the value is already assigned in the first statement.

Using a ternary operator it can be done like this:
echo '<img id="imgdisp" src="/img/'.(empty($imgset)?'logo':$imgset).'.jpg" />';
Shorter code at the cost of readability.

This is the reason why it's better to reverse the condition:
if ('' = $imgset)
would have lead to an error.
The answer:
if ('' == $imgset)
//or
if (empty($imgset))

If you are selecting from MYSQL, you can use something like
SELECT *,COALESCE(image,"logo") AS image FROM ....
This way when the results come back and some rows have a NULL image, it will be replaced by "logo" so you don't need the IF logic in your PHP :)

Related

How do you make sure an array is empty in PHP?

Im writing a page in HTML/PHP that connects to a Marina Database(boats,owners etc...) that takes a boat name chosen from a drop down list and then displays all the service that boat has had done on it.
here is my relevant code...
if(isset($_POST['form1'])){//if there was input data submitted
$form1 = $_POST['form1'];
$sql1 = 'select Status from ServiceRequest,MarinaSlip where MarinaSlip.SlipID = ServiceRequest.SlipID and BoatName = "'.$form1.'"';
$form1 = null;
$result1 = $conn->query($sql1);
$test = 0;
while ($row = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
$values1[] = array(
'Status' => $row['Status']
);
$test = 1;
}
echo '<p>Service Done:</p><ol>';
if($test = 1){
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
echo '</ol>';
}else{
echo 'No service Done';
}
the issue im having is that some of the descriptions of sevice are simply Open which i do not want displayed as service done, or there is no service completed at all, which throws undefined variable: values1
how would I stop my script from adding Open to the values1 array and display a message that no work has been completed if values1 is empty?
Try this
$arr = array();
if (empty($arr))
{
echo'empty array';
}
We often use empty($array_name) to check whether it is empty or not
<?php
if(!empty($array_name))
{
//not empty
}
else
{
//empty
}
there is also another way we can double sure about is using count() function
if(count($array_name) > 0)
{
//not empty
}
else
{
//empty
}
?>
To make sure an array is empty you can use count() and empty() both. but count() is slightly slower than empty().count() returns the number of element present in an array.
$arr=array();
if(count($arr)==0){
//your code here
}
try this
if(isset($array_name) && !empty($array_name))
{
//not empty
}
You can try this-
if (empty($somelist)) {
// list is empty.
}
I often use empty($arr) to do it.
Try this instead:
if (!$values1) {
echo "No work has been completed";
} else {
//Do staffs here
}
I think what you need is to check if $values1 exists so try using isset() to do that and there is no need to use the $test var:
if(isset($values1))
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
Or try to define $values1 before the while:
$values1 = array();
then check if it's not empty:
if($values1 != '')
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
All you have to do is get the boolean value of
empty($array). It will return false if the array is empty.
You could use empty($varName) for multiple uses.
For more reference : http://php.net/manual/en/function.empty.php

php check if two variables are empty and merge them togheter

First thing first, i'm new to php.
I'm trying to check if two variables are both empty, and if so merge them togheter to display only one result, but if one of them is not empty, than i have to display is value.
I currently have:
$customerNotesWC = "";
$DYSPrintableOrderNotes = "test note";
Here's the code i tried so far:
function displayCustomerOrderNotes($customerNotesWC,$DYSPrintableOrderNotes){
if ($customerNotesWC == "") {
$customerNotesWC = "(none)";
}
if ($DYSPrintableOrderNotes ==""){
$DYSPrintableOrderNotes = "(none)";
}
if ($DYSPrintableOrderNotes == "(none)" && $customerNotesWC == "(none)"){
$NotesToDisplay = "(none)";
}
else {
$NotesToDisplay = $customerNotesWC . "<br/>" . $DYSPrintableOrderNotes;
}
}
Unfortunately this doesn't work, as the results is the following:
(none)
Pre-sale order note
I know that there must be a better way to achieve this, and any suggestions will be really appreciated.
Thanks a lot
In order to get your desired functionality of only printing "(none)" when both values are blank, the simplest thing to do to fix your code is remove the code that's setting either value to "(none)" and change your main if-statement to check for "":
function displayCustomerOrderNotes($customerNotesWC,$DYSPrintableOrderNotes){
if ($DYSPrintableOrderNotes == "" && $customerNotesWC == ""){
$NotesToDisplay = "(none)";
}
else {
$NotesToDisplay = $customerNotesWC . "<br/>" . $DYSPrintableOrderNotes;
}
//shouldn't there be an echo $NotesToDisplay; or return $NotesToDisplay; ? or something?
}

How to add '#' symbol if it doesn't exist in the field?

I'm outputting a custom user field in Wordpress, which is user's Twitter username. Some users might add it with '#' symbol, some might without. How can I output that field and check if the symbol already exists, if not, add it?
This is code I'm using to output usrename:
<?php echo get_the_author_meta('twitter_name'); ?>
<?php
$authorMeta = get_the_author_meta('twitter_name');
if (strpos('#', $authorMeta) !== 0) {
$authorMeta = '#'.$authorMeta;
}
echo $authorMeta;
you need to check if # is on 1st place, you can do this in many ways
<?php
$authorMeta = get_the_author_meta('twitter_name');
if ($authoMeta[0] != '#') {
$authorMeta = '#'.$authorMeta;
}
echo $authorMeta;
Try this...it might help
$a = get_the_author_meta('twitter_name');
$b = explode('#',$a);
if($b[1] == 0){
echo "#".$a;
}
else{
echo $a;
}

Check if the fetched array is empty or not PHP?

I am trying to check if the mysql_fetch_array() function returns an empty array or not. But my code doesn't seem to work. Here I want to ensure that if the array is empty I want to display under construction message.
Code :
$queryContents= queryMembers();
$exeQuery = mysql_query($queryContents);
while($fetchSet = mysql_fetch_array($exeQuery)) {
if(count($fetchSet) == 0) {
echo "This Page is Under Construction";
}else{
// something else to display the content
}
}
How do I check to acheive such feature ?
use mysql_num_rows to count number of rows. try this.
$exeQuery = mysql_query($queryContents);
if(mysql_num_rows($exeQuery)== 0){
echo "This Page is Under Construction";
}
else{
while($fetchSet = mysql_fetch_array($exeQuery)) {
// something else to display the content
}
}
You really should be using mysql_num_rows http://us2.php.net/manual/en/function.mysql-num-rows.php
However, on a side note, you should use php empty() instead. http://us2.php.net/empty
When you use mysql_fetch_array(), it returns the rows from the data
set one by one as you use the while loop.
If there will be no record, while loop wont execute. In this case, declare a boolean variable and make it true if it enters the while loop. Like:
$queryContents= queryMembers();
$exeQuery = mysql_query($queryContents);
$recordExists = 0;
while($fetchSet = mysql_fetch_array($exeQuery)) {
if($recordExists == 0 )
$recordExists = 1;
// something else to display the content
}
if($recordExists == 0 ){
echo "This Page is Under Construction";
}
Hope this works!
You can do it this way:
while($r[]=mysql_fetch_array($sql));
// now $r has all the results
if(empty($r)){
// do something
}
source: php doc
Your code inside the while loop never runs if there are no results. mysql_fetch_array returns null/false if there are no more results. What you need yo do is check with mysql_num_rows first, before the while.
$queryContents= queryMembers();
$exeQuery = mysql_query($queryContents);
if(mysql_num_rows ($exeQuery) == 0) {
echo "This Page is Under Construction";
}
while($fetchSet = mysql_fetch_array($exeQuery)) {
// something else to display the content
}
Try this
if(empty($fetchSet)
{
echo "This Page is Under Construction";
}
else
{
// something else to display the content
}

Wordpress QR Code Widget

Basically, I've been trying to make a simple Wordpress widget that displays a QR code with the URL of the current page. I'm using a modififed version of the simple text widget that parses PHP too.
function the_qrcode($permalink = '', $title = '') {
if($permalink && $title == '') {
$permalink = 'http://eternityofgamers.com/forums';
$title = 'Forums';
}
echo '<img src="http://api.qrserver.com/v1/create-qr-code/?data=' .$permalink. '" alt="QR: ' .$title. '"/>;
}
Can someone tell me what's wrong with this? I get a 500 error when I add it to functions.php.
You will need to use the urlencode() function. Generally as a rule of thumb all querystring values should be url encoded.
function the_qrcode( $permalink = '' ) {
if($permalink == '') {
$permalink = 'http://eternityofgamers.com/forums';
}
echo '<img src="http://api.qrserver.com/v1/create-qr-code/?data='.urlencode($permalink);
}
Now you can create your QR code with:
the_qrcode(the_permalink());
Also, you had a very bad missing equals sign. It is very important to understand the difference between = and ==. If you don't, no matter the context = and == mean two different things. = assigns the right hand side to the left. == returns true or false whether the left and right hand side are loosely equal (loosely because casting will be used if the sides are not of the same type).
Look at this example (Codepad demo):
$a = 5;
$b = 10;
if($a = 6) {
echo "This always appears because when you assign a truthy (all non-zero numbers are true) to a variable, true is returned.\n";
echo "Also a should now equal six instead of five: " . $a . "\n";
}
if($b == 10) {
echo "This will work as expected because == is a comparison not an assignment.\n";
echo "And b should still be 10: " . $b;
}
Try with:
<?php
function the_permalink( $permalink ) {
if ($permalink == '') {
echo '<img src="http://api.qrserver.com/v1/create-qr-code/?data=http://eternityofgamers.com/forums" alt="QR Code">';
} else {
echo '<img src="http://api.qrserver.com/v1/create-qr-code/?data='.$permalink;
}
}
?>
(I've corrected a bunch of syntax errors)

Categories