Home     Wordpress     Codex

Posts Tagged ‘Learning PHP’

Learning PHP (6) – Connecting to a database

June 16th, 2009 by admin | 4 Comments | Filed in Learning PHP

Everyone needs to store and get data from a database every now and then. MySQL can be an excellent choice for some.

Creating a table
This is how you create a simple table from the CLI, you can recognize the values if you use systems like phpmyadmin for modifying database structures.

mysql> CREATE TABLE mytable (
-> id INT NOT NULL AUTO_INCREMENT,
-> name VARCHAR(255) NOT NULL,
-> PRIMARY KEY(id)
-> );
Query OK, 0 rows affected (0.02 sec)

The MySQL reserved are upper cased, all the text in lower case are things
that you can change. This basically creates a table named ‘mytable’ with
two columns; “id” and “name”, id is an INT(eger) and name is a varchar of
max 255 characters.

AUTO_INCREMENT means that id will be automatically incremented if not defined.

Connecting to MySQL from PHP
Disclaimer: This is a very basic example, if you are coding for production use please at least look at the function mysql_real_escape_string() or a library
that will handle insertion and such.

The example above inserts a record in MySQL, the id will be automatically set to 1 (for the first row you insert, 2 for the next, etc.). To read this record out from the database again you can do something like this:


Warning:  mysql_connect() [function.mysql-connect]: Unknown MySQL server host 'mysqlhost' (1) in /home/espen/virtualhosts/www.cfg.no/htdocs/wp-content/plugins/exec-php/includes/runtime.php(42) : eval()'d code on line 26

Warning:  mysql_select_db(): supplied argument is not a valid MySQL-Link resource in /home/espen/virtualhosts/www.cfg.no/htdocs/wp-content/plugins/exec-php/includes/runtime.php(42) : eval()'d code on line 27
Data from MySQL
Warning:  mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/espen/virtualhosts/www.cfg.no/htdocs/wp-content/plugins/exec-php/includes/runtime.php(42) : eval()'d code on line 31

This piece of code will perform a “SELECT * FROM mytable” query (the * means every column from the table, you could get only the name by doing “SELECT name FROM mytable“.
Since there can be multiple rows we perform a while loop, so while $row gets fed with data from the mysql_fetch_assoc() function it will print the ‘id’ and ‘name’ columns from the table.

Select specific row(s) only (match on name)


Warning:  mysql_connect() [function.mysql-connect]: Unknown MySQL server host 'mysqlhost' (1) in /home/espen/virtualhosts/www.cfg.no/htdocs/wp-content/plugins/exec-php/includes/runtime.php(42) : eval()'d code on line 43

Warning:  mysql_select_db(): supplied argument is not a valid MySQL-Link resource in /home/espen/virtualhosts/www.cfg.no/htdocs/wp-content/plugins/exec-php/includes/runtime.php(42) : eval()'d code on line 44
Data from MySQL
Warning:  mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/espen/virtualhosts/www.cfg.no/htdocs/wp-content/plugins/exec-php/includes/runtime.php(42) : eval()'d code on line 48

Now we used the LIKE keyword in MySQL, the percent (%) sign is a wildcard.
This will get every row from the table where name begins with an E.

Homework: Now try to combine $_GET and $_POST + MySQL. :)

Tags: ,

Learning PHP (5) – Using built-in functions

June 12th, 2009 by admin | No Comments | Filed in Learning PHP

I had promised myself that I would post every second day, but I didn’t know exactly where to go from what we have built up and I also became engaged, she said yes! So it has been crazy days.
But I’m happy, at least :-D

I am going to continue with showing how to take use of some of the built-in string fuctions. These can be used to manipulate text variables that you might receive from the $_GET and $_POST variables.

Find occurrence of text in strings
You can for example use the function strstr() or stristr() if you want a cast-insensitive matching style.

Example

$mystring = 'this websites owner is nice';
if (strstr($mystring, 'website')) {
 echo 'I found the word "website" in the string.';
}

I can use double quotes in the string because I have it enclosed in single quotes.
If I were to use single quotes it would unquote the string and generate a syntax error.

If you replace strstr with stristr in the example, it would
also give a match if $mystring contains the word ‘Website’ with an upper case W.

explode() strings
If you get a string such as “one,two,three,four,five,six” and you would rather have
it indexed in an array you can use the function explode() to achieve this.

The build-in function explode() will parse a string and split it based on the
argument you give the function. An example will follow:

