How to speak to an API using PHP

I wanted to integrate Paypal to my site. Some would probably say that I should use a pre-built shopping cart – but I didn’t want to. I want to code everything from scratch as much as possible – this may seem stupid when there are lots of very well established frameworks which includes lots of pre-built stuff out there but I feel that to truly learn as much as possible as quickly as possible it will be more beneficial for me to do things the long way.

This approach is not without it’s hindrances. For example, I already know that I need to change some of my code so that it is more object oriented – this will me to re-use the code in the future. I also know that I have not kept to the model, view , controller framework very well – particularly the model side of things – so I need to undertake an exercise to move that model code out into it’s own place. I also need to make my code set more manageable by splitting up files. I also have a great deal to learn about security and will probably have a lot of re-work to make my site and it’s transactions secure. Having said all that I doubt that I would even having been thinking properly bought my own re-use or maintenance or security requirements if I had been using an existing framework which contained pre-built modules etc.

Anyway – what I was really going to talk about was talking to an API using PHP. Well, it’s so bloody simple it’s ridiculous. PHP uses a library called lib curl. This allows you to use cURL. I don’t want to rip of someone else’s work so take a look at how to use it at Brandon Beasleys Blog.

The only other thing I have to say on the matter is that to parse the response from the API you can use the most magical of PHP functions – in fact it might be the most magical function I have ever seen in any language – it saves writing your own function to parse API responses – that PHP function is parsestr(string encodedString). This means that if I get a response back from an API like TOKEN=EC%3FV7729610061Y&ACK=Success&VERSION=9uuIIHT&OTH=ple887, then I can use the magical statement to assign each API response value to a global variable. So if I use the cURL execute statement to set the response from the API to the variable $result as follows:

$result = curl_exec($apiArrayOfValues);

Then perform the magic:

parse_str($result);

I then have instant access to the information that was present in that string by calling them using a global variable which has magically been set for each value – the variable names are basically whatever word came before the equals sign in the API response – so in this case $TOKEN, $ACK, $VERSION and $OTH.

So if I execute

parse_str($result);

echo “THE TOKEN IS: ”.$TOKEN;

I get the result:

THE TOKEN IS: EC-3FV7729610061Y

(Not that the function also changes the % to – for us as well).

If I execute

echo $ACK;

I get the result:

Success

So all that work is done for me in one easy statement – brilliant!

Advertisements

Got a Resource id #5 appearing, don’t worry!

So I was echoing out my $query and my $result variables and I coded my site in order to check my SQL statements and I came across a value of ‘Resource id #5’ in my echo values where I instead expected to see a customerID.

The answer? Well,  you can’t echo the result of a sql query,   i.e you can’t do this:

$query = "SELECT CustomerID  FROM CUSTOMER WHERE emailAddress = '".$emailAddress."'";
$result=mysql_query($query);
echo $result;

instead you need to identify which item in $result you want to echo (and for which row). In my instance the item was CustomerID and  I thought it would be good to iterate through all the rows in the resultset, so I echoed it like this:

$query = "SELECT CustomerID  FROM CUSTOMER WHERE emailAddress = '".$emailAddress."'";
$result=mysql_query($query);

//Get the number of rows in the recordset
$num=mysql_numrows($result);

//Set the initial value of the counter to zero (the first position in the resultset)
$i=0;

//iterate through the resulset and echo the value of the CustomerID for each record
while ($i < $num) {
echo mysql_result($result,$i,"CustomerID");
$i++;
	}

It’s an easy mistake to make, but a bit thoughtless when you think about it..after all, how can we expect to echo a recordset? I don’t think I’ll be making that mistake again!!

How to post the values of set checkboxes back to the database – Stage 5 complete!

Much play has stopped work for a number of days, but tonight I picked up my laptop and went back to the problem that I had in passing the values of the checkboxes that the user had checked back to the database.

Why on earths name I thought I might need to use javascript I have no idea…too much internet reading of the wrong thing I think.

Anyway, here’s how I managed to solve the problem of presenting the list of items from the database with checkboxes and then updating the database with values of the checked checkboxes. The first part gets the items from the database and displays them on the page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Diplay data as checkboxes</title>
</head>

<body>

<?php
// Include connection to my local server
include("Connections/connectionData.php");
//Connect to the database - 
mysql_connect ($server, $username, $password, $dbName) or die ('Error: ' .mysql_error());
mysql_select_db($dbName);
//Create the query
$query="SELECT * FROM TableName WHERE columnName = 1";
//Define the variable that will hold the result set
$result=mysql_query($query);
//Find out how many records there are in the resultset
$num=mysql_numrows($result);
?>

<!-- Create the form - this will tell the page which php script to get when the form is submitted --->
<form action="process_changes.php" method="post">

<!-- go into php scripting to obtain each value individually from the resultset --->
<?php
//Set up the loop to loop thru the result set
$i=0;
while ($i < $num) {
	
//set the value from the current row of the resultset to the $field1 variable
$field1=mysql_result($result,$i,"myColumnName");
?>


<!-- Display the checkbox on the page containing the value from the current row of the resultset --->
  <input type="checkbox" name="items[]" value="<?php echo $field1;?>" /> <?php echo $field1;?><br />

<!-- break back into php to increment the variable - and therefore go to the next row of the resultset -->
<?php
	
	//increment the counter
	$i++;
}


