|
Added on 14.11.09 |
| Clicks 1523 |
| Rating: 4.00 out of 5 from 2 raters |

mysql_close($link);
?>Explaining the above code is quite simple, as you can see ,it starts with
for variables where we store the host,the username,the password and the
database name.Then we connect to MySql using a predefined PHP function
mysql_connect passing as
parameters the variables we created,once the connection succeeds,we can
create the database assigning the SQL statement
'CREATE DATABASE $database'to the
variable $sql and then using another PHP
function mysql_query to execute the query and
,at the end,it's a good habit to close the connection with the PHP function
mysql_close.That's
it the database is ready to store all your data
Create a Table
Now that we've got a database we can create a table ,but before actually do it we better have a look what data the table will be storing,for our example we are going to store books for a library, Therefore we'll need an identifier , a title, an author and a category for each book,let's see how we can sort it out:
| Field | Type | Length | Description | ||||
| ID | int | 6 | Unique identifier | ||||
| title | Varchar | 250 | Book's title | ||||
| Author | Varchar | 150 | The Author's name | ||||
| Category | Varchar | 50 | The Category for the book | ||||
| Price | Varchar | 20 | The book price | ||||
We can see the code below
if (!$link = @mysql_connect($host,$username,$password,true))
{die('Could not connect:'. mysql_error()); }
@mysql_select_db($database)
or die( "Unable to select database");
The code creates a table in a existing database,it starts like before
,declaring all the variables ,the i connects to the database
link = mysql_connect('$host', '$username', '$password');
if (!$link) {
die('Could not connect: ' . mysql_error()); And
this time we select the Database to store the
table using the PHP function @mysql_select_db ,
we assign the sql statement to create the book table and then we execute the
query with mysql_query,and finally,we close the
connection.
Try the example below