|
Connecting to MySQL
So you have your shiny new MySQL database your web host has given you and you
are already to begin your PHP scripting. If not then you can get an account with
all this from www.tripod.lycos.co.uk.
Or you could when I wrote this anyway.
For those of you used to connecting to Microsoft Access Databases, like I am,
the difference here is that rather than the database being a normal file like
a word document or a music file which can be easily opened, etc, MySQL databases
are stored on the server. So rather than connecting to a file you connect to
the server.
First I am going to jump straight in to the code and then explain it:
<%php
$db = mysql_connect("localhost", "username", "password");
mysql_select_db("database",$db);
%>
That is a basic connection. Ignoring the php open and close tags, the second
link in the code makes the connection to the database of your choose. In this
case it connects to a database simply called "database" so change
this to your database name.
The top line tells the script where the database is. In most cases you can
leave this as "localhost" as most hosts keep this as standard. If
you get told your MySQL host is different though replace localhost with the
new address your web host gives you.
Once you have established a connection you can then enter SQL underneath:
<%php
$db = mysql_connect("localhost", "username", "password");
mysql_select_db("database",$db);
$sql="SELECT * FROM members WHERE posts > 10";
%>
In 5 lines you have connected to a database and even selected a record set
from it. That is pretty simple I recon.
|