1 / 55

PHP and MySQL

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.

Download Presentation

PHP and MySQL

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. PHP and MySQL Lectue 4

  2. 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.

  3. PHP, Apache, MySql • Apache, PHP, MySqlса част от групата софтуер с отворен код. • Комбинацията от тези три модула най-често се означава като AMP. • Apache. Това е HTTP (Web) сървър. • По статистика от 2004 – 2005 година Apacheработи на повече от 64 милиона сървъра, повече от Microsoft, SunOne и Zeus, взети заедно.

  4. PHP, Apache, MySql • PHP.Това е скриптов език, изпълняван върху сървър. • Неговата гъвкавост и относително малкото време за изучаване (особено за програмисти, запознати със C, Java, Perl) го правят един от най-популярните сред другите подобни езици. • MySql. Това е също много предпочитан продукт с отворен код, който осъществява връзка с бази от данни и дава възможност PHP и Apache да работят заедно. • Това е SQL сървър, предназначен да работи с големи натоварвания и да осъществява сложни задачи. • Като система за релационни бази от данни MySql позволява свързването на много различни таблици за максимална ефективност и скорост.

  5. Настройване на инсталацията на MySQL • MySQL се нуждае от TCP/IP, за да работи правилно. • В Windowsтова става чрез настройка на Networksettings. • Тестване на инсталацията на MySQL. • За тестване на инсталацията на MySQL се използва прозорец на DOS (конзолен прозорец). • За целта трябва да стартира 'Commandprompt’ и да се позиционира папката ...mysql/bin. • MySqlобикновено се конфигурира да бъде стартиран със стартиране на операционната система. • Ако MySQLсървъра не е стартиран той може да се стартира с командата: • Mysqld start.

  6. Настройване на инсталацията на MySQL • В конкретната инсталация с XAMPPкомандата в конзолен прозорец изглежда по следния начин: • C:\xampp\mysql\bin> Mysqldstart • Командата може да се стартира и от основния каталог C:\>. • Системата показва съобщение, че MySQLсървъра е стартиран успешно: • The MySql service was started successfully. • MySQLсървъра може да бъде спрян с командата: • C:\xampp\mysql\bin>Mysqld stop

  7. Настройване на инсталацията на 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>

  8. Настройване на инсталацията на 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’.

  9. Настройване на инсталацията на MySQL • Входът към MySQL монитора се осъществява с командата: • C:\xampp\mysql\bin>mySql –u root –p • Password********* • Командата за изход от MySQLe: • mysql> quit ; 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>

  10. Основни команди на MySQL • MySQLе програмна система за управление на бази данни. • Базите данни са контейнери, които съхраняват информация в структуриран вид. • Всяка база данни се състои от една или повече таблици, които структурират данните в редове и колони. • Всяка колона в таблицата има наименование (етикет), който идентифицира какъв тип данни се съхраняват в полетата на таблиците. • Всеки ред съдържа запис за определен обект. • При инсталацията на MySQL по подразбиране се създават две бази данни – едната е празна с наименование „test” и една с наименование „mysql”, в която се съхранява служебна информация на MySQL. • За да се види какви бази от данни съществуват под управлението на MySQL се използва команда: • mysql> show databases;

  11. Основни команди на MySQL • Ако не са създадени други бази от данни то конзолният екран за тази команда би изглеждал така: • Създаването на нова база данни се извършва с помощта на командата: • mysql>create database testdb ; • При успешно създаване на база данни, за да се работи с нея тя трябва да се направи активна (да се избере). • Това става с помощта на командата: • мysql> usetestdb ; mysql>show databases ; -------------- |Database | -------------- |mysql | |test | -------------- 2 rows in set (0.00 sec)

  12. Основни команди на 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; …………….

  13. Основни команди на MySQL • Може да се използва SQLкомандата ‘explain’ (обяснение) за да се види формата на таблицата. • Тази команда показва всички имена на колони в таблицата и подробностии за данните, които се съдържат в тях. • Друга важна дейност на MySQLе осигуряване на сигурност на данните. • Хакерите са твърде находчиви в опитите си да проникнат и да използват информацията в Internet. • MySQLдава възможност да се изберат кои потребители, какви функции могат да изпълняват с информацията в базата данни на основата на ‘привилегии’. • Цялата тази информация се съхранява в база от данни, наречена mysql, която по подразбиране се намира в папката: C:\xampp\mysql\data.

  14. Основни команди на MySQL • Ако за работа с базите данни има само един потребител с достъп до MySQL, тогава не необходимо добавянето на други потребители и задаване на привилегии. • В повечето случаи се налага с базата данни да работят и други потребители, които могат да имат различни задачи при работата с информацията в базите данни. • Някои може само да разглеждат информацията, други да въвеждат определен тип данни, трети да могат да създават и изтриват таблици и т.н. • Поради тази причина трябва да се въведат и други потребители, които да имат достъп до MySQL, като за всеки от тях се уточни какви права има по отношение на базата данни. • За целта се използват няколко команди на MySQL, които се изпълняват от ‘root’ потребителя (администратора).

  15. Основни команди на MySQL • Създаване на нов потребител. • Използва се следната команда в MySQL монитора: • С тази команда се създава потребител ‘testadmin’, данните за който са записани в таблицата ‘user’ от служебната база данни '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) mysql>insert into db (host, user, db) values (‘localhost’,’testadmin’,’testbd’) ; Query OK, 1 row affected (0.03 sec) mysql>

  16. Основни команди на MySQL • С изпълнението на тази команда на потребителят ‘testadmin’ се дава достъп до базата данни 'testdb’. • Все още не са уточнени какви привилегии има той по отношение на таблиците, намиращи се в базата данни. За да се уточнят привилегиите на потребителя се използват команди от типа: • С тази команда се задават привилегии SELECT, INSERT, UPDATEна потребителя ‘testadmin’ за база от данни ‘testdb’. Вместо изброяване на конкретни привилегии може да се запише 'all’, което означава, че се задават всички привилегии дефинирани в MySql;. mysql> GRANT SELECT, INSERT,UPDATE, -> ON testdb.* -> testadmin -> [IDENTIFIED BY ‘testpass’] -> [with grant option]; Query OK. 0 rows affected (0.44 sec) mysql> …………….

  17. Основни команди на MySQL • Привилегиите могат да се зададат на потребителя за всички бази от данни, ако вместо ‘testdb’ се използва символа '*'. • Последните два елемента от командата, зададени в квадратни скоби, са незадължителни. • Спесификацията от последния ред 'withgrantoption’ се използва, когато потребителят може да предоставя част от своите привилегии на други потребители. • Другият начин за задаване на привилегии, специфични за конкретна база данни 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> …………….

  18. 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.

  19. Privileges • SELECT allows users to select (read) records from tables. • INSERTallows users to insert new rows into tables. • UPDATEallows users to change values in existing table rows. • DELETEallows users to delete table rows (records). • INDEXallows user to index tables • ALTERallows users to change the structure of the database. - Adding columns - Renaming columns or tables - Changing the data types of tables • DROPallows users to delete databases or tables. • CREATEallows 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. • USAGEallows users nothing. • ALLmeans just that.

  20. MySQL DataBase • This is how we open and close a MySQL database:  • <?php    $link = mysql_connect("mysql_host", "mysql_login", "mysql_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 quarymysql_close($link); ?> 

  21. 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”);

  22. 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.

  23. 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.

  24. Step 4 & 5: Iterating through eachrow 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");

  25. 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) - Get a result row as an enumerated array  • mysql_fetch_array($result) - Fetch a result row as an associative array. 

  26. 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, name TEXT not null ,  comment TEXT not null , PRIMARY KEY (id), INDEX (id), UNIQUE (id))  

  27. MySQL example : guest book - the form • gustbook1.php • Please sign my guestbook : <form action="guestbook2.php" method="post">  Name: <input type="text" name="guestname"><br>  your comment: <input type="text" name="comment"><br>  <input type="submit"><br> </form> <br> <table border=1>  <tr>   <td>    <B>name</b>   </td>   <td>    <b>comment</b>   </td>  </tr>  

  28. 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',comment='$comment'";     mysql_query ($query) or die ("Query failed: $query<br>" . mysql_error()); ?> 

  29. 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.

  30. 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

  31. Creating a Table • <?php • $link = mysql_connect ('localhost','root','') • or die ('Could not connect') ; • print ('Connection successfully <br>'); • 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 <br>'); • 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 <br>'); • ?>

  32. 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")."<br>"; • } • ?>

  33. 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"] . "<br>"; //echo $row[2]; • } • ?>

  34. 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.

  35. 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"); ?>

  36. 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.

  37. 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.

  38. 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 studentsVALUES • (‘Maria Stoyanova',20)”); • mysql_query(“INSERT INTO studentsVALUES • (‘Dimitar Kalev',20)”); • These are hard coded examples – but we could be using variables • in these statements

  39. 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.

  40. 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 studentsWHERE age<25); • print mysql_num_rows().“ studentsare 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

  41. 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()."<BR>"; • Note: this function does not work with SELECT statements - only on statements which modify records.

  42. 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.

  43. 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?

  44. 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['email']"; • }

  45. 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']"; • }

  46. 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

  47. 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

  48. Adding Actionable Hyperlinks 1/2) • <table> • <tr> • <th>First Name</th> <th>Last Name</th> <th>Email</th> • <th>Actions</th> • </tr> • <?php • $conn = mysql_connect("localhost", "root", “"); • mysql_select_db("AddressBook", $conn); • $result = mysql_query("select * from contacts"); • while ($row = mysql_fetch_array($result)) { • print “<td>" . $row["LastName"] . "</td>"; • print “<td>" . $row["email"] . "</td>"; • print “<td><a href='remove.php?id=".$row["ID"]."'> • Remove </a></td>"; • print "</tr>"; } • mysql_close($conn);

  49. Adding Actionable Hyperlinks 2/2) • <?php • $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"; • } • ?>

  50. Interaction with the User • Populate form fields with information from database • Send the user input to PHP script for storing in the Database

More Related