Lesson 1: Connecting to MySQL
Before you can make any actions in MySQL, you will have to connect into it. You Web Server may give you the necessary information for this.
Let"s see a simple example:
|
<?php // MySQL info variables $mysql["host"] = "localhost"; $mysql["user"] = "root"; $mysql["pass"] = "pass"; $mysql["database"] = "devpapers";
// Connect to MySQL mysql_connect($mysql["host"], $mysql["user"], $mysql["pass"]) or die("MySQL connection failed. Some info is wrong");
// Select database mysql_select_db($mysql["database"]) or die("Could not connect to DataBase \"$mysql["database"]\""); ?> |
if you do everything right, nothing will appear, and now you can start using MySQL!
Lesson 2: Creating a MySQL table
For content storage, you must have a table in your DataBase. The code bellow will show how to create a simple table.
|
<?php // Define table fields and types $query = "CREATE TABLE `test1` ( `id` INT( 6 ) NOT NULL AUTO_INCREMENT ,"; $query .= " `name` VARCHAR( 40 ) NOT NULL ,"; $query .= " `email` VARCHAR( 80 ) NOT NULL ,"; $query .= " `info` TEXT NOT NULL ,"; $query .= " PRIMARY KEY ( `id` ) );";
// Create the table mysql_query($query) or die("Could not create the table"); echo "Table created!"; ?> |
This must create our examples table. See more about the "CREATE TABLE" syntax at
http://www.mysql.com/doc/en/CREATE_TABLE.html
Lesson 3: Inserting content into the table
The main objective of a DataBase is storage content, so, lets insert it.
<?php // Inserting query $query = "INSERT INTO test1 (id, name, email, info) VALUES ("", "Andreas", "dreazdesign@hotmail.com", "PHP and MySQL programmer")";
// Run the query mysql_query($query) or die("Could not insert content into table"); echo "Content was sucessfully insert"; ?> |
Lesson 4: Showing a table content
Supposing that you are using the table test1 (lesson3), content showing will look like this:
|
<?php // Get the MySQL connection file (lesson 1) require "connection.php";
// Call the table test1 $query = "SELECT name, email, info FROM test1";
// Execute the query $query = mysql_query($query) or die("error in the query \$query");
// Show what we got while($info = mysql_fetch_array($query)) { echo "User Name: ".$info["name"]."<br>"; echo "User e-mail: ".$info["email"]."<br>"; echo "User Info: ".$info["info"]."<br>"; echo "<br>"; } ?> |
With this you may have every table content printed in the screen.
Now you have your personal content storage! In the next page you will learn some other queries syntax, which will prove to you that DataBase is very useful.