Presentation is loading. Please wait.

Presentation is loading. Please wait.

Tried my best to simplify it for you!

Similar presentations


Presentation on theme: "Tried my best to simplify it for you!"— Presentation transcript:

1 Tried my best to simplify it for you!
PHP & MySQL

2 PHP Functions There are two parts which should be clear to you:
Creating a PHP Function Calling a PHP Function

3 Sample </body> <html> <body>
<head> <title>Writing PHP Function</title> </head> <body> <?php /* Defining a PHP Function */ function writeMessage() { echo “Exam is knocking at the door,<BR> Are you ready?"; } /* Calling a PHP Function */ writeMessage(); ?> </body> </html> Exam is knocking at the door, Are you ready?

4 PHP functions with parameters
<html> <head> <title>Writing PHP Function with Parameters</title> </head> <body> <?php function addFunction($num1, $num2) { $sum = $num1 + $num2; echo "Sum of the two numbers is : $sum"; } addFunction(10, 20); ?> </body> </html> Would the answer still remain the same if this stmt was outside the function? Sum of the two numbers is : 30

5 Passing Arguments by Reference
A reference to the variable is manipulated by the function rather than a copy of the variable's value. Any changes made to an argument in these cases will change the value of the original variable. Add an ampersand to the variable name in either the function call or the function definition.

6 Pass by Reference <?php function addFive ($num) { $num += 5; }
function addSix (&$num) $num += 6; $x = 10; addFive ( &$x ); echo "Original Value is $x <br />"; addSix ( $x ); echo "Original Value is $x <br />"; ?> Original Value is 15 Original Value is 21

7 Functions returning a value
A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code.

8 Example <?php function addFunction($num1, $num2) {
$sum = $num1 + $num2; return $sum; } $return_value = addFunction(10, 20); echo "Returned value from the function : $return_value”; ?> Returned value from the function : 30

9 Highlights of the lecture
Creation of table Insertion of records Retrieval of records

10 What came first the egg or ….?
So what comes first the Table or the Database?

11 Creation of Database is a must
This is the very first step involved in your php-mysql operations.

12 Start up Server2Go

13 Conversation between Gary and Sumedha:
Hey good morning Sumedha! Sumedha: Watzz so good about the morning Gary ? The good thing about this morning is dat a gal called Sumedha is going to help me understand phpMyAdmin So what is phpMyAdmin? You can’t ask me the same question back again. I know that, so I was saying….. You were saying….. 1. phpMyAdmin is a tool . 2. It is open source and free 3. Allows you to view all the MySQL DB, tables and entries. Can we execute sql queries too? Ofcourse you can do so via the web browser.

14 Click on phpMyAdmin

15 On Successful Login… CollegeDB

16 On clicking Create, see what happens….

17 Sumedha decides to test the knowledge of Gary
Some basic questions Sumedha decides to test the knowledge of Gary Sumedha: What is MySQL? Gary: It is a database What does this database contain? The data in MySQL is stored in database objects called tables. What is a table? A table is a collection of related data entries and it consists of columns and rows. So you think your smart huh! Whats to think in that Sumedha? Ok Smarty, can you give me an example of a database? A company may have a database with the following tables: "Employees", "Products", "Customers" and "Orders". Howz that for you sweety? Ok ok, that answer has finally convinced me that you know your basics right.

18 Create a Connection to a MySQL Database
First creation of database along with a connection to it is a must. In PHP, this is done with the mysql_connect() function. Syntax mysql_connect(servername,username,password);

19 mysql_connect(servername,username,password);

20 What is $con? <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con)   {   die('Could not connect: ' . mysql_error());   } // some code ?>

21 OR <?php $con = mysql_connect("localhost","root",""); if($con) else
{ echo "Connection Successful"; } else { echo"Connection Error:".die(mysql_error()); } ?>

22 Closing the connection
Although, the connection will be closed automatically when the script ends. But to close the connection before, use the mysql_close() function: mysql_close($con);

23 Can we create a Database in php?
The CREATE DATABASE statement is used to create a database in MySQL. CREATE DATABASE database_name

24 Code: <?php $con = mysql_connect("localhost","root",""); if (!$con)
{ die('Could not connect: ' . mysql_error()); } if (mysql_query("CREATE DATABASE emp_db",$con)) { echo "Database was created"; } else echo "Error creating database: " . mysql_error(); mysql_close($con); ?>

25 Letz check and see if the Database was created?

26 The die() function The die() function prints a message and exits the current script. This function is an alias of the exit() function. Syntax: die(message);

27 Manually destroying a database

28 Adding tables to a database
Syntax of MySQL CREATE TABLE table_name ( column_name data_type, column_name data_type, column_name data_type, .... )

29 Php example code Create a database “emp_db”
Create a table called “tbl_employee” in the “emp_db” database. Fields of tbl_employee are as follows: emp_id emp_firstname emp_lastname emp_post

