Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Wednesday, January 7, 2015

Tutorials: How to Work With Arrays in PHP

What is an array? Arrays are common to almost every programming language. An array is simply an ordered map of values, indexed so you can find these values, called elements. These elements can be of multiple datatypes, and can be ordered any way you want.
Array ( [a] => 1 [b] => 2 [c] => 3 )
Two types of arrays in PHP There are two types of arrays in PHP, associative and enumerative. The difference between the two is how they are indexed.
Associative arrays allow you to index each element with an arbitrary value. For example, you can use letters of the alphabet, or just about anything to index the value, as long as it’s unique. Here is an example:
Array ( [name] => Jeremy [website] => jeremymorgan.com [occupation] => developer ) `
Some programmers prefer associative arrays because they can use the key to indicate what type of data is stored in the element, like “name” in the above example. This is an indicator of what is stored, however its not a rule that’s enforced. You can just as easily put a phone number in a name field and vice versa.
Enumerative arrays are indexed with a numerical index, either auto incremented, or random. PHP is very flexible with arrays, you can use numbers at will, and add in associative elements, and return to enumerative again. Also, the keys do not need to be sequential. Also note if you leave a key blank, an auto incremented number will be assigned to the key. Here is an example of an enumerative array:
Array ( [0] => Jeremy [1] => jeremymorgan.com [2] => developer )`
How to build an array in PHP
Using the array function you can create arrays a few different ways:
$ourary = array (1,2,3); $ourary = array (‘a’ => ‘1’, ‘b’ => ‘2’, ‘c’ => ‘3’); $ourary = array ();`
What do we do with arrays?
There are a few neat things we can do with arrays. You can extract only specific parts of an array:
$name = $ourary['name'];
or you can loop through an array:
$ourary = array(0 => 'Jeremy', 1 => 'jeremymorgan.com', 2 => 'developer');
foreach ($ourary as $value) {
echo “Value: $value”;
}
There are many things arrays can be really handy for, and I’ll cover that in future articles.
Checking your arrays
One question you might have is, how to easily check the data in the array. There are two easy ways to do this.
print_r($yourary);
This will display the contents of your array so you can visually verify the data before processing it. Print_r will recursively print the values of your elements. Here is another way:
var_dump($yourary);
This also prints out the values of your elements, but displays the datatypes as well. Whether or not you need this functionality will determine whether you use print_r or var_dump.
Conclusion
Arrays are a beautiful thing. Mastering them is key to success in any language. In future articles I will cover some of the things you can do with arrays.

Linux Tutorial: How to Build Apache, PHP5 and MySQL From Source

I’m going to show you how to do it the hard way, building everything from source, the way Linus intended. Let’s get started.

Step 1: Determine if it’s right for you.

This is not the only way to get a LAMP server going and not always the best way. You can get these files from your package manager in your favorite distribution or use something like XAMPP like I mentioned in previous articles. For most developers this a perfectly acceptable way to do it, and likely a better use of your time. Here are the reasons you would want to build from source:
You should only build from source if:
  • You have a good idea of what you’re doing.
  • You have time and patience.
  • You want the latest and greatest stuff and your package manager doesn’t have it yet.
  • You want to do something really custom and need to change crucial options.
  • You want full control over the installation details.
  • You need the maximum performance and stability possible.
  • You want to learn something.
If those don’t apply to you, then head over to this site and get XAMPP, it’s an awesome project.

Step 2: Get Sources.

Here is all the stuff you’re going to need. I put asterisks next to the “maybe” stuff that you might not need depending on how updated your system is.
Apache:
PHP:
MySQL:
Cmake: *
Mcrypt: *
APR:
PCRE:
Additional reading about setting up an Apache server can be found here:
Verify your files!
Make sure and download the .asc file also and do a quick checksum on it. This extra few seconds is well worth the benefit. Here is how you do it with Apache:
You should verify all your files before building, just to make sure you didn’t get a corrupt file.
Notes before you start:
You will see version numbers here, and those numbers are for the latest version of the software available when I wrote this. By the time you read this, they will have changed. If you want you can get these exact version numbers and build them exactly as in the article, but usually the newest version of the software is best.
I use “nice -20” before running make to ensure it gets priority. You don’t have to do this, and usually its not even required as most kernels will prioritize it pretty well.
You do not have to be root to build this stuff, in fact you shouldn’t be. You only need root privileges to install the software but you can build it with a regular user.

Step 3: Start Building

Install cmake:
./configure –prefix=/usr –mandir=/usr/share/man gmake
Install MySql:
groupadd mysql useradd -g mysql mysql
tar zxvf mysql-5.5.24.tar.gz (file name will differ)
cd mysql-5.5.24 ./configure –prefix=/usr/local/mysql make make install cd /usr/local/mysql chown -R mysql . chgrp -R mysql . scripts/mysql_install_db –user=mysql chown -R root . chown -R mysql var cp support-files/my-medium.cnf /etc/my.cnf
bin/mysqld_safe –user=mysql &
This will install your MySQL server. If you have issues getting it working, consult this page and follow those instructions.
Install Mcrypt
bunzip2 libmcrypt-2.5.8.tar.bz2 tar xvf libmcrypt-2.5.8.tar cd libmcrypt-2.5.8 ./configure –prefix=/usr –mandir=/usr/share/man nice -20 make make install
Install APR
tar xvzf apr-1.4.6.tar.gz /usr/src/http-2.4.2/srclib cd apr-1.4.6 ./configure nice -20 make
APR Utils:
tar xvzf apr-util-0.9.19.tar.gz ./buildconf –with-apr=/usr/src/apr-1.4.6/ ./configure
Install PCRE
tar xvzf pcre-8.30.tar.gz ./configure nice -20 make make install
Install Apache
cd httpd-2.4.2 CFLAGS=”-O2” ./buildconf –with-apr-util=/usr/src/httpd-2.4.2/srclib/apr-util-1.4.1 –with-apr=/usr/src/httpd-2.4.2/srclib/apr-1.4.6/ –enable-so –prefix=/usr/local/apache2 CFLAGS=”-O2” ./configure nice -20 make make install
Install PHP
We are going to install PHP 5.4.3 which was the most current at the time of this writing.
tar -xvzf php-5.4.3.tar.gz cd php-5.4.3
Note: The configure paramaters are where you really customize your installation. The following is the one I used for my machine, but your needs may be different. I will show you two of them and if mine doesn’t work, you can use a failsafe one.
My config:
./configure –with-apxs2=/usr/local/apache2/bin/apxs –with-mysql –with-curl=/usr/bin/curl –enable-bcmath –enable-calendar –with-curl=/usr/bin/curl –with-gdbm –enable-exif –enable-ftp –with-gd –with-freetype-dir=/usr –with-jpeg-dir=/usr –with-png-dir=/usr/bin/libpng-config –enable-gd-native-ttf –with-gettext –with-mcrypt=/usr/bin/libmcrypt-config –with-mhash –with-mysql=/usr/local/mysql/ –with-mysqli=/usr/bin/mysql_config –with-openssl –with-pdo-mysql=/usr –enable-soap –enable-wddx –with-xsl –with-zlib –enable-mbstring –enable-zip
Failsafe:
./configure –with-apxs2=/usr/local/apache2/bin/apxs –with-mysql
Make sure and get what you really need, but remember you can always recompile later. Now copy over a PHP.ini
cp php.ini-development /usr/local/apache2/php/php.ini
NOTE: Here’s an error you might run into:
configure: error: Cannot find MySQL header files under /usr. Note that the MySQL client library is not bundled anymore!
If you do install the mysql client libraries:
git clone git://github.com/Sannis/node-mysql-libmysqlclient.git cd node-mysql-libmysqlclient nice -20 make make test make clean sudo make install
After it’s built you’ll need to do a couple things:
vi /usr/local/apache2/conf/httpd.conf
Make sure this is here:
LoadModule php5_module modules/libphp5.so
And add this to the file also:
SetHandler application/x-httpd-php
Then restart Apache:
/usr/local/bin/apache2/apachectl restart
This will give you a nice running system! You will run into problems along the way, nothing that should be a showstopper. Good luck and if you have any questions, feel free to comment!

Tutorial: How to Create an Ajax Drop Down Menu With PHP and MySQL

There’s no doubt by now you’ve heard of Ajax, it’s far from a new thing. We went from hating JavaScript in the late 90s / early 2000s to now having arguably more development in JavaScript than any other language on the web. Simply put: we found a way to turn a gimmicky technology into something useful with Ajax.
Today I’m going to show you how a basic dropdown list works with Ajax. This is mostly geared towards beginners to show you the basics of how it works. When you get serious about development you’ll likely be using some kind of library like jQuery anyway. But here’s how you can roll your own Ajax dropdown.
Note: This is for academic purposes only. Please do not use this code in a production site. This is not very secure or robust code it’s just to teach you the basics. This will be a website to show shopping lists for sesame street muppets.

Step 1: Create your MySQL tables.

SQL to create the tables for this tutorial.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
CREATE TABLE IF NOT EXISTS `customer` (
  `idcustomer` int(11) NOT NULL AUTO_INCREMENT,
  `customername` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`idcustomer`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;


INSERT INTO `customer` (`idcustomer`, `customername`) VALUES
(1, 'Cookie Monster'),
(2, 'Guy Smiley'),
(3, 'Big Bird'),
(4, 'Oscar Grouch'),
(5, 'Alastair Cookie');


CREATE TABLE IF NOT EXISTS `item` (
  `iditem` int(11) NOT NULL AUTO_INCREMENT,
  `customerfk` int(11) DEFAULT NULL,
  `itemname` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`iditem`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=18 ;


INSERT INTO `item` (`iditem`, `customerfk`, `itemname`) VALUES
(1, 1, 'Milk'),
(2, 1, 'Cookies'),
(3, 1, 'Napkins'),
(4, 2, 'Toothpaste'),
(5, 2, 'Hair Gel'),
(6, 2, 'Razors'),
(7, 2, 'Tooth Whitener'),
(8, 2, 'Comb'),
(9, 3, 'Seeds'),
(10, 3, 'Bread'),
(11, 3, 'Snuffalupagus Treats'),
(12, 4, 'Febreeze'),
(13, 4, 'Earplugs'),
(14, 4, 'St Johns Wort'),
(15, 5, 'Cookies'),
(16, 5, 'Milk'),
(17, 5, 'Eyeglass cleaner');
This of course gives us two basic tables that show a list of names, and a list of items. They’re joined by idcustomer matching up to customerfk. Let’s first create our page, titled shoppinglist.php and put in some code to connect to the database.
We’re just going to use mysql_connect with zero error checking for simplicity. If this were a real app I would use PDO with prepared statements and error checking. But this is just an exercise.

Step 2: Create Your Webpage

Initial php file
1
2
3
4
5
6
7
8
<?php

// shoppinglist.php - a Demo by Jeremy Morgan

$link = mysql_connect('localhost', 'root', 'password');
mysql_select_db('test', $link);

?>
Replace the connection items with your own of course. And the first thing we’ll do is put a database driven dropdown in the file:
database driven select
1
2
3
4
5
6
7
8
9
10
11
$sql = "select * from customer";

$result = mysql_query($sql);

echo "<select name=\"muppetname\" onchange=\"changeContent(this.value)\">";

while ($ary = mysql_fetch_array($result)){
  echo "<option value=\"" . $ary['idcustomer']  . "\">" . $ary ['customername']  . "</option>";
}

echo "</select>";
It’s pretty easy to see what this does right? It simply pulls a result from the database and uses the mysql_fetch_array() function to fetch the data into an array. This outputs the “option” part of the dropdown using the idcustomer element as an id value and the customername is the displayed value.
Now we need to create a div below that:
content div
1
2
3
4
?>
<h2>Shopping list:</h2>
<div id="content">(Empty)</div>
<?php
It’s pretty simple to see what we’re doing here. We escape out of php to create a div with the id of “content”. This is where our shopping list will go.

Step 3: Create the JavaScript

This step is where we’ll create the actual JavaScript that’s going to interact with the dropdown. Here’s the script you’ll want to add to the top of your page:
JavaScript to communicate with getlist.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<script type="text/javascript">
function changeContent(str)
{
if (str=="")
  {
  // if blank, we'll set our innerHTML to be blank.
  document.getElementById("content").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {    // code for IE7+, Firefox, Chrome, Opera, Safari
      // create a new XML http Request that will go to our generator webpage.
      xmlhttp=new XMLHttpRequest();
  }
else
  {    // code for IE6, IE5
      // create an activeX object
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  // on state change
  xmlhttp.onreadystatechange=function()
  {
  // if we get a good response from the webpage, display the output
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
  {
      document.getElementById("content").innerHTML=xmlhttp.responseText;
    }
  }
 // use our XML HTTP Request object to send a get to our content php. 
xmlhttp.open("GET","getlist.php?idcustomer="+str, true);
xmlhttp.send();
}
</script>
I tried to explain what’s going on with this script in the file. Basically what you need to know is:
  • An event (dropdownmenu changes) triggers and calls the changeContent() function
  • Event passes a string to that function (the customer id)
  • Checks to see if string passed is blank
  • Create a new XMLHttpRequest
  • When readystate changes we send a request to getlist.php
  • If it returns back successfully we populate the div with id of content.

Step 4: Create the response php file

So now, it looks like the only thing missing is the getlist.php. This file simply needs to take an id and return a list. It is very black box and only serves this purpose, and the data will be populated on the page. Here’s what it will look like;
Initial php file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php

// getlist.php - a Demo by Jeremy Morgan

$link = mysql_connect('localhost', 'root', 'password');
mysql_select_db('test', $link);

$sql = "SELECT itemname FROM item WHERE customerfk=" . $_REQUEST['idcustomer'];

$result = mysql_query($sql);

echo "<ul>";

while ($ary = mysql_fetch_array($result)){
  echo "<li>" . $ary['itemname'] . "</li>";
}

echo "</ul>";

?>
Again this file is pretty self explanatory, you send it a customer id and it sends you back the list for the customer. Now that every thing is combined, your page should be functional. Load up shoppinglist.php in a web browser.
To be sure, this is what your final shoppinglist.php should look like:

The final shoppinglist.php file

Final shoppinglist.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<script type="text/javascript">
function changeContent(str)
{
if (str=="")
  {
  // if blank, we'll set our innerHTML to be blank.
  document.getElementById("content").innerHTML="";
  return;
  } 
if (window.XMLHttpRequest)
  {   // code for IE7+, Firefox, Chrome, Opera, Safari
      // create a new XML http Request that will go to our generator webpage.
      xmlhttp=new XMLHttpRequest();
  }
else
  {   // code for IE6, IE5
      // create an activeX object
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  // on state change
  xmlhttp.onreadystatechange=function()
  {
  // if we get a good response from the webpage, display the output
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
  {
      document.getElementById("content").innerHTML=xmlhttp.responseText;
    }
  }
 // use our XML HTTP Request object to send a get to our content php. 
xmlhttp.open("GET","getlist.php?idcustomer="+str, true);
xmlhttp.send();
}
</script>
<?php

// shoppinglist.php - a Demo by Jeremy Morgan

$link = mysql_connect('localhost', 'root', 'password');
mysql_select_db('test', $link);

$sql = "select * from customer";

$result = mysql_query($sql);

echo "<select name=\"muppetname\" onchange=\"changeContent(this.value)\">";

while ($ary = mysql_fetch_array($result)){

  echo "<option value=\"" . $ary['idcustomer']  . "\">" . $ary ['customername']  . "</option>";
}

echo "</select>";


?>
<h2>Shopping list:</h2>
<div id="content">(Empty)</div>
<?php


mysql_close($link);

?>
Run the file and start changing the name in the dropdown menu. As it changes, so does the list! Congratulations you’ve built your first PHP Ajax page!
It should look something like this.

Conclusion

I hope this helps you understand how Ajax works a little better. As your skills advance there’s no doubt you’ll use some sort of library to perform functions like this, but it’s good to know how it actually works behind the scenes.
If you’d like you can grab the source for this on Github. If you want to use it for your own tutorials or courses go for it!
I hope this tutorial has helped you and if you have any questions, feel free to contact me about it or leave a comment below.
Good Luck!