|
Excited that you have found php? Well get really excited now because I am going to show you how to create a connect and execute a query against a MySql database
First we need a text editor, you can find plenty by doing a search on google or clicking here for a shortcut to the search. Now that you have it installed you can begin developing our connection
Okay the first thing you need to do in any connection situation is establish a new connection. The code to do that looks like this:
$server = "localhost";
$username = "jimini";
$password = "cricket";
$dbHandle = mysql_connect($server,$username,$password)
or die("unable to conect to database server");
Now we have an open handle to the database. This handle will be used for all further operations. The next thing you have to do is select the database you want to use (command line equivelant of "USE DatabaseName".
mysql_select_db("yourDatabaseName")
or die ("Couldn't use Database");
Right now the cheese on on the sandwhich, time to start grilling!
The first thing we will do is a standard select from the table of your choice.
//after we have established the connections.
$query = "SELECT * FROM yourTableName";
$result = mysql_query($query,$dbHandle);
while($row = mysql_fetch_array($result)){
echo $row[0];
echo $row['rowName'];
}
Now the $dbHandle is an optional argument but I would recommend making it a habit to use it. Come the day you need to connect to multiple database you are going to have to pass the handle to the query function so it knows which database to query.
Now to show you how to execute a write query against the database.
$query = "INSERT INTO yourTableName VALUES('valueHere');
mysql_query($query, $dbHandle);
if(mysql_affected_rows($dbHandle) > 0){
echo "Successfully inserted data";
}else{
echo mysql_error();
}
Nice and easy huh? The delete and insert execution are just as simple:
//DELETE ALL ROWS
$query = "DELETE FROM yourTableName; //delete all records
mysql_query($query, $dbHandle);
if(mysql_affected_rows($dbHandle) > 0){
echo "Successfully deleted data";
}else{
echo mysql_error();
}
//UPDATE RECORD
$query = "UPDATE yourTableName
SET rowName = 'valueHere'"; //Update all records
mysql_query($query, $dbHandle);
if(mysql_affected_rows($dbHandle) > 0){
echo "Successfully updated data";
}else{
echo mysql_error();
}
Now before you going belting into this I would recommend that you do more research into the SQL language and best practises. If you would like a more object orientated design for your connection routines check out the Database Connection and Database Statement tutorials (you will require PHP 5 for these. If I get enough request about a PHP4 version I will port it
Happy querying!
|