$mystring = "one,two,three,four;five,six,seven";
$myarray = explode(",", $mystring);

var_dump($myarray);

The first argument to explode is the delimiting character, while the other
is the string that will be split into an array. The result of this would be:

array(6) {
[0]=>
string(3) “one”
[1]=>
string(3) “two”
[2]=>
string(5) “three”
[3]=>
string(9) “four;five”
[4]=>
string(3) “six”
[5]=>
string(5) “seven”
}

Notice that $myarray[3] contains four;five, this is due to a common
mistake.. it can be hard to overlook, so can you figure out why it does that? :-D

Anyways, you should check out the documentation and try out some
of the functions, because they are really easy to use and implement.

Good luck!

Tags: , , , , , , , ,

Learning PHP Part Four – If and else

May 30th, 2009 by admin | No Comments | Filed in Learning PHP

Have you been playing around with the GET and POST arrays now?
If not, learn about foreach in PHP here.

What can I do now?
You can go ahead and use if to check the contents of variables.
Check this out.

If
The syntax for if goes like this:

if (statement) {
  Insert your code here
}

The statement will be checked, and if it is true the code within the { and } will be executed.
Take for example a script where you get a variable from the url, take the previous
example where you used $_GET['name'] to retrieve the ?name= part of the URL.

Now, if your name is John and you want the page to say hello to you but not to anyone else.


The $_GET['name'] == ‘John’ part is called the statement,
you probably understand it but it checks to see if the $_GET array variable
with the key ‘name’ contains a string ‘John’.

You can do similar tests with numbers, but then you won’t need the quotes
like the ones I have around ‘John’.

The example will then be:


Let us say you want to check if the name is NOT John.

You're not my master.

Else
Now, take the example where you output ‘Hi master’, what if you want
to print something to the ones not being the master? You can use else

You're not my master

That’s all for today, I don’t have so much time today so I am going to keep it quite short.
I will get back with a new article in these series in a couple of days, hope I’ll see you back here then!

Tags: , , ,

Learning PHP (3); Reserved vars and loops

May 28th, 2009 by admin | 1 Comment | Filed in Learning PHP

In my previous article I explained arrays and their use. But have you ever wondered what happens to those variables set in the url? They are contained within an array which is prefilled for your scripts.

The array variables $_GET, $_POST and $_SERVER are some of the interesting ones you can use.

The reserved $_GET variable
An example would be this type of URL.
http://www.example.domain/myphpscript.php?name=Espen

To catch the variable ‘name’ you can do this piece of PHP

<?php
echo “Hi ” . $_GET['name'];
?>

This will output “Hi Espen”.

Using the reserved $_POST variable
To get the variables from a form you can use $_POST['key'].
Look at this example:

Create this HTML form, change the path to myhelloscript.php to a place where you test your scripts.

<form action=”http://my.domain/myhelloscript.php” method=”post”>
<input type=”text” name=”name”>
<input type=”submit” value=”send it”>
</form>

Then create the file myhelloscript.php with the following contents

<?php
echo “hi ” . $_POST['name'];
?>

You see? The same result here, only now we’re using POST instead of GET (you can also notice that the URL does not contain the variables).

Looping over an array
Looping over an array can be very usefull in the case where you don’t know what the reference keys are.
Let us say you didn’t know that the key for the name in the previous post example was not called  ‘name’, how would you find it?

Here is an example of looping over an array, looping through all the key and value pairs.

<?php
$myarray = array(‘Espen’, ‘John’, ‘Lisa’, ‘Mark’);

foreach ($myarray as $value) {
echo $value . “<br>”;
}
?>

Now we’re saying for each ‘entry’ in $myarray get the entry as $value and do something with it between the { and }
So for each $myarray as $value: echo $value and a ‘<br>’ (to get a newline).

This example will output

Espen
John
Lisa
Mark

Getting the key
But that’s not the key, is it?  How do you find the keys?
This example will use the foreach command in another way to get the keys also

<?php
foreach ($myarray as $key => $value) {
echo $key . ‘ is ‘ . $value . ‘<br>’;
}
?>

Now you can also use the variable $key within the loop for each value to get the corresponding key.

This is an example of looping over the $_GET array

<?php
foreach ($_GET as $key => $value) {
echo $key . ‘ is set to ‘ . $value . ‘<br>’;
}
?>

A Challenge
The $_SERVER variable contains a lot of variables about the request, can you figure out how to show them all?

If you get any weird syntax errors or such, post them as a comment and I will try to help you out!

Tags: , , , , ,