RSS
 

Posts Tagged ‘php’

Using the database from inside a helper (CodeIgniter)

17 Jun

I have some custom functions that I store in a helper in CodeIgniter.

Some of those functions need to use the database, and to do so you have to explicitly tell the function to load the Code Igniter framework and database class.

Its pretty simple when you know how, but it took quite a while to work it out.

function get_user_full_name($userId) {
 
    //the database functions can not be called from within the helper
    //so we have to explicitly load the functions we need in to an object
    //that I will call ci. then we use that to access the regular stuff.
    $ci=& get_instance();
    $ci->load->database();
 
    //select the required fields from the database
    $ci->db->select('firstName, lastName');
 
    //tell the db class the criteria
    $ci->db->where('userId', $userId);
 
    //supply the table name and get the data
    $query = $ci->db->get('user');
 
    //ensure that there is something in the variable - in case of no match
    $fullName = "";
 
    foreach($query->result() as $row):
 
        //get the full name by concatinating the first and last names
        $fullName = $row->firstName . " " . $row->lastName;
 
    endforeach;
 
    // return the full name;
    return $fullName;
 
}
 

Using Eclipse as a PHP IDE in Ubuntu 9.10

25 Nov

This is actually much easier than any of the guides I found online make out.

Firstly, install Eclipse from the repositories. Then open it up, select your default workspace (if you havent already) and then:

  1. From the Help menu, select “Install new software”.
  2. Click the “Add” button and add the following:
      • Name: Eclipse Updates (Galileo)
      • Location: http://download.eclipse.org/releases/galileo/
      1. Apply your changes and wait for the contents to download.
      2. When all is ready, select your new source from the drop down and look for the “Programming languages” section.
      3. Open it up and add the “PHP Development Tools (PDT) SDK Feature”.
      4. Step through using Next and Finish etc, and after a few moments downloading and installing you now have a PHP ready IDE.
       

      Setting up a basic web server using Ubuntu 9.10 (Desktop)

      12 Nov

      Ubuntu LogoI have been using Ubuntu 9.10 for a while and wanted to see how it performs as a web server. The GUI interface is very slick and it is an ideal OS for beginners and advanced users alike. I suspect that many people will want to use it as the basis for their webservers.

      I suggest creating a virtual machine with something like VirtualBox for this. It is much more flexible that way, and you can move it to a more powerful machine if you decide you need to.

      Phase 1. Install required applications:

      1. Open ‘Synaptic package manager’ from the System/Administration menu.
      2. Click the ‘Search’ button.
      3. Enter ‘Apache’ and press return.
      4. You will see an item called ‘Apache2′ in the list of results. Click the box to the left to mark it as something you want to install.
      5. Repeat this process for:
        • Php5
        • MySql
        • Php5-mysql
      6. Click the ‘Apply’ button on the toolbar.
      7. This will start the installation process, during which you will be prompted to provide a password for the MySQL root account. Supply a strong password and make sure you do not forget it.
      8. It worked!When everything has finished installing, I suggest rebooting. There are ways of starting the servers without rebooting, but a reboot works just as well and is much easier.
      9. After you have logged back in to Ubuntu, open up Firefox and visit http://localhost.
      10. You should see a page that says “It works!” which means that your webserver is now working.

      Phase 2: Configure Virtual Hosts (So you can have more than one site on your server)

      I have chosen to use the command line to do much of this phase rather than the GUI. For me, it is much easier to access protected system files from the shell rather than use a GUI. However, should you want to use a GUI, you will need to be running with root privileges. You can do this by entering: sudo nautilus in to a command line (and enter your password). However, the instructions below are for using the shell.

      Any time you see the sudo command, that means that you will run the command as root (administrator). Linux is much more secure than Windows thanks to it being locked down by default with a standard set of permissions. It might seem like hassle to keep having to switch to be administrator but it makes things much safer. Deal with it!

      1. Open a new Terminal from Applications / Accessories in the menus.
      2. In the terminal, enter the following commands and review the results so you know what you are doing.
      3. cd /etc/apache2/sites-enabled (this moves you to the folder where you can define different websites)
      4. ls (lower case LS: this will show you a list of files)
      5. sudo cp 000-default 001-mysite (this will copy the default config file so you can use it as the basis for your new site)
      6. Enter your password when prompted (this should only happen once, but if you are prompted again – just re-enter it)
      7. sudo gedit 001-mysite (this will use the gedit text editor to open and allow you to edit the new site config file)
      8. Change the ServerAdmin row to use your email address. ie. ServerAdmin sam@mysite.net
      9. Add a row below with the tag: ServerName followed by the name of your site. I will continue to use mysite.local throughout. ie. ServerName mysite.local
      10. Edit the row DocumentRoot so that the new path is a sub-folder of www called 001-mysite. ie. /var/www/001-mysite
      11. Edit the row <Directory…> so that the new path is also used. ie. <Directory /var/www/001-mysite>
      12. Save the file and closed GEdit.
      13. A working PHP virtual hostWe now need to let your computer know that it IS mysite.local. The easiest way to do this is to edit your hosts file. There is plenty of information online about what this file does.
      14. From the terminal, type: sudo gedit /etc/hosts
      15. Add a new row below 127.0.0.1    localhost that reads: 127.0.0.1     mysite.local (spaces are tabs).
      16. Save the file and close GEdit.
      17. Now we need to create the file structure for where the sites files will live.
      18. Enter: sudo mkdir /var/www/001-mysite (this will create a new folder that will store your php/html files etc)
      19. cd /var/www/001-mysite
      20. sudo gedit index.php (this will open the text editor again and will allow you to create the index page for your site).
      21. In the text editor, enter the following bold text (including all the punctuation): <?php phpinfo(); ?>
      22. Save the file and close.
      23. sudo /etc/init.d/apache2 restart (this restarts the Apache service so that the new virtual host is available)
      24. Now open firefox and visit your new site: http://mysite.local
      25. You should see a whole load of information about your server, and more specifically about your PHP installation.
      26. Thats it! Repeat this phase to add as many virtual hosts as you like.

      You will now almost certainly want to secure your server. If you have got this far then you can at least get your site(s) up and running on your local machine. Ill cover securing your server in another post.

       

      Creating JSON data from MySQL in PHP

      24 Aug

      Here is a quick post that demonstrates how to create some neat JSON data from MySQL using PHP. The script is really simple, and has been working well for me over the last few weeks.

      If anything is confusing, it might be worth checking out the previous post about creating XML data from PHP. It explains things in more detail and will help if you are not familiar…

      //set up the php headers so that the page doesnt cache etc
      header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
      header("Last-Modified: " . gmdate( "D, d M Y H:i:s") . " GMT");
      header("Cache-Control: no-cache, must-revalidate");
      header("Pragma: no-cache");
      header("Content-type: text/json");
       
      $jsonArray->page = $page; 
      $jsonArray->total = $totalPages;
      $jsonArray->records = $recordCount; 
       
      $i=0; 
      while ($row = $db->fetch_array($countRows)) {
      	$jsonArray->rows[$i]['id']=$row['userAccountId']; 
      	$jsonArray->rows[$i]['userName']=$row['userName'];
      	$jsonArray->rows[$i]['fullName']=$row['fullName'];
      	$jsonArray->rows[$i]['accessCode']=$row['accessCode'];
      	$jsonArray->rows[$i]['email']=$row['email'];
      	$jsonArray->rows[$i]['addedBy']=$row['addedBy'];
      	$jsonArray->rows[$i]['addedDate']=$row['addedDate'];
      	$jsonArray->rows[$i]['modifiedBy']=$row['modifiedBy'];
      	$jsonArray->rows[$i]['modifiedDate']=$row['modifiedDate'];
      	$i++; 
      } 
       
      echo json_encode($jsonArray);

      The above code will create the following style JSON output.

      {"page":1,"total":1,"records":"3","rows":[
      {"id":"1","userName":"demo","fullName":"Demo User","accessCode":"","email":"demo@myexample.com","addedBy":"1","addedDate":"2009-05-02 00:00:00","modifiedBy":"10","modifiedDate":"2009-06-04 00:00:00"},
      {"id":"2","userName":"sam","fullName":"Sam Lasagne","accessCode":"","email":"sam@myexample.com","addedBy":"2","addedDate":"2009-05-02 00:00:00","modifiedBy":"2","modifiedDate":"2009-08-02 00:00:00"},
      {"id":"10","userName":"adrian","fullName":"Adrian Spaghetti","accessCode":"","email":"adrian@myexample.com","addedBy":"1","addedDate":"2009-05-02 00:00:00","modifiedBy":"2","modifiedDate":"2009-09-01 00:00:00"}
      ]}
       
       

      Using XML in your jQuery to populate input boxes

      11 Aug

      In a previous post I wrote about creating XML pages with MySQL data, using PHP. In this article, I’ll explain in simple terms how to parse that XML data and insert some of its values in to your page using jQuery.

      I’m going to keep this very simple, as there seem to be very few examples of this on the net. It took me a while to work out a neat way of doing this, and I’m sure someone can improve on things. If so – please let me know in the comments.

      First, lets set up an example. A very simple example.

      Imagine an invoice. 4 boxes at the top of a grid, with a ‘Save’ button that will add the contents of those boxes to the list below. The fields are such as ‘Item code’, ‘Description’, ‘Quantity’ and ‘Unit Price’. The user enters the values and clicks the ‘Save’ button to add that row to the list and clear the boxes, ready for the next row to be added. For the purposes of what we are doing, we will also want a 5th box (which would usually be hidden) to store the ‘Invoice Detail Id’.

      Something like this:

      Code Description Quantity Price Hidden ID

      Creating this application is all quite trivial for someone experienced in PHP. However, what would be nice is to be able to edit each row without having to re-load the page. Well we can do this quickly and easily using jQuery.

      Before we start with the jQuery code, we need to have ready a PHP page that will return valid XML with the details of an invoice detail record. Please see my previous post for some help on how to do this.

      This is an example output from the getDetailRow.php file.

      <?xml version="1.0" encoding="utf-8" ?>
      <invoice>
        <invoiceDetail>
          <invoiceDetailId>10</invoiceDetailId>
          <code>CR282</code>
          <description>Software Support</description>
          <quantity>3</quantity>
          <unitPrice>40</unitPrice>
       </invoiceDetail>
      <invoice>

      Against each row, add a button labeled ‘Edit’, and attach some jQuery code that calls a function called editDetailRow(detailRowId) – as the grid is built, insert this code in to each button with the parameter of that row’s detail ID.

      Assuming that there is only ever one result in the XML output, you could use the following code to insert the values in to your input boxes.

      <script type="text/javascript">
      function editDetailRow(detailId) {
          //first we need to load the XML data for that detail row
          //if the function is a success it will call the function called processDetail
          $.ajax({
             type: "GET",
             url: "getDetailRow.php?detailId=" + detailId,
             dataType: "xml",
             success: processDetail
           });
      }
       
      function processDetail(xml) {
          //this function gets the results from the xml file
          //and inserts them in to the boxes
          $(xml).find("invoiceDetail").each(function()   {
              $("#code").val($(this).find("code").text());
              $("#description").val($(this).find("description").text());
              $("#quantity").val($(this).find("quantity").text());
              $("#unitPrice").val($(this).find("unitPrice").text());
              $("#invoiceDetailId").val($(this).find("invoiceDetailId").text());
          });
      }
      </script>

      Yes, it really is that simple. You will need to add a reset button, and make sure you check for a value in the invoiceDetailId when you save (to either call an UPDATE or an INSERT) but thats it.

      Hopefully you will find this useful and can use this as the basis for much more complicated XML and jQuery hookup’s.

       

      Creating XML in PHP

      28 Jul

      Quite often I need to create some XML via PHP, pulling data from a MySQL database.

      I have tried various methods but I always come back to this. I like the way that I get full control over doing it explicitly, so thought I would share the code. I am using the MySQL PHP class from Ricocheting.

      There are loads of examples out there already on the web, but I hope the code below is very easy to understand as it uses simple PHP code.

      <?php
       
      //pick up required variables
      $userName = $_GET['username'];
      $password = $_GET['password'];
       
      //include the required files
      require_once('config.php');
      require_once("Database.class.php");
       
      // create the $db ojbect
      $db = new Database($config['server'], 
      	$config['user'], 
      	$config['pass'], 
      	$config['database'], 
      	$config['tablePrefix']);
       
      // connect to the server
      $db->connect();
       
      //build the query
      $query = "SELECT * FROM ".$db->pre."useraccount "; 
       
      //build the where statements
      $where = "WHERE (userAccountId > 0)";
       
      if ($userName) {
      	$where = " AND (userName = '" . $db->escape($userName). "')";
      }
       
      if ($password) {
      	$where = " AND (password = '" . $db->escape($password). "')";
      }
       
      //get the FULL record count
      $sql2 = "SELECT count(0) AS theCount FROM ".$db->pre."useraccount $where";
       
      $countRecRows = $db->query($sql2);
      while ($countRecRow = $db->fetch_array($countRecRows)) {
      	$recordCount = $countRecRow['theCount'];
      }
       
      //execute the main query
      $countRows = $db->query($query . $where);
       
      //set up the php headers so that the page doesnt cache etc
      header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
      header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . " GMT" );
      header("Cache-Control: no-cache, must-revalidate" );
      header("Pragma: no-cache" );
      header("Content-type: text/xml");
       
      //include the page header info
      echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
       
      //begin the xml data
      echo "<useraccounts>\n";
       
      //set up the result info
      echo  "<total>$recordCount</total>\n";
       
      //loop through all the records
      while ($row = $db->fetch_array($countRows)) { 
      	echo "<useraccount id=\"".$row['userAccountId'] ."\">\n";
       
      	echo "<username>";
      	echo $row['userName'];
      	echo "</username>\n";
       
      	echo "<fullname>";
      	echo $row['fullName'];
      	echo "</fullname>\n";
       
      	echo "<accesscode><![CDATA[";
      	echo $row['accessCode'];
      	echo "]]></accesscode>\n";
       
      	echo "</useraccount>\n";
      }
       
      echo "</useraccounts>";
       
      //free the result
      $db->close();
      ?>
       
       

      XML Output From PHP

      28 Jul

      Just a quick one. If you want to output XML from your PHP page you need to set the Headers correctly.

      Here is the code you need to include, and it has to be before anything else is printed.

      <?php
         header ("Content-Type:text/xml");
      ?>
       
       

      Installing Aptana on Ubuntu Linux 9.04

      26 Jul
      aptana

      Aptana Studio IDE

      UPDATE: With the latest version of Aptana 2 and Ubuntu 9.10 it seems you dont need to do this hack anymore. Try it without first of all, then if you get problems – apply the fixes as described.

      I have been using the Aptana IDE for PHP and Ajax development for a while now on my Windows system, and have decided that it is much better than the standard Eclipse, at least for me. I wanted to start using it on my Linux machine but encountered problems which prevented it from running.

      It took me a while to find out how to get it to work, but thanks to Google and some others who have had this problem before me, I now have a working Aptana Studio on my Ubuntu system.

      Here is how to get it working:

      1. Download and extract Aptana Studio for Linux (All in one) from here.
      2. Use Synaptic to install xulrunner (version 1.8).
      3. Use Synaptic to install a JRE.
      4. Create a text file (in your home folder etc) which we will use to set up the Aptana environment and execute the application. Call it startAptana.
      5. Paste the text from below in to the new text file, and be sure to change the bottom line so that it matches the path to your Aptana installation.
      6. Make the startAptana file executable.
      7. Double click the startAptana file to start using Aptana, or create menu icon that links to it.
      #!/bin/sh
      MOZILLA_FIVE_HOME=/usr/lib/xulrunner
      if [ $LD_LIBRARY_PATH ]; then
         LD_LIBRARY_PATH=$MOZILLA_FIVE_HOME:$LD_LIBRARY_PATH
      else
         LD_LIBRARY_PATH=$MOZILLA_FIVE_HOME
      fi
      export MOZILLA_FIVE_HOME LD_LIBRARY_PATH
      /home/sam/Apps/aptana/AptanaStudio