?>

<!-- Place a submit button on the webpage, so that the checkbox values selected are passed when the button is clicked -->
  <input type="submit" value="Submit" />
</form>


</body>
</html>

The second part is the script process_changes.php (which is called from the previous script). This script gets the items array (which holds the list of checkbox values) from previous page and builds an SQL INSERT statement for each item. This may not be the way that you want to send your inserts to the database, but it gives you an idea anyway.

<?php

$checkBox = $_POST['items'];
for($i=0; $i<sizeof($checkBox); $i++){
    $query = "INSERT INTO table(TableToInsertInto) values('".$checkBox[$i]."')";
//	echo $query;
   mysql_query($query) or die(mysql_error());
}

?>

So Stage 5 is now complete – I now just need to collect some more data from my user and write some more update and insert queries and then I get to work on Stage 7, which is finding out how to send a verification e-mail to a user and then process it’s return. I expect that this will be pretty easy since it’s the corner stone of a lot of web actions. I’m more than 25% of the way through now.  It’s great to be doing something and not just thinking about it.

We have reference data and a page with dynamic content

My reference data table is now loaded and I have now managed to get the data from my database and out onto the lovely php page, I have dymamically generated content!

I think I can say that stage four is now complete.

Oh I found out today that sometimes, if you don’t restart your webserver after making code changes, the code hangs onto old values in some it’s variables, so now I’m doing a webserver restart after every major update to the code…I’m nots sure yet if this is normal, or if it’s just my code that’s bad…I need to do more reading a learn a bit more before I figure this out.

Where on my mac is my php.ini file?

I found the path to it by creating a .php script called phpinfo.php with the following code in it:

<?php

phpinfo()

?>

I then went to my browser navigated to the  http://127.0.0.1/useful/phpinfo.php and hey presto, the full current configuration was displayed in the browser including the php.ini path. (it was in /etc)

Warning: mysql_connect() [function.mysql-connect]: No such file or directory

I spent an age trying to work out why I couldn’t post a simple e-mail address to a PHP database. Everytime I tried to test submitting the form using my local server I got the following message:

Warning: mysql_connect() [function.mysql-connect]: No such file or directory

I was using the following connection string:

mysql_connect ("localhost",  "root", "xxxx", "my_fdb") or die ('Error: ' .mysql_error());

It turns out that when I changed “localhost” to the actual ip address and port of my local mySQL database, the error disapeared:

mysql_connect ("127.0.0.1:3306",  "root", "xxxx", "my_fdb") or die ('Error: ' .mysql_error());

Now if I was on a windows machine I would have known where to go to edit my locahosts file, but on a mac I haven’t the first clue and right now I don’t care, I’m just pleased that I’m now able to write to and read from my local database.

Which Development Environment?

I’ve been trying to find out which IDE I should use to start on my journey.

(Why does this wordpress do double line spacing?)

In my google search for IDE’s on a Mac I came across the blog of a guy called Sean Barton (http://www.sean-barton.co.uk/2009/02/setting-up-a-phpmysql-local-development-environment-on-a-mac-doing-it-properly/) and thought, that looks good, I’ll learn how to set up a php and mysql development environment on my mac. So, I followed his instructions and downloaded and installed mysql then configured apache to load the php module (I think this is the right terminology!).

The big question is, was it simple? The answer is, not as simple as I thought it would be. Below are the things that I learned along the way…they might be useful for another complete newbie.

Tip1: It’s the MySQL Community Server edition that you want to download ( I hope)

Tip 2: Make sure you use a mirror from the mysql site to get a .dmg file and not a .tar file.

Tip 3: To a copy a previous command in a Terminal window use crtl+P. For a full list of commands see this helpful bash cheat sheet

Tip 4:  How do you edit a file using vi? Answer: I”ve no idea – I used nano [to do this I substitued the word pico for the word vi when I executed this command ]

sudo vi /private/etc/apache2/httpd.conf

Tip 5: How to edit a file using nano? Answer : Wherever you see the ^ sign means hold the crtl key! – This site contains a neat crib sheet.

Tip 6: apachectl is not the same as apachrct1 – be careful of 1s and ls when looking at text which uses a terminal style font

Tip 7:  The command sudo /usr/sbin/apachectl restart doesn’t work. It errors with:

usr/sbin/apachectl:
line 82: ulimit: open files: cannot modify limit: Invalid argument

The guy at this deversus page explain a way around it, but to be honest I just ignored it and continued.

Anyway, after removing the index.html page from the /Library/WebServer/Documents folder and navigating to 127.0.0.1 in my browser and pressing refresh a few times,  I finally saw a page come up containing a question mark on it…so I guess my environment is now working!!

So, lots of new things learned today. Roll on tomorrow when I’ll be working out what I should do next!