Remove Last Comma In Loop

When performing a database query, we normally use a loop to output the database result. This is a common exercise for programmers when displaying results to the screen. To make the output readable, commas are typically used to separate data. Consider a loop below that prints a list of names. We added a string ‘, ‘ after each name to make it readable.

foreach($query as $item) :
echo $item->name.', '; 
endforeach;

The output would be something like this:
John, Mary, Steve, Mark,

The output works as intended, but there is a trailing comma at the end that we don’t want. We either need to get rid of it, or replace it with a period. So, how do we do that? Here’s how.

We will use the trim() function to remove the last comma. But before we can do that, we should probably hold off on echoing to the screen until the loop is finished. So, we will store the results in a variable called $result as we go through the loop. To avoid a PHP undefined variable error, we need to initialize the $result variable before the loop begins. After the loop, we will use the rtrim function to remove the last comma. Finally, we echo the trimmed results and add a period.

$result="";
foreach($query as $item) :
$result.=$item->name.', '; 
endforeach;
$trimmed=rtrim($result, ', ');
echo $trimmed;
echo '.';

The output is now:
John, Mary, Steve, Mark.

Bootstrap Your Website

Jumpstart your website by adding Bootstrap, a front-end CSS framework started by a couple of Twitter developers. If you are starting on a new web project, why not dress it with Bootstrap. You can quickly transform your website, by just adding a couple of markups. Bootstrap uses some HTML markup, LESS CSS, and Javascript plugins to create the framework.

To get started, Download Bootstrap first.

Then, use this HTML Bootstrap template

<!DOCTYPE html>
<html>
  <head>
    <title>Bootstrap 101 Template</title>
    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
  </head>
  <body>
  <div class="container-fluid">
    <h1>Hello, world!</h1>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script src="js/bootstrap.min.js"></script>
  </div>
  </body>
</html>

To learn more about Bootstrap, just play around with all the different aspects of the framework. Add some navigation buttons, forms, tables, alerts, and some Javascript features. Finally, you can learn a lot more by studying the rest of the documentation.

Dropbox Folder As Web Root

One of many clever ways you can do with Dropbox is to make it the web root of your development server. There’s an advantage to doing this, as I’ll explain in this post. Currently, I have Dropbox installed on my Linux Mint desktop. I also use the desktop as my web development server. I have Apache, PHP, MySQL, etc. installed. Typically the web root of the Apache web server, is located in the /var/www directory. I’ve changed mine to a Dropbox folder at /home/ulysses/Dropbox/web/.

There’s an advantage to making Dropbox the web root. I normally use multiple computers to code. I have a Linux desktop, Macbook Air, and a Windows machine. I installed Dropbox on all of them, and placed my code in a Dropbox folder to share files. My code is always synched on all computers. Each time I move to another computer, I can always access the same code, because Dropbox does a fantastic job of synching files on all my computers.

In addition, I made Dropbox the web root of my development server, so every time I make a file change, the development web server is also updated. So, there is no more need for me to FTP or copy files to my development server. One more thing, if my desktop is turned on at home, any changes I make away from home, are reflected on my development server instantaneously.

To change Apache’s web root, edit the /etc/apache2/sites-available/default config file. Change the default directory from /var/www to /home/ulysses/Dropbox/web/, the location of my Dropbox folder.

DocumentRoot /home/ulysses/Dropbox/web
<Directory />
 Options FollowSymLinks
 AllowOverride None
</Directory>
<Directory /home/ulysses/Dropbox/web/>
 Options Indexes FollowSymLinks Multiviews
 AllowOverride All
 Order allow,deny
 allow from all
</Directory>

Do the same for the /etc/apache2/sites-enabled/default config file.

Finally, restart Apache.

$ sudo /etc/init.d/apache2 restart

Validate Empty Fields

Here’s a simple way to validate forms with empty fields. When working with forms, we want users to submit required fields. We can easily check by using the PHP empty() function. In this example, I will use a simple form, and check if “username” is empty. Since the action for the form is blank, the form will submit to itself. The the code you see for “value” is a shorthand PHP code to echo the field entry after a submit.

<form name="" method="post" action="">
<input type="text" name="username" value=<?=$username;?> />
<input type="submit" name="submit" value="Submit" />
</form>

Here’s the PHP code. First, we need to check if the form was submitted. We do this by checking $_POST[‘submit’]. Next, we will check if “username” is empty by using the empty() PHP function. If it’s empty, then we assign an error message to $errors. Finally, we will check if $errors is empty. If it is, then we can proceed with whatever we want to do. Otherwise, we echo the error messages.

$errors = array();
if (isset($_POST['submit'])) :
 $username = $_POST['username'];
 if (empty($username)) $errors[] = "Empty username.";
 if (empty($errors)) : 
  // do something special here, like saving to a database.
 else:
  // otherwise print the error messages.
  foreach ($errors as $msg) :
   echo "$msg<br>\n";
  endforeach;
 endif;
endif;

And one more thing. Place this PHP code above your form. The reason for this is, we want to redisplay the form just below the error messages. Users will be able to see the error messages right away, and the form is right there in front of the user ready for editing again.

Validate Email Address

I was working with PHP forms the other day which contained an email address. Validating email addresses is important. Occasionally, email addresses are used for activating accounts or resetting passwords. We can’t always guarantee that the email address provided is going to be valid, but at least, we can validate it’s going to be in the correct format. For pattern matching, I’m using a regex I found online. I like it because it’s very strict. I’m using the regex pattern with the preg_match function to determine a valid email address.

function check_email($email) {
 $pattern = "/^([a-zA-Z0-9])+([a-zA-Z0-9\._+-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/";
 if (!preg_match($pattern, stripslashes(trim($email)))) :
  return false;
 else :
  return true;
 endif;
}

To use the function, we can do this.

$email = "name@domain.com";
 
echo $message = (check_email($email) ? "Valid." : "Wrong format.");

In this example above, I’m using a ternary operator to display the result. It echoes out “Valid” because the email address we provided is in a valid format. You can use the regular “if else” conditional, if you prefer, instead of the ternary operator. By the way, I set $email variable manually. It this was an actual application, the email address cloud have come from a form.