MySQL & php, some things. Feel free to add more

Had your computer crash on you, or a website shows wrong, or your printer went dead on you? Come on in...

Moderator: Crew

User avatar
Maz
Admin emeritus
Posts: 1938
Joined: Thu Mar 16, 2006 21:11
Location: In the deepest ShadowS

MySQL & php, some things. Feel free to add more

Post by Maz »

First things first:

php is a programming language. It is mainly used to create dynamic www pages. Some features to mention:
php sourcecode is not visible for end user, when user connects to server with his browser, and browser sends server a request to display somefile.php, server 'filters' the .php file through php interpreter which reads the php code, and generates corresponding output.

For example code

Code: Select all

<?php
for($i=0;$i<10;$i++)
{
    echo 'Hello World <br>';
}
?>
would make php interpreter on server to simply give browser data

Hello World<br>Hello World<br>Hello World<br>Hello World<br>Hello World<br>Hello World<br>Hello World<br>Hello World<br>Hello World<br>Hello World<br>

If user tries to look at the sourcecode, he would see that.

And browser would display it's normal output as:

Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

(<br> is HTML code, and browsers interprete it as linefeed)


Now, MySQL is a database engine, which allows storing data in database. This means basically creating databases, consisting of tables which of course consist of rows and columns. Why databases are preferred over files, is that using plain text files are always a security risk. Or of course one can spend LOTS of time with creating secure datastoring system which is based on files, but well, that's what databases are. It's just that efficiency and security of databases have been developed for years, and I doubt no one want's really to spend years just to do their own databasesystem when they can use some already existing system... :rolleyes:
User avatar
Maz
Admin emeritus
Posts: 1938
Joined: Thu Mar 16, 2006 21:11
Location: In the deepest ShadowS

Post by Maz »

Now. When you have MySQL program installed, you notice that the system is based on different users. That's no surprize for one who has been using Unix/Linux, but for regular home computer user does not necessarily understand right away what's the point...

Ok. First, to access/create/delete a database, you need user who have RIGHTS to do that. Usually when one first installs MySQL, default 'superuser' with all rights (privileges) is created. Usually users username is root, and at this point the password is not specified.

Let's do a little check for username before going on...

Actually the default user's username is 'root'@'localhost'. That means that the user can only access from the host specified after the @ mark. In this case from the wery same computer.

Later you might want to create user(s) who can access to database from other computers too, by making them like 'foo'@'bar' or even 'foo'@'%'

First one can of course connect only from computer which hostname is bar, latter one from all possible hosts. I cannot actually remember anymore, but I think that before you can use 'foo'@'%' from all hosts, you need to also create user 'foo'@'localhost'. That was something related to how MySQL operates, but as I said, I'm not 100% sure anymore.

Now, some general princibles.

