Transcript PHP and MySQL - renenergy2011.net
PHP and MySQL
Lectue 4
PHP & MySQL
Open source
has brought a lot more than Linux to the computing world. It has also given us
PHP and MySQL
.
PHP and MySQL are viewed by many as the world's best combination for creating data-driven sites.
MySQL databases
are ideal for storing that data we have collected about a user or for holding user preferences between visits.
It is free and it is easy
.
PHP, Apache, MySql
Apache, PHP, MySql
отворен код. са част от групата софтуер с Комбинацията от тези три модула най-често се означава като
AMP
.
Apache
. Това е HTTP (Web) сървър. По статистика от 2004 – 2005 година Apache работи на повече от 64 милиона сървъра, повече от Microsoft, SunOne и Zeus, взети заедно.
PHP, Apache, MySql
PHP.
Това е скриптов език, изпълняван върху сървър.
Неговата гъвкавост и относително малкото време за изучаване (особено за програмисти, запознати със C, Java, Perl ) го правят един от най-популярните сред другите подобни езици.
MySql.
Това е също много предпочитан продукт с отворен код, който осъществява връзка с бази от данни и дава възможност PHP и Apache да работят заедно. Това е SQL сървър, предназначен да работи с големи натоварвания и да осъществява сложни задачи. Като система за релационни бази от данни MySql позволява свързването на много различни таблици за максимална ефективност и скорост.
Настройване на инсталацията на MySQL
MySQL
се нуждае от TCP/IP, за да работи правилно. В Windows това става чрез настройка на
Network settings
.
Тестване на инсталацията на
MySQL
.
За тестване на инсталацията на MySQL се използва прозорец на DOS (конзолен прозорец).
За целта трябва да стартира
'Command prompt
’ и да се позиционира папката ...mysql/bin. MySql обикновено се конфигурира да бъде стартиран със стартиране на операционната система. Ако MySQL сървъра не е стартиран той може да се стартира с командата:
Mysqld start
.
Настройване на инсталацията на MySQL
В конкретната инсталация с XAMPP командата в конзолен прозорец изглежда по следния начин:
C:\xampp\mysql\bin> Mysqld start
Командата може да се стартира и от основния каталог C:\>.
Системата показва съобщение, че MySQL сървъра е стартиран успешно:
The MySql service was started successfully.
MySQL сървъра може да бъде спрян с командата:
C:\xampp\mysql\bin>Mysqld stop
Настройване на инсталацията на MySQL
Следващата стъпка е да се провери, че
MySQL
работи.
За целта може да се въведе следното:
C:\xampp\mysql\bin>mySql –u root
Конзолният екран изглежда по следния начин.
C:\xampp\mysql\bin>mySql –u root Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1 Server version: 5.0.45-community-nt MySQL Community Edition (GPL) Type ‘help’ or ‘\h’ for help. Type ‘\c’ to clear the buffer. mysql>
Настройване на инсталацията на MySQL
Наличието на такова съобщение означава, че MySql сървъра е достъпен без парола с потребителско име ‘root’. Най-често при инсталацията такава настройка се установява по подразбиране. Може
MySQL
да се конфигурира за достъп с помощта на парола и друго потребителско име. За да се промени конфигурацията за достъп до MySQL може да се използва следната последователност от команди:
C:\xampp\mysql\bin>mysqladmin –u root reload C:\xampp\mysql\bin>mysqladmin –u root password mypassword
Тук е променена настройката на MySQL за достъп. След тези команди за достъп до MySQL се изисква парола, като в случая паролата е 'mypassword’.
Настройване на инсталацията на MySQL
Входът към MySQL монитора се осъществява с командата:
C:\xampp\mysql\bin>mySql –u root –p Password*********
C:\xampp\mysql\bin>mySql –u root –p Password********* Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1 Server version: 5.0.45-community-nt MySQL Community Edition (GPL) Type ‘help’ or ‘\h’ for help. Type ‘\c’ to clear the buffer. mysql>
Командата за изход от MySQL e: mysql> quit ;
Основни команди на MySQL
MySQL е програмна система за управление на бази данни. Базите данни са контейнери, които съхраняват информация в структуриран вид. Всяка база данни се състои от една или повече таблици , които структурират данните в редове и колони. Всяка колона в таблицата има наименование (етикет), който идентифицира какъв тип данни се съхраняват в полетата на таблиците. Всеки ред съдържа запис за определен обект. При инсталацията на MySQL по подразбиране се създават две бази данни – едната е празна с наименование „
test
” и една с наименование „
mysq
l ”, в която се съхранява служебна информация на MySQL. За да се види какви бази от данни съществуват под управлението на MySQL се използва команда:
mysql> show databases;
Основни команди на MySQL
Ако не са създадени други бази от данни то конзолният екран за тази команда би изглеждал така: mysql>
show databases
------------- ; |Database ------------- | |mysql | |test | ------------- 2 rows in set (0.00 sec) Създаването на нова база данни се извършва с помощта на командата:
mysql>create database testdb ;
При успешно създаване на база данни, за да се работи с нея тя трябва да се направи активна (да се избере). Това става с помощта на командата:
мysql> use testdb ;
Основни команди на MySQL
Може да се види какви таблици има в дадената база данни с помощта на командата:
мysql> show tables ;
mysql>
use mysql;
mysql>
show tables;
--------------------- |Tables_in_mysql --------------------- |columns_priv | | |db |func |help_category | | | ............
|user | --------------------- 15 rows in set (0.02 sec) mysql> explain user; …………….
Основни команди на MySQL
Може да се използва SQL командата ‘
explain ’
да се види формата на таблицата.
(обяснение) за Тази команда показва всички имена на колони в таблицата и подробностии за данните, които се съдържат в тях.
Друга важна дейност на MySQL е осигуряване на на данните.
сигурност Хакерите са твърде находчиви в опитите си да проникнат и да използват информацията в Internet.
MySQL
дава възможност да се изберат кои потребители, какви функции могат да изпълняват с информацията в базата данни на основата на
‘привилегии
’.
Цялата тази информация се съхранява в база от данни, наречена
mysql
, която по подразбиране се намира в папката:
C:\xampp\mysql\data.
Основни команди на MySQL
Ако за работа с базите данни има само един потребител с достъп до
MySQL
, тогава не необходимо добавянето на други потребители и задаване на привилегии.
В повечето случаи се налага с базата данни да работят и други потребители, които могат да имат различни задачи при работата с информацията в базите данни.
Някои може само да разглеждат информацията, други да въвеждат определен тип данни, трети да могат да създават и изтриват таблици и т.н.
Поради тази причина трябва да се въведат и други потребители, които да имат достъп до данни.
MySQL,
като за всеки от тях се уточни какви права има по отношение на базата За целта се използват няколко команди на
MySQL
, изпълняват от ‘root’ потребителя (администратора).
които се
Основни команди на MySQL
Създаване на нов потребител.
Използва се следната команда в MySQL монитора: mysql>use mysql; Database changed mysql>
insert into user (host, user, password) values (‘localhost’,’testadmin’,password(‘testpass’)) ;
Query OK, 1 row affected, 3 warnings (0.03 sec) С тази команда се създава потребител ‘
testadmin
’, данните за който са записани в таблицата ‘
user
’ от служебната база данни
'mysql
’.
Добавяне на права за достъп.
Използва се следната команда в MySQL монитора: mysql>
insert into db (host, user, db) values (‘localhost’,’testadmin’,’testbd’) ;
Query OK, 1 row affected (0.03 sec) mysql>
Основни команди на MySQL
С изпълнението на тази команда на потребителят ‘
testadmin
’ се дава достъп до базата данни '
testdb
’.
Все още не са уточнени какви привилегии има той по отношение на таблиците, намиращи се в базата данни. За да се уточнят привилегиите на потребителя се използват команди от типа: mysql>
GRANT SELECT, INSERT,UPDATE, -> ON testdb.* -> testadmin -> [IDENTIFIED BY ‘testpass’] -> [with grant option];
Query OK. 0 rows affected (0.44 sec) mysql> …………….
С тази команда се задават привилегии
UPDATE
на потребителя ‘
testadmin
’
SELECT, INSERT,
за база от данни ‘
testdb
’. Вместо изброяване на конкретни привилегии може да се запише 'all’, което означава, че се задават всички привилегии дефинирани в MySql;.
Основни команди на MySQL
Привилегиите могат да се зададат на потребителя за всички бази от данни, ако вместо ‘
testdb
’ се използва символа '*'. Последните два елемента от командата, зададени в квадратни скоби, са незадължителни. Спесификацията от последния ред
'with grant option
своите привилегии на други потребители.
’ се използва, когато потребителят може да предоставя част от Другият начин за задаване на привилегии, специфични за конкретна база данни mysql>
update db Set Create_priv=’y’, Delete_priv=’y’ -> where user like ‘testadmin’;
Query OK. 1 rows affected (0.00 sec) Mysql>
flush privileges;
Query OK. 0 rows affected (0.02 sec) mysql> …………….
Granting Privileges
This is a command to create users and give them privileges. A simplified general syntax is
GRANT privileges ON item TO user_name [IDENTIFIED BY 'password'] [WITH GRANT OPTION]
If you use WITH GRANT OPTION, you allow the user to grant other users the privileges that you have given to him.
REVOKE is opposite of GRANT.
Privileges
SELECT
allows users to select (read) records from tables.
INSERT
allows users to insert new rows into tables.
UPDATE
allows users to change values in existing table rows.
DELETE
allows users to delete table rows (records).
INDEX
allows user to index tables
ALTER
allows users to change the structure of the database.
- Adding columns - Renaming columns or tables - Changing the data types of tables
DROP
allows users to delete databases or tables.
CREATE
allows users to create new databases or tables.
- If a specific database or table is mentioned in the GRANT statement, users can only create that database or table.
USAGE
allows users nothing.
ALL
means just that.
MySQL DataBase
This is how we open and close a MySQL database:
$link = mysql_connect("mysql_host", "mysql_login", "mys ql_password") or die ("Could not connect"); print ("Connected successfully"); mysql_select_db ("my_database") or die ("Could not select database"); $query = "SELECT * FROM my_table"; $result = mysql_query ($query) or die ("Query failed"); // This is where we proccess the data returned by the quary ?> mysql_close($link);
Step 1: mysql_connect()
mysql_connect() establishes a connection to a MySQL server.
◦ ◦ ◦ ◦
It takes 3 parameters.
The address of the server Your Username for that db account Your password
$conn = mysql_connect(“address", “user“, “pass”);
Step 2: mysql_select_db()
In our code
mysql_select_db()
then tells PHP that any queries we make are against the mydb database.
mysql_select_db(“dbname",$conn);
We could create multiple connections to databases on different servers. But for now, you’ll only need one database.
Step 3: mysql_query()
Next,
mysql_query()
does all the hard work.
Using the database connection identifier, it sends a line of SQL to the MySQL server to be processed.
This is the key command for interacting with the database.
In our example the results that are returned are stored in the variable
$result.
Step 4 & 5: Iterating through each row and displaying each field
Using
mysql_num_rows($result),
we iterate through each row, and return the value of the specified fields.
Finally,
mysql_result()
is used to display the values of fields from our query:
mysql_result($result,$row,"first");
MySQL DataBase
mysql_num_fields($result)
Get number of fields in result
mysql_num_rows($result)
Get number of rows in result mysql_fetch_row($result) array Get a result row as an enumerated
mysql_fetch_array($result)
associative array.
Fetch a result row as an
MySQL example : guest book
1. CREATE DATABASE test_data (or use existing db) 2. Create the table containing the list. SQL-query: CREATE TABLE guestsign (id INT not null AUTO_INCREMENT, n ame TEXT not null , comment TEXT not null , PRIMARY KEY (id), INDEX (id), UNIQUE (id))
MySQL example : guest book - the form
gustbook1.php
Please sign my guestbook : $link = mysql_connect("localhost", "", "") or die ("Could not connect"); mysql_select_db ("guestbook") or die ("Could not select database"); $query = "SELECT * FROM guestsign"; /* you migh want to add a "LIMIT 0,30" */ /* or maybe a "ORDER BY id DESC"*/ $result = mysql_query ($query) or die ("Query f ailed"); $signnum = mysql_num_rows($result); for ($i=1 ; $i <= $signnum ; $i++){ $row_array = mysql_fetch_array($result); ?> } ?> mysql_close($link);
name comment
= $row_array["name"] ?> = $row_array["comment"] ?>
MySQL example : guest book - insert
guestbook2.php
$link = mysql_connect("localhost", "", "") or die ("Could not connect"); mysql_select_db ("guestbook") or die ("Could not select database"); $guestname = stripslashes(str_replace("'","''",$guestname)); $comment = stripslashes(str_replace("'","''",$comment )); $query = "insert into guestsign set name='$guestname',comme nt='$comment'"; mysql_query ($query) or die ("Query failed: $query
" . mysql _error()); ?>
The Query
The
Query
is the basic method by which data is entered or extracted from a database.
It is common to all database systems.
It is simply a command to the
MySQL
database in order to tell it to do something.
SQL Commands
SQL is a reasonably powerful query language.
However it is incredibly simple. You can learn it in a night.
The fundamental SQL commands are:
CREATE SELECT INSERT DELETE UPDATE
Creating a Table
$link = mysql_connect ('localhost','root','') or die ('Could not connect') ; print ('Connection successfully
'); mysql_select_db ('test_data') or die ('Could not select database') ; mysql_query ("CREATE TABLE people ( first varchar (30), last varchar (30), ; country varchar (30))"); print ('Creation successfully
'); mysql_query ("INSERT INTO people VALUES ('George','Bush','USA')") ; mysql_query ("INSERT INTO people VALUES ('Peter','Crouch','England')") mysql_query ("INSERT INTO people VALUES ('Ivan','Vazov','Bulgaria')") ; print ('Insertion successfully
'); ?>
MySQL/PHP Program
$db = mysql connect (“localhost”, “root”, “”) ; mysql_select_db (“mydb”,$db) ;
$result= mysql_query("SELECT * FROM people“, $db); for($i = 0; $i < mysql_num_rows($result); $i++)
◦
{
◦
$first= mysql_result($result, $i, "first");
◦
$last = mysql_result($result, $i, "last");
◦
$addr=mysql_result($result, $i, "address")."
";
◦
}
?>
MySQL/PHP Program (Another way to access values)
$db = mysql connect (“localhost”, “root”, “”) ; mysql_select_db (“mydb”,$db) ;
$result= mysql_query ("SELECT * FROM people“, $db); while($row = mysql_fetch_array($result)) { echo $row["first"]; //echo $row[0]; } echo $row["last"]; //echo $row[1]; echo $row["address"] . "
"; //echo $row[2]; ?>
1. Magic Quotes Problem
For example say, we are putting a record into our database – the mysql query might be:
insert into people values (‘Cameron Diaz’);
In you
php
this would be sent to the database using mysql_query as follows:
mysql_query(‘insert into people values (‘Cameron Diaz’)’);
This would cause a parse error – so make sure you use the correct quotes to avoid this.
2. MySQL Connection Function
Here is a function that automates connecting to a certain database.
}
Save it in a separate file e.g. ConnectToDB.inc
function db_connect() { $result = mysql_connect("localhost ", “jog", “pass"); if (!$result) return false; if (!mysql_select_db
(“people")) return false; return $result;
It is a good practice to write these statements in a function and separate file.
Include this file and call the function wherever you want to connect to database.
include_once (“ConnectToDB.inc"); ?>
Making a query (reminder)
Now we have connected by calling this function, we can access the database to make a query to it.
Remember to send a mySQL instruction to the database we use
mysql_query()
You can make absolutely any query that you would type into the database command line via PHP in this way.
Create Table Example
For example, to create a table from our PHP code you might type:
mysql_query (“CREATE TABLE students (
name varchar(30),
age integer)”);
Remember that this is something that you would only want to do once – once the table is created we don’t want to wipe it by accident.
MySQL Insert Example
Equally we can populate our tables with INSERT statements via
mysql_query()
mysql_query (“INSERT INTO students VALUES (‘Ivan Dimitrov',26)”); mysql_query (“INSERT INTO students VALUES (‘Maria Stoyanova',20)”); mysql_query (“INSERT INTO students VALUES (‘Dimitar Kalev',20)”);
These are hard coded examples – but we could be using variables in these statements
Mysql Select Example
We use a SELECT statement to grab data from a certain table and then put the result into a variable ready to analyse…
$result = mysql_query(“SELECT * FROM students WHERE age<25);
However now result has all the info we want inside it… you can use any of the following function to access the returned result.
mysql_fetch_array()
is an extended version of
mysql_fetch_row().
In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.
Which you use is up to you. Both functions are pretty similar.
mysql_num_rows()
mysql_num_rows()
returns the number of rows in a result set. This command is only valid for SELECT statements.
mysql_query (“SELECT * FROM students WHERE age<25); print mysql_num_rows ().“ students are younger than 25";
It’s a great function for when you need to loop round all the results in your query, or just to know how many matches you got
mysql_affected_rows()
mysql_affected_rows()
returns the number of rows affected by the last INSERT, UPDATE or DELETE query associated with. For example:
mysql_query("DELETE FROM mytable WHERE id < 10"); print "Records deleted: ".mysql_affected_rows()."
";
Note:
this function does not work with SELECT statements - only on statements which modify records.
Terminating Execution
There are two ways to stop the execution of a script.
The first is using the
exit()
statement which simply stops the script without returning anything.
More useful – especially for bug checking – is the
die()
command.
This language construct can be used to output an error message or execute a function before terminating the script.
Why won’t you just die
die(“Could not execute query”);
This would simply exit the script and send the message to the browser. However you can add a die statement to another using the or command…for example:
mysql_query($query) or die(“Could not execute query”);
Alternatively you can use die to fire off
a function
– maybe you want to email notification to yourself when a major error has occurred or add errors to a log file?
Querying Web Databases with PHP
Address Book database from the previous lab Contacts, Groups $conn =
mysql_connect
(“localhost", “root", “");
mysql_select_db
("addressbook", $conn); $results =
mysql_query
("SELECT * FROM Contacts", $conn); while ($row =
mysql_fetch_array
($result)) { } print "$row[
'firstName
'] $row[
']";
Handling Errors
$conn = mysql_connect (“localhost", “root", “");
or die("Could not connect: " . mysql_error());
mysql_select_db("addressbook", $conn);
or die("Could not connect: " . mysql_error());
$results = mysql_query("SELECT * FROM Contacts", $conn);
or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_array($result)) {
print "$row['firstName'] $row['email']";
}
MySQL Functions (1/2)
mysql_connect
— Open a connection to a MySQL Server
mysql_ping
— Ping a server connection or reconnect if there is no connection
mysql_close
— Close MySQL connection
mysql_error
— Returns the text of the error message from previous MySQL operation
mysql_list_dbs
— List databases available on a MySQL server
mysql_select_db
— Select a MySQLdatabase
mysql_list_tables
— List tables in a MySQL database
mysql list fields
— List MySQL fields
MySQL Functions (2/2)
mysql_query -
Send a MySQL query
mysql_affected_rows
— Get number of affected rows in previous MySQL operation
mysql mysql_num_rows
— Get number of rows in result
mysql_fetch_array
— Fetch a result row as an associative array, a numeric array, or both
mysql_fetch_assoc
— Fetch a result row as an associative array
mysql_fetch_row
— Get a result row as an enumerated array
mysql_fetch_object
— Fetch a result row as an object
mysql fetch field
— Get column information from a result
Adding Actionable Hyperlinks 1/2)
$conn = mysql_connect ("localhost", "root", “"); mysql_select_db("AddressBook", $conn); $result = mysql_query("select * from contacts"); while ($row = mysql_fetch_array($result)) { print “
$cid = $_GET['id']; $conn = mysql_connect ("localhost", "root", “"); mysql_select_db ("AddressBook", $conn); $query = "DELETE FROM Contacts WHERE id={$cid}"; mysql_query ($query); If( mysql_affected_rows ($query) ) { print mysql_affected_rows ($query).“ row(s) Deleted successfully"; } ?> Populate form fields with information from database Send the user input to PHP script for storing in the Database ‐
...
$results = mysql_query("SELECT * FROM Groups", $conn); print ' while ($group = mysql_fetch_array($results)) { print "
$group[“id”] . “ '> “ . $group[“name”]” . “
" ; } print ''; ?> ... do ‐ add.php ... $group_id = _POST['group']; $query = "INSERT INTO Contacts VALUES … group=$group_id "; mysql_query($query, $conn); if( mysql_affected_rows($conn) ) { } print "New contact added successfully"; ... Don’t run MySQL as administrator/root . Run it as a user created specifically for this purpose. Don’t use this account for anything else. Don’t access web database with root user. Create a separate admin account for each database for reading and writing from PHP script. Disallow access to port 3306 (or whatever port you have MySQL running on) except from trusted hosts. All MySQL accounts should have a password, especially root . Grant users the minimum level of privilege required to do their job. ◦ Principle of Least Privilege Set permissions on the database directories so that only appropriate user can access them. Only the root user should have access to the mysql database, which contains privilege information. Don’t Don t store application passwords in plaintext in the database. (Use hashing mechanisms) PHP has an in built sha1() function that calculates hashing scheme of a string. The result of sha1() can not be translated back into the original string. This makes it a good way to store password. $safe_password=sha1($password);
First Name Last Name Email Actions " . $row["LastName"] . " "; print “" . $row["email"] . " "; print “ Remove "; print ""; } mysql_close($conn);
Adding Actionable Hyperlinks 2/2)
Interaction with the User
Populating Selection Box
add
contact.php
Storing User Input in Database
Secure Configuration
Accounts and Privileges
Using Encryption