PHP MySQL

advertisement
PHP MySQL
The tutorials…
MySQL
• MySql is a powerful database.
• It's very good and free of charge.
• Many developers in the world selected mysql
and php for developing their website.
Top Ten Reasons to Use MySQL
•
•
•
•
•
•
•
•
•
•
•
Scalability and Flexibility
High Performance
High Availability
Robust Transactional Support
Web and Data Warehouse Strengths
Strong Data Protection
Comprehensive Application Development
Management Ease
Open Source
Freedom and 24 x 7 Support
Lowest Total Cost of Ownership
Create database, table and managing
MySQL database using phpMyAdmin
• phpMyAdmin is a tool for managing MySQL
database and free of charge, it's a web base
tool.
• If you install Wamp, Xammp or EasyPHP,
phpMyAdmin is included in the package.
• If you manually installed Apache, PHP and
MySQL, you can download phpMyAdmin at
their officail site.
Create database, table and managing
MySQL database using phpMyAdmin
• phpMyAdmin
Create database, table and managing
MySQL database using phpMyAdmin
• Create database using phpMyAdmin
– To create new database use this form, type
database name then click "Create" button. In this
example I create database name
"test_create_DB".
Create database, table and managing
MySQL database using phpMyAdmin
• Create table
– After created database. this form'll be display.
Enter the name of table and number of field. In
this example, I create table name "web_members"
for store my web members and it have 4 fields (id,
name, lastname, email)
Create database, table and managing
MySQL database using phpMyAdmin
• Result after created table on database
Create database, table and managing
MySQL database using phpMyAdmin
• Create table by runing SQL query
– ou can create table by run SQL query for example,
put MySql code in the form and click "Go“or
browse from text file (read export database for
creating text file (.sql))
Create database, table and managing
MySQL database using phpMyAdmin
• MySQL code
CREATE TABLE `web_members` (
`id` int(4) NOT NULL auto_increment,
`name` varchar(65) NOT NULL default '',
`lastname` varchar(65) NOT NULL default '',
`email` varchar(65) NOT NULL default '',
PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=1 ;
Create database, table and managing
MySQL database using phpMyAdmin
• Export database
Create database, table and managing
MySQL database using phpMyAdmin
• In tab Export. You can export your database in
many format like
- SQL (text file .sql)
- Latex
- Microsoft Exel 2000
- Microsoft Word 2000
- CVS for MS Exel
- CVS
- XML
Create database, table and managing
MySQL database using phpMyAdmin
• Steps
– Select table you want to export or select all table.
– Select file format
– Select save as file(if you want to save as a file if
not select it'll show you only Sql query)
– Select compression
• None
• zipped (.zip)
• gzipped (.gzip)
CONNECT TO MYSQL DATABASE
Syntax
mysql_connect("host", "username", "password")or
die("cannot connect to server");
• Overview
– host="localhost" you don't have to change it. When
it's on your computer or server it still be localhost
Username = database username
Password = database password
Database = database name
Example
$host="localhost";
$username=“root";
$password="1234";
$db_name="test";
mysql_connect("$host", "$username", "$password")or
die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select db");
or
mysql_connect("localhost", “root", "1234")or die("cannot
connect to server");
mysql_select_db("test")or die("cannot select db");
Creating file config.php
$host="localhost";
$username=“root";
$password="1234";
$db_name="test";
mysql_connect("$host", "$username",
"$password")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot
select db");
Creating file config.php
• Save this code as file "config.php", connect.php or whatever you
want.
• When you want to use this code include it to your main php file
• Example
<?php
include("config.php");
$tbl_name="member";
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
...
?>
INSERT DATA INTO MYSQL
Syntax
"INSERT INTO table_name(column_name1,
column_name2)VALUES('value1, 'value2')" ;
Overview
• In this tutorial, create 2 files
1. insert.php
2. insert_ac.php
Steps
1. Create table "test_mysql" in database
"test".
2. Create file insert.php.
3. Create file insert_ac.php.
STEP1: Create table "test_mysql"
CREATE TABLE `test_mysql` (
`id` int(4) NOT NULL auto_increment,
`name` varchar(65) NOT NULL default '',
`lastname` varchar(65) NOT NULL default '',
`email` varchar(65) NOT NULL default '',
PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=0 ;
STEP2: Create file insert.php
• View In Browser
STEP2: Create file insert.php
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1">
<tr>
<td><form name="form1" method="post" action="insert_ac.php">
<table width="100%" border="0" cellspacing="1" cellpadding="3">
<tr>
<td colspan="3"><strong>Insert Data Into mySQL Database </strong></td>
</tr>
<tr>
<td width="71">Name</td>
<td width="6">:</td>
<td width="301"><input name="name" type="text" id="name"></td>
</tr>
<tr>
<td>Lastname</td>
<td>:</td>
<td><input name="lastname" type="text" id="lastname"></td>
</tr>
<tr>
<td>Email</td>
<td>:</td>
<td><input name="email" type="text" id="email"></td>
</tr>
<tr>
<td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
$datetime= date('Y-m-d H:i:s');
$sql="INSERT INTO $tbl_name(name, lastname,
email, datetime)VALUES('$name', '$lastname',
'$email', '$datetime')";
$result=mysql_query($sql);
STEP3: Create file insert_ac.php
• Diagram
STEP3: Create file insert_ac.php
<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="test_mysql"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$name=$_POST['name'];
$lastname=$_POST['lastname'];
$email=$_POST['email'];
// Insert data into mysql
$sql="INSERT INTO $tbl_name(name, lastname, email)VALUES('$name', '$lastname', '$email')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='insert.php'>Back to main page</a>";
}
else {
echo "ERROR";
}
?>
<?php
// close connection
mysql_close();
?>
Another way connect to server and
select database
• Use confing.php to connect to server and
select database.
include("config.php");
SELECT DATA FROM MYSQL
Syntax
• When you need data from your mysql database to
show in your web page, you need to select database,
table and what's row you want to pull its data first.
// Select all columns from all rows.
"SELECT * FROM table_name";
or
// Select some column from all rows.
"SELECT column_name1, column_name2 FROM
table_name";
or
// Select all coulumns from one row.
"SELECT * FROM table_name WHERE column_name='
value in column '";
Overview
• In this tutorial, we'll create only 1 file.
1. select.php
Steps
1. Create table "test_mysql" in database
"test".
2. Create file select.php.
3. test it!
Overview
• If you don't want looping rows in mysql, replace
while($rows=mysql_fetch_array($result)){
........
<?php
}
mysql_close();
?>
replace with this
$rows=mysql_fetch_array($result);
.........
<?php
mysql_close();
?>
STEP1: Insert data into table
"test_mysql"
• In this step, you have to insert data for testing our
code.
INSERT INTO `test_mysql` VALUES (1, 'Billly',
'Blueton', 'bb5@phpeasystep.com');
INSERT INTO `test_mysql` VALUES (2, 'Jame',
'Campbell', 'jame@somewhere.com');
INSERT INTO `test_mysql` VALUES (3, 'Mark',
'Jackson', 'mark@phpeasystep.com');
STEP2: Create file - select.php
STEP2: Create file - select.php
<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="test_mysql"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Retrieve data from database
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
?>
<table width="400" border="1" cellspacing="0" cellpadding="3">
<?php
// Start looping rows in mysql database.
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td width="10%"><? echo $rows['id']; ?></td>
<td width="30%"><? echo $rows['name']; ?></td>
<td width="30%"><? echo $rows['lastname']; ?></td>
<td width="30%"><? echo $rows['email']; ?></td>
</tr>
<?php
// close while loop
}
</table>
?>
<?php
// close MySQL connection
mysql_close();
?>
STEP3: Run the Code
UPDATE DATA IN MYSQL
Syntax
• Update/Edit data from mysql database, can do
it easily.
"UPDATE table_name SET column_name1='
value', column_name2=' value' WHERE
column_name=' value' ";
Overview
• In this tutorial, we create 3 PHP files for testing
our code.
1. list_records.php
2. update.php
3. update_ac.php
Steps
1. Create file list_records.php
2. Create file update.php
3. Create file update_ac.php
STEP1: Create file - list_records.php
STEP2: Create file - update.php
STEP3: Create file - update_ac.php
DELETE DATA FROM MYSQL
Syntax
• Delete data from your mysql database.
"DELETE FROM table_name WHERE
column_name=' value' ";
Overview
• Overview
In this tutorial create 2 files
1. delete.php
2. delete_ac.php
Step
1. Create file delete.php.
2. Create file delete_ac.php.
STEP1: Create file - delete.php
STEP2: Create file delete_ac.php
ORDER MYSQL RESULTS
Overview
• You can order MySQL results using "ORDER BY"
1. ORDER BY column_name ASC
2. ORDER BY column_name DESC
3. ORDER BY RAND().
1. ORDER BY column_name ASC is order by ascending.
2. ORDER BY column_name DESC is order results by
descending.
3. ORDE BY RAND() is order results by random.
If you're not set this up the default is order results by
ascending.
Syntax
"SELECT column_name FROM table_name ORDER BY column_name
ASC";
or
"SELECT column_name FROM table_name";
- This will select the records from mysql by ascending (ascending is the
default value).
"SELECT column_name FROM table_name ORDER BY column_name
DESC";
- This will select the records from mysql by descending
"SELECT column_name FROM table_name ORDER BY RAND()";
- This will select the records from mysql by random
Example Order by Ascending
Example Order by Descending
Example Order by Random
PHP LOGIN SCRIPT TUTORIAL
Overview
• Learn to create a simple login system with php
+ mysql script, this tutorial is easy to follow,
teach you step by step.
– In this tutorial, we create 3 php files for testing
our code.
1. main_login.php
2. checklogin.php
3. login_success.php
Steps
1.
2.
3.
4.
5.
Create table "members" in database "test"
Create file main_login.php
Create file checklogin.php
Create file login_success.php
Create file logout.php
STEP1: Create table "members"
• For testing this code, we need to create
database "test" and create table "members".
STEP1: Create table "members"
CREATE TABLE `members` (
`id` int(4) NOT NULL auto_increment,
`username` varchar(65) NOT NULL default '',
`password` varchar(65) NOT NULL default '',
PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=2 ;
--- Dumping data for table `members`
-INSERT INTO `members` VALUES (1, 'john', '1234');
STEP2: Create file main_login.php
• The first file we need to create is
"main_login.php" which is a login form.
STEP3: Create file checklogin.php
• We have a login form in step 2, when a user
submit their username and password, PHP code
in checklogin.php will check that this user exist in
our database or not.
• If user has the right username and password,
then the code will register username and
password in the session and redirect to
"login_success.php".
• If username or password is wrong the system will
show "Wrong Username or Password".
STEP3: Create file checklogin.php
<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword");
header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}
?>
STEP4: Create file login_success.php
• User can't view this page if the session is not registered.
// Check if session is not registered, redirect back to main page.
// Put this code in first line of web page.
<?php
session_start();
if(!session_is_registered(myusername)){
header("location:main_login.php");
}
?>
<html>
<body>
Login Successful
</body>
</html>
How to protect other pages?
• Just put this code to the other pages!
// Check if session is not registered, redirect back to main page.
// Put this code in first line of web page.
<?php
session_start();
if(!session_is_registered(myusername)){
header("location:main_login.php");
}
?>
STEP5: Create file Logout.php
• If you want to logout, create this file. The
code in this file will destroy the session.
// Put this code in first line of web page.
<?php
session_start();
session_destroy();
?>
Encrypting Password - Make your
Login More Secure
• Use MD5
THANK YOU!
<td align="center"><a
href="update.php?nombor=<?php echo $rows['id'];
?>">update</a> | <a href="delete_ac.php?id=<?php
echo $rows['id']; ?>" onclick="return confirm('Are you
sure you want to delete this entry?')">delete</a></td>
Download