30 Code Part1 + Part2 Step 1: Connect to the mysql via php <?php
$con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } //code continues…

31 Step2: Creation of Database
if (mysql_query( "CREATE DATABASE emp_db1",$con)) { echo "Database created"; } else echo "Error creating database: " . mysql_error(); } //code continues…

32

33 Step 3: Creation of Table
mysql_select_db("emp_db1", $con); $my_query = "CREATE TABLE tbl_employee ( emp_Id int, emp_FirstName varchar(15), emp_LastName varchar(15), emp_post varchar(15) )"; // Execute query mysql_query($my_query,$con);

34

35 On Clicking Data Dictionary

36 Auto Increment of Id $my_query = "CREATE TABLE tbl_employee ( )";
mysql_select_db("emp_db1", $con); $my_query = "CREATE TABLE tbl_employee ( emp_Id int NOT NULL AUTO_INCREMENT, PRIMARY KEY(emp_id), emp_FirstName varchar(15), emp_LastName varchar(15), emp_post varchar(15) )";

37

38 Insert Data into a Database Table
The INSERT INTO statement is used to insert new records in a table. 2 ways of doing it: 1st form: Directly insert without specifying column names. 2nd form: Specify column names and values too.

39 Direct Insertion without column names
INSERT INTO table_name VALUES ( value1, value2, value3,...) To get PHP to execute the statements above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Insertion with THE use of column names INSERT INTO table_name (column1, column2, column3,...) VALUES ( value1, value2, value3,...)

40 Inserting Data mysql_select_db("emp_db1", $con);
$sql = "INSERT INTO tbl_employee (emp_FirstName, emp_LastName, emp_post) VALUES ('Frazer', 'Mascarenhas','Principal')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 record added";

41

42 Inserting data via html form+post
You need: An HTML form to read the data And a php form to process the data

43

44 27th September 2012 Recall: Set up a database called College_DB
Created a table called tbl_employee Having structure????? Inserted 2 records via html form.

45 Displaying Data via Selection

46 Select SELECT column_name(s) FROM table_name
mysql_query("SELECT * FROM tbl_employee");

47 mysql_fetch_array() function
Function used to return the first row from the recordset as an array. Each call to mysql_fetch_array() returns the next row in the recordset. A recordset is a data structure that consists of a group of database records, and can either come from a base table or as the result of a query to the table.

48 mysql_select_db("emp_db1", $con);
<?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("emp_db1", $con); $result = mysql_query("SELECT * FROM tbl_employee"); while( $row = mysql_fetch_array($result) ) echo $row['emp_FirstName'] . " " . $row['emp_LastName']; echo "<br />"; mysql_close($con); ?>

49 Role of -- The while loop
The while loop, loops through all the records in the recordset. To print the value of each row, we use the PHP $row variable ( $row[‘emp_FirstName'] and $row[‘emp_LastName']).

50 Display the Result in an HTML Table

51 $result = mysql_query("SELECT * FROM tbl_employee");
echo "<table border='1'> <tr> <th>Firstname</th> <th>Lastname</th> </tr>"; while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['emp_FirstName'] . "</td>"; echo "<td>" . $row['emp_LastName'] . "</td>"; echo "</tr>"; } echo "</table>";

52 $result = mysql_query("SELECT * FROM tbl_employee");
echo "<table border='1'> <tr> <th>Firstname</th> <th>Lastname</th> </tr>"; while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['emp_FirstName'] . "</td>"; echo "<td>" . $row['emp_LastName'] . "</td>"; echo "</tr>"; } echo "</table>";

53 Where Clause SELECT column_name(s) FROM table_name WHERE column_name operator value Use the mysql_query() function. This function is used to send a query or command to a MySQL connection.

54 $result = mysql_query("SELECT * FROM tbl_employee
<?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("emp_db1", $con); $result = mysql_query("SELECT * FROM tbl_employee WHERE emp_FirstName='Jyoti'"); while($row = mysql_fetch_array($result)) echo $row['FirstName'] . " " . $row['LastName']. " ". $row['post']; echo "<br />"; ?>

55 The ORDER BY Keyword The ORDER BY keyword is used to sort the data in a recordset. The ORDER BY keyword sort the records in ascending order by default. If you want to sort the records in a descending order, you can use the DESC keyword.

56 SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC
The following example selects all the data stored in the “tbl_employee" table, and sorts the result by the “emp_LastName" column

57 ORDER BY emp_LastName

58 Order by Two Columns SELECT column_name(s) FROM table_name ORDER BY column1, column2 possible to order by more than one column. the second column is only used if the values in the first column are equal

59 Order by emp_FirstName, emp_LastName


Download ppt "Tried my best to simplify it for you!"

Similar presentations


Ads by Google