OSempire
Go Back   OS Webmaster Community > Blogs > OS-Mark
Rate this Entry

PHP / MySQL Overview

Posted 10-30-2009 at 12:02 PM by OS-Mark
Updated 10-30-2009 at 12:46 PM by OS-Mark
in this short tutorial, I'll show you how to create a database, setup the fields, connect to it using PHP, insert data from an HTML form, and display all results to the screen.

not going to go into great detail and spend a lot of time explaining each little part of this... so if you have questions along the way do not hesitate to ask... but now, lets get right too it.

Before you do anything you need to create a MySQL database.

Login to Cpanel and create a new MYSQL database. We'll call it phonebook.

next create a MySQL user, and assign a password. I'll use dbuser as the username and 12345 as the password.

Next we need to grant all privileges for our newly created dbuser to work on the phonebook database we created.


As you may be aware, Cpanel prefixes all database names and usernames with the cpanel username. So our Database name is now: username_phonebook and username_dbuser

*note the username prefix will be your cpanel login username.

Alright, so now we're all setup. Lets write some PHP to connect to the database and try inserting, selecting, updating data.


First off, we need to connect. Localhost is used when PHP and MySQL are installed on the same server. Some hosts may provide a domain name or IP address to use here instead of localhost. So if localhost doesnt work for you, ask your host.
PHP Code:
<?php
mysql_connect
("localhost""username_dbuser""12345"
or die(
mysql_error());

// If the connection was a success, brag about it.
echo "woot! we are connected to MySQL<br />";
?>
now we have only connected to MySQL, we have not yet chosen a database to work on, so lets do that.

PHP Code:
<?php
mysql_connect
("localhost""username_dbuser""12345"
or die(
mysql_error());

// If the connection was a success, brag about it.
echo "woot! we are connected to MySQL<br />";

//Connect to a specific database
mysql_select_db("username_phonebook"
or die(
mysql_error());

echo 
"alright! connected to the phonebook database";

?>
So now when you save this file and check it out in your browser you should see the 2 successful messages. If you see a MySQL error that means you have made a small mistake somewhere. Dont worry, thats going to happen go over your code and make sure your username, database name and password is all correct.

before we can insert or select any data from the database we need to setup "tables" to hold our information. In this example we'll create a small phone book which will have 3 fields, ID, NAME, and PHONE. So lets go back to Cpanel and open phpmyadmin, once opened, click on your 'phonebook' link on the left hand side.

Near the center of your screen you'll see something like: Create new table on database phonebook

enter contacts as the name, and 3 as the number of fields. Then hit GO

now its time to steup the fields for our contacts table.

You should see 3 sets of form fields now. The first thing to enter is the name of the field, our first will be id, change VARCHAR to INT (this will allow numeric entries only). Next, under 'extra' set this to 'auto increment'. Finally click the radio button beside the small key icon. This will make this numeric ID field the primary key for all records in this database. This will make querying our database faster and easier later.

in the second group of form fields we want to name the field name leave it as VARCHAR and in the Length/Values field enter 150

in the third group of form fields we want to name the field phone also leave it as VARCHAR and in the Length/Values field enter 50

Screenshot attached>>>



Now we are ready to insert some data..

Here is a basic HTML form
Code:
<form method="POST">
Name: <input type="text" name="name"/><br />
Phone: <input type="text" name="phone"/><br />
<input type="submit">
</form>

Prefect, now all we need is some PHP to take the values in the HTML form and add them to the fields in our database table.


PHP Code:
<?php

mysql_connect
("localhost""username_dbuser""12345"
or die(
mysql_error());

// If the connection was a success, brag about it.
echo "woot! we are connected to MySQL<br />";

//Connect to a specific database
mysql_select_db("username_phonebook"
or die(
mysql_error());

echo 
"alright! connected to the phonebook database";

//Now lets check if the form has been submitted

if(isset($_POST['name'])) {

//the form has been submitted, lets add the data

mysql_query("INSERT INTO contacts 
(name, phone) VALUES(\"{$_POST['name']}\",\"{$_POST['phone']}\" ) "

or die(
mysql_error());  

echo 
"Name and Phone # added!<br /><br />";

}

//If the form has not been submitted
else {
?>
<form method="POST">
Name: <input type="text" name="name"/><br />
Phone: <input type="text" name="phone"/><br />
<input type="submit">
</form>
<?php

}

?>
Now using this form you can add as many entries into your phonebook as you like.



so now we know how to add data to our database, how about showing the data we have added.

PHP Code:
<?php

//Connect to the Database
mysql_connect("localhost""username_dbuser""12345"
or die(
mysql_error());

// If the connection was a success, brag about it.
echo "woot! we are connected to MySQL<br />";

//Connect to a specific database
mysql_select_db("username_phonebook"
or die(
mysql_error());

echo 
"alright! connected to the phonebook database";

//Query to select all contacts we have added
$query "SELECT * FROM contacts"
     
//Run the query
$result mysql_query($query) or die(mysql_error());

// A loop to run until empty
while($row mysql_fetch_array($result)){

//output results to the screen after each loop through

    
echo $row['name']. " - "$row['phone'];
    echo 
"<br />";
}

?>
So there you have it, a quick and dirty way to add data to a mysql database and then select the results for outputting to the screen.

Some of the finer nuances have been left out for sake of keeping this tutorial short, but rest assured you will need to validate all the POST variables to secure your script, this is a topic for the near future or you can google PHP form validation, there have been plenty of write ups about this very important topic.
Attached Thumbnails
Click image for larger version

Name:	tables.gif
Views:	442
Size:	16.5 KB
ID:	7  
Posted in Coding
Views 1837 Comments 3 Email Blog Entry
« Prev     Main     Next »
Total Comments 3

Comments

  1. Old
    <a href=”http://www.sdff.com/”>good</a>
    good
    good
    Posted 06-03-2010 at 10:45 PM by siluo siluo is offline
  2. Old
    See ugg shoes online National Car Rental Specials to Go, where you can find the best car rental deals National has to offer. Local, regional, and international rental car rates and E-coupons discounts! Nationalcar.com offers nationwide car rental exclusives, daily, weekly, weekend and one-way rental ugg women's boots car specials as well as our Last Minute travel discounts. Reserving a rental car, luxury car rental, or van rental for your next business trip or vacation travel couldn't be any more convenient.National Car Rental provides a large selection ugg bailey button of quality vehicles for your business or leisure car rental needs from midsize and fullsize car models, to convertibles, SUVs, and minivans as well as specialty cars, trucks, and van rental. National provides exceptional variety and service to alexander wang boots discount every car reservation and rental. National Car Rental has a car rental agency located in over 3,000 destinations throughout the United States, Canada, Europe, Latin America, the Caribbean, Asian-Pacific, Africa and Australia. Locations can be searched through mapping or alexander wang boots on sale text searches yjh.
    Posted 06-03-2010 at 10:45 PM by siluo siluo is offline
  3. Old
    seem that you do notchristian louboutin weddingproperly lovebuy christian louboutinyour friend for his sake,
    and wow raid items for saleso your relationship is not fully one of friendship after all.
    So it looks like pleasurewow gears onlineand utility friendships are at best deficient modes of friendship;
    by contrast, virtuecheapest wow gearsfriendships, because they are motivated by the excellences of your are genuine, non-deficient friendships. Forwow gear salethis reason, most contemporary accounts,
    by focusingnike shox men xzx
    Posted 07-05-2010 at 07:43 PM by yangyue yangyue is offline
 


Powered by vBulletin Copyright ©2000 - 2010, , Jelsoft Enterprises Ltd