1. Give users only those rights they need. (IE, only access to specific databases, debending on your needs. Basically it's good idea to do 1 user / site, and 1 database / site.)
2. Do not grant privileges to add users or drop databases for users with hostmask % (unless really needed)
3. use non dictionary passwords, having some special marks in them.

Remember that nowadays the internet is no longer any nice & peacefull harbour, but more like the pub in Star Wars episode 4... Consider everybody as enemy, and if you can think of a way to break your code tms, someone else can surely do so too... Be paranoid.
User avatar
Maz
Admin emeritus
Posts: 1938
Joined: Thu Mar 16, 2006 21:11
Location: In the deepest ShadowS

Post by Maz »

Now, if we have database here, and php there, what's the point? Of course we want a way to deliver information from database to php scripts. Therefor we do have a bridge between php and MySQL. Back in good ol' times, this bridge came with php installation automatically. Nowadays it does not. (I think it was due to some licence thingee, not sure though). Anyways, the bridge exists, and it can be obtained free. Incredible imagination has been used when it has been named, and it's called php-mysql :rolleyes:

If you use some real operating system (Read, Linux with some good packagemanager), you can probably obtain it straight away with your favourite update agent. In other cases, try using our dear friend google to find rpm for linux or some other package for windows. (Or rather delete the windows fro your server, and install Linux instead :D )
User avatar
Maz
Admin emeritus
Posts: 1938
Joined: Thu Mar 16, 2006 21:11
Location: In the deepest ShadowS

Post by Maz »

Let's get to actual usage of mysql via php.

First you need to connect to mysql. It's done with mysql_connect() function.
Function returns a handle to the database (You have surely used files with C, or even php, right? Similairly open() function returns handle to file.)

mysql_connect takes hostname, username and password as parameters.

Now, the function to connect to the database could look like

Code: Select all

$con=mysql_connect('hostname','username','password');
Or if we add a simple errorchecking

Code: Select all

$con=mysql_connect('hostname','username','password') or die ('Error
while connecting to database: ' . mysql_error());
As you probably guessed, or die statement halts the processing of the script, and displays the message specified afterwards. mysql_error() function returns the last error occurred in mysql.

After connecting to the database software, we need to select the actual database we are using.

That's done with
mysql_select_db()
function. argument's to this function will be the name of the database we wish to use, and the connection handle. So that command could look like

Code: Select all

mysql_select_db ('cwf_data',$con) or die("couldn`t find the DB");
After this our database is ready to use. (assuming you did previous steps correctly, and your user had necessary privilegies)
User avatar
Maz
Admin emeritus
Posts: 1938
Joined: Thu Mar 16, 2006 21:11
Location: In the deepest ShadowS

Post by Maz »

After the connection to mysql engine is established, and database is selected, you can start performing operations to delete, add & retrieve data, and perform other tasks. The basic tasks can be done with
mysql_query()
function.
This function takes a SQL query as argument, which will be using the same syntax as native SQL queries, when MySQL is used straight from commandline without php.

Retrieving data:

The most used way to get data from database is to use SELECT statement.

It's syntax is

SELECT columnname FROM 'tablename'.

This returns kind of a pointer to a structure holding the information we asked for. Actually I am not sure if it's a real pointer, or just somekind of odd php thingy :D

Information can be retrieved for example by using the following functions:

mysql_fetch_array()
mysql_fetch_row()

mysql_fetch_array and mysql_fetch_row both take one row from selected data, and create an array out of it in following way.

mysql_fetch_row inserts the data in that line so that data in first column will be in array location 0, next column in location 1 and so on. When using mysql_fetch_array function, user can ask data to be stored in named array, so that instead of array[0], array[1]... there will be array['name_of_the_first_column'], array['name_of_the_second_colum']...

A typical example of that would be for example

Code: Select all

$sql="SELECT name_of_the_first_col, name_of_the_second_col FROM 'exampledatabase'";
$result=mysql_query($sql) or die('querying first & second col in exampletable failed because: ' . mysql_error());
while($row=mysql_fetch_row($result))
{
      echo 'first column in this row is ' . $row[0] .'<br>';
      echo 'second column in this row is ' . $row[0] . '<br>';
}
Or if using fetch array, it could be like:

Code: Select all

$sql=...
$result=mysql_query...
while($row=mysql_fetch_array($result, MYSQL_ASSOC))
{
      echo 'first column in this row is ' . $row['name_of_the_first_column'] .'<br>';
      echo 'second column in this row is ' . $row['name_of_the_second_column'] . '<br>';
}
You probably noticed that fetch array took one argument more than fetch row. That's true. with this argument you can specify whether you wish to have data stored in 'named' array, or in 'numeric' array. And as the example shows, MYSQL_ASSOC makes data to be stored in named array. Other possible arguments are MYSQL_NUM and MYSQL_BOTH. And as the names suggest, ASSOC_NUM stores data in numeric array, in fact, it's similair to fetch row then, and MYSQL_BOTH stores data in both arraytypes.

Default value here is MYSQL_BOTH. (IE, if that argument is not specified, it uses MYSQL_BOTH).

Sometimes you wish to get all fields (columns) from table. In that case you can write your SQL query as SELECT * FROM tablename. But this is HEAVY query if table is large, and it should be avoided. (Never retrieve more information than you need).

Now, usually it's not wanted to get all the data from the table. Let's take an example.

We have table of members of OG AA association, and their favourite drinks in a table as follows:

Code: Select all

        col1     col2     col3
        id     name   drink
line1   1      Bald   Guinness
line2   2      Maz    homebrew
line3   3      Pitk   Tea
Of course secent people do not remember anything tea related, so they wan't to get the pitk's favourite drink out of the table. Sure it would be possible to retrieve names and drinks, and check the names in for loop & find the drink corresbonding to the pitk's name with php... But php is not optimized for this kind of tasks, whereas the database engines are. So let's look how to let the MySQL to get the data...

For that we use new word in query. It's WHERE. Query would be as follows:

Code: Select all

$sql="SELECT drink FROM 'og_aa' WHERE 'name'='pitk'";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
    echo 'Ptkin\'s favourite drink is tar, although he claims it to be' . $row['drink'];
}
Other usefull keywords for getting data are

LIMIT number which tells the maximum amount of row's to be retrieved.
ORDER BY 'columname' DESC which sorts the results according to column 'columname' in ascending (default/use ASC) or descending order (DESC).

You can also use other comparation operators with WHERE clause. Those are
< (smaller than)
> (greater than)
<= (smaller or equal)
>= (greater or equal)
!= ('different from')

More will follow when I find time... :/
User avatar
Maz
Admin emeritus
Posts: 1938
Joined: Thu Mar 16, 2006 21:11
Location: In the deepest ShadowS

ADDING DATA IN TABLE

Post by Maz »

ADDING DATA IN TABLE[/b

Another important thing with databases is of course adding the data. We can again use the mysql_query() function to do that.

One possible form of SQL syntax is:

INSERT INTO tablename SET columname='new_value', anothercolumn='another new value' ...

now, if you insert numeric value in column, you should not use ' ' around the value (as far as I remember).

(
This is only one possible way, and this is not too often used. I have myself used to this, so I do not remember the syntax of that common query, which first contained columnames separated with commas, and then had values in same order. Something like

BLAA blaa BLA col1,col2,col3 VALUES( val1,val2,val3)
)

EDITING DATA IN TABLE

Of course editing data is important too. Now, we can replace some data in some column with following command:

UPDATE tablename SET column='value', col2='val2'

The abowe command would put value 'value' in column 'column' and value 'val2' in column 'col2' for EVERY ROW. Of course that's not usually what we want... For example if in drink table example we should for some reason change pitkin's favourite drink to tar and we used the abowe command, would Baldie be really irritated...

Well, don't worry mates. We can use WHERE and LIMIT statements here too, so we can safely do

UPDATE og_aa SET drink='tar' WHERE id=3 LIMIT 1

Although usage of limit is unnecessary here since all seem to have unique id, I do prefer using it just in case... (I am wise enough to be afraid of Bald's anger ;) )

Next... Well, when I have time, I might tell you something about creating a database and setting the column attributes...