Well in this tutorial i will show how to do connect to database, how to add things and how to update things in your database.
1. Connecting
Syntax:
Code:
mysql_connect(servername,username,password);
Example:
PHP Code:
<?php
$connect = mysql_connect("localhost", "MyUsername", "MyPassword");
// If there's problem with connecting to database then this part will show this problem
if(!$connect){
die("Cannot connect to database ".mysql_error());
}
?>
2. Selecting a database
Syntax
Code:
mysql_select_db(database_name);
Example:
PHP Code:
<?php
$connect = mysql_connect("localhost", "MyUsername", "MyPassword");
if(!$connect){
die("Cannot connect to database ".mysql_error());
}
mysql_select_db("my_database");
?>
3. Creating a database
Syntax:
Code:
CREATE DATABASE databasename
Example:
PHP Code:
<?php
$connect = mysql_connect("localhost", "MyUsername", "MyPassword");
if(!$connect){
die("Cannot connect to database ".mysql_error());
}
if(mysql_query("CREATE DATABASE my_database"){
echo "Database created!";
}else{
echo "There was problem with creating a database: ".mysql_error();
}
?>
4. Inserting into database
Syntax:
Code:
INSERT INTO table_name VALUES (first_value, second_value, third_value)
or
INSERT INTO table_name (first_column, second_column, third_column) VALUES (first_value, second_value, third_value)
Example:
PHP Code:
<?php
$connect = mysql_connect("localhost", "MyUsername", "MyPassword");
if(!$connect){
die("Cannot connect to database ".mysql_error());
}
mysql_select_db("my_database");
mysql_query("INSERT INTO users (username, email, age) VALUES ('Jaan', 'jaan(at)et-resources.com', '15')");
?>
5. Selecting from database
Syntax:
Code:
SELECT column(s) FROM table_name
Example:
PHP Code:
<?php
$connect = mysql_connect("localhost", "MyUsername", "MyPassword");
if(!$connect){
die("Cannot connect to database ".mysql_error());
}
mysql_select_db("my_database");
// This * means ALL so.. select all from users
mysql_query("SELECT * FROM users");
?>
Example 2:
PHP Code:
<?php
$connect = mysql_connect("localhost", "MyUsername", "MyPassword");
if(!$connect){
die("Cannot connect to database ".mysql_error());
}
mysql_select_db("my_database");
mysql_query("SELECT email FROM users");
?>
Example 3:
PHP Code:
<?php
$connect = mysql_connect("localhost", "MyUsername", "MyPassword");
if(!$connect){
die("Cannot connect to database ".mysql_error());
}
mysql_select_db("my_database");
$select = mysql_query("SELECT * FROM users");
// This creates a loop which will repeat itself until there are no more rows to select from the database. We getting the field names and storing them in the $row variable. This makes it easier to echo each field.
while($row = mysql_fetch_array($select)){
echo $row['username']. "<br>";
echo $row['age'];
}
?>
This is basic what you need to know. If you have more questions feel free to ask from me.
Have fun!