musicmarkup.info Tutorials PHP MYSQL TUTORIAL PDF

PHP MYSQL TUTORIAL PDF

Thursday, March 26, 2020 admin Comments(0)

PHP i. About the Tutorial. The PHP Hypertext Preprocessor (PHP) is a programming language that allows web programming, Internet, Database, and MySQL. Do you want a simple reference on PHP CRUD Tutorial, or how to do CRUD Coding CRUD with PHP and MySQL is one of the basics. PHP. 3. MySQL. ▫. Sistema de Gestión de Base de Datos Relacional. ▫. La información Crear gráficos (PDF) del esquema de la base de datos. ▫. Exportar a.


Author:MILFORD KENNAMORE
Language:English, Spanish, Dutch
Country:Botswana
Genre:Lifestyle
Pages:735
Published (Last):06.01.2016
ISBN:284-7-23284-409-1
ePub File Size:24.49 MB
PDF File Size:10.78 MB
Distribution:Free* [*Sign up for free]
Downloads:25902
Uploaded by: ELENOR

O'Reilly Media, Inc. Learning PHP, MySQL, JavaScript, and CSS, the image of .. bring this revised, updated, and improved web development tutorial to fruition. This manual describes the PHP extensions and interfaces that can be For help with using MySQL, please visit either the MySQL Forums or. TASK 7 - The switch statement. PHP Tutorial 4 – Arrays and Loops. Part 1- Creating Arrays. Indexed arrays. Associative arrays. Assigning a range of.

For instance for storing pdf documents or images to make som kind of online briefcase like Yahoo briefcase. For the first step, let's make the table for the upload files. The table will consist of. BLOB is a binary large object that can hold a variable amount of data. First you need to upload the file to the server then read the file and insert it to MySQL. For uploading a file we need a form for the user to enter the file name or browse their computer and select a file. Example : upload.

This makes it easier to discover the error. Information sent from a form with the GET method is visible to everyone it will be displayed in the browser's address bar and it has limits on the amount of information to send max.

When the user clicks the "Submit" button, the URL sent could look something like this: So this method should not be used when sending passwords or other sensitive information! However, because the variables are displayed in the URL, it is possible to bookmark the page.

This can be useful in some cases. Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. When the user clicks the "Submit" button, the URL will not contain any form data, and will look something like this: However, because the variables are not displayed in the URL, it is not possible to bookmark the page. Syntax date format,timestamp.

Specifies the format of the timestamp Optional. Specifies a timestamp. Default is the current date and time as a timestamp.

A timestamp is the number of seconds since January 1, at This is also known as the Unix Timestamp. It uses letters to represent date and time formats. Here are some of the letters that can be used: The output of the code above could be something like this: This parameter is optional. If you do not supply a timestamp, the current time will be used. In our next example we will use the mktime function to create a timestamp for tomorrow. The mktime function returns the Unix timestamp for a specified date.

To go one day in the future we simply add one to the day argument of mktime: Server Side Includes You can insert the content of a file into a PHP file before the server executes it, with the include or require function. The two functions are identical in every way, except how they handle errors. The include function generates a warning but the script will continue execution while the require function generates a fatal error and the script execution will stop after the error.

These two functions are used to create functions, headers, footers, or elements that can be reused on multiple pages. Page 30 of This means that you can create a standard header or menu file that you want all your web pages to include.

When the header needs to be updated, you can only update this one include file, or when you add a new page to your site, you can simply change the menu file instead of updating the links on all web pages. The include Function The include function takes all the text in a specified file and copies it into the file that uses the include function.

Example 1 Assume that you have a standard header file, called "header. To include the header file in a page, use the include function, like this: Example 2 Now, let's assume we have a standard menu file that should be used on all pages include files usually have a ". Look at the "menu. The three files, "default. Here is the code in "default. And, of course, we would have to do the same thing for "about.

By using include files, you simply have to update the text in the "menu.

The require Function The require function is identical to include , except that it handles errors differently. If you include a file with the include function and an error occurs, you might get an error message like the one below. PHP code: Failed opening 'wrongFile. Notice that the echo statement is still executed! This is because a Warning does not stop the script execution. Now, let's run the same example with the require function. Error message: No such file or directory in C: Failed opening required 'wrongFile.

The echo statement was not executed because the script execution stopped after the fatal error. It is recommended to use the require function instead of include , because scripts should not continue executing if files are missing or misnamed. The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened: The file may be opened in one of the following modes: Starts at the beginning of the file Write only.

Opens and clears the contents of file; or creates a new file if it doesn't exist Append. Preserves file content by writing to the end of the file Write only. Creates a new file. If the fopen function is unable to open the specified file, it returns 0 false. Example The following example generates a message if the fopen function is unable to open the specified file: Closing a File The fclose function is used to close an open file: The feof function is useful for looping through data of unknown length.

You cannot read from files opened in w, a, and x mode! Reading a File Line by Line The fgets function is used to read a single line from a file. After a call to this function the file pointer has moved to the next line.

Other books: WICKED COOL PHP PDF

The example below reads a file line by line, until the end of file is reached: Reading a File Character by Character The fgetc function is used to read a single character from a file. After a call to this function the file pointer moves to the next character.

The example below reads a file character by character, until the end of file is reached: Create an Upload-File Form To allow users to upload files from a form can be very useful.

Look at the following HTML form for uploading files: Notice the following about the HTML form above: For example, when viewed in a browser, there will be a browse-button next to the input field Note: Allowing users to upload files is a big security risk.

Only permit trusted users to perform file uploads. Like this: For security reasons, you should add restrictions on what the user is allowed to upload. Restrictions on Upload In this script we add some restrictions to the file upload.

The user may only upload. Saving the Uploaded File The examples above create a temporary copy of the uploaded files in the PHP temp folder on the server. The temporary copied files disappears when the script ends. To store the uploaded file we need to copy it to a different location: The script above checks if the file already exists, if it does not, it copies the file to the specified folder.

This example saves the file to a new folder called "upload". What is a Cookie? A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values. How to Create a Cookie? The setcookie function is used to set a cookie. Syntax setcookie name, value, expire, path, domain ;.

In the example below, we will create a cookie named "user" and assign the value "Alex Porter" to it. We also specify that the cookie should expire after one hour: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received to prevent URLencoding, use setrawcookie instead. Example 2. You can also set the expiration time of the cookie in another way. It may be easier than using seconds. How to Retrieve a Cookie Value?

In the example below, we retrieve the value of the cookie named "user" and display it on a page: In the following example we use the isset function to find out if a cookie has been set: How to Delete a Cookie? When deleting a cookie you should assure that the expiration date is in the past. Delete example: If your application deals with browsers that do not support cookies, you will have to use other methods to pass information from one page to another in your application.

One method is to pass the data through forms forms and user input are described earlier in this tutorial. The form below passes the user input to "welcome. Retrieve the values in the "welcome.

PHP With MYSQL

Session variables hold information about one single user, and are available to all pages in one application. PHP Session Variables When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: A PHP session solves this problem by allowing you to store user information on the server for later use i.

However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database. Before you can store user information in your PHP session, you must first start up the session.

The code above will register the user's session with the server, allow you to start saving user information, and assign a UID for that user's session.

In the example below, we create a simple page-views counter. The isset function checks if the "views" variable has already been set. If "views" has been set, we can increment our counter. If "views" doesn't exist, we create a "views" variable, and set it to 1: The unset function is used to free the specified session variable: Description Required.

Specifies the subject of the email. This parameter cannot contain any newline characters Required. Defines the message to be sent. Lines should not exceed 70 characters Optional. Specifies additional headers, like From, Cc, and Bcc. Specifies an additional parameter to the sendmail program.

For the mail functions to be available, PHP requires an installed and working email system. The program to be used is defined by the configuration settings in the php.

Read more in our PHP Mail reference. This is a simple email message. The example below sends a text message to a specified e-mail address: This is how the example above works: First, check if the email input field is filled out If it is not set like when the page is first visited ; output the HTML form If it is set after the form is filled out ; send the email from the form When submit is pressed after the form is filled out, the page reloads, sees that the email input is set, and sends the email Note: This is the simplest way to send e-mail, but it is not secure.

In the next chapter of this tutorial you can read more about vulnerabilities in e-mail scripts, and how to validate user input to make it more secure. Page 47 of The problem with the code above is that unauthorized users can insert data into the mail headers via the input form. What happens if the user adds the following text to the email input field in the form? The mail function puts the text above into the mail headers as usual, and now the header has an extra Cc: When the user clicks the submit button, the e-mail will be sent to all of the addresses above!

The code below is the same as in the previous chapter, but now we have added an input validator that checks the email field in the form: In the code above we use PHP filters to validate input: An error message with filename, line number and a message describing the error is sent to the browser.

Page 50 of If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks. This tutorial contains some of the most common error checking methods in PHP.

Index of /pdf/Gentoomen Library/Databases/mysql/

We will show different error handling methods: Simple "die " statements Custom errors and error triggers Error reporting. Basic Error Handling: Using the die function The first example shows a simple script that opens a text file: If the file does not exist you might get an error like this: To avoid that the user gets an error message like the one above, we test if the file exist before we try to access it: The code above is more efficient than the earlier code, because it uses a simple error handling mechanism to stop the script after the error.

However, simply stopping the script is not always the right way to go. Let's take a look at alternative PHP functions for handling errors. Creating a Custom Error Handler Creating a custom error handler is quite simple. We simply create a special function that can be called when an error occurs in PHP. This function must be able to handle a minimum of two parameters error level and error message but can accept up to five parameters optionally: Specifies the error report level for the user-defined error.

Must be a value number. See table below for possible error report levels. Specifies the filename in which the error occurred Optional. Specifies the line number in which the error occurred. Specifies an array containing every variable, and their values, in use when the error occurred.

Error Report levels These error report levels are the different types of error the user-defined error handler can be used for: Page 52 of Description Non-fatal run-time errors. The code above is a simple error handling function.

When it is triggered, it gets the error level and an error message. It then outputs the error level and message and terminates the script. Now that we have created an error handling function we need to decide when it should be triggered. Page 53 of We are going to make the function above the default error handler for the duration of the script. It is possible to change the error handler to apply for only some errors, that way the script can handle different errors in different ways.

However, in this example we are going to use our custom error handler for all errors: Example Testing the error handler by trying to output variable that does not exist: The output of the code above should be something like this: Trigger an Error In a script where users can input data it is useful to trigger errors when an illegal input occurs. In this example an error occurs if the "test" variable is bigger than "1": Value must be 1 or below in C: An error can be triggered anywhere you wish in a script, and by adding a second parameter, you can specify what error level is triggered.

Possible error types: Errors that can not be recovered from. User-generated run-time notice. The script found something that might be an error, but could also happen when running a script normally. Now that we have learned to create our own errors and how to trigger them, lets take a look at error logging. Sending errors messages to yourself by e-mail can be a good way of getting notified of specific errors.

Send an Error Message by E-Mail In the example below we will send an e-mail with an error message and end the script, if a specific error occurs: And the mail received from the code above looks like this: This should not be used with all errors. Regular errors should be logged on the server using the default PHP logging system. PHP Exception Handling Exceptions are used to change the normal flow of a script if a specified error occurs. Exception handling is used to change the normal flow of the code execution if a specified error exceptional condition occurs.

This condition is called an exception. This is what normally happens when an exception is triggered: The current code state is saved The code execution will switch to a predefined custom exception handler function Depending on the situation, the handler may then resume the execution from the saved code state, terminate the script execution or continue the script from a different location in the code We will show different error handling methods: Basic use of Exceptions Creating a custom exception handler Multiple exceptions Page 57 of Exceptions should only be used with error conditions, and should not be used to jump to another place in the code at a specified point.

Basic Use of Exceptions When an exception is thrown, the code following it will not be executed, and PHP will try to find the matching "catch" block. If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message. Lets try to throw an exception without catching it: The code above will get an error like this: Fatal error: Uncaught exception 'Exception' with message 'Value must be 1 or below' in C: Try, throw and catch To avoid the error from the example above, we need to create the proper code to handle an exception.

Page 58 of Proper exception code should include: Try - A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown" 2.

Throw - This is how you trigger an exception. Each "throw" must have at least one "catch" 3. Catch - A "catch" block retrieves an exception and creates an object containing the exception information Lets try to trigger an exception with valid code: Example explained: The code above throws an exception and catches it: The checkNum function is created.

It checks if a number is greater than 1. If it is, an exception is thrown Page 59 of The checkNum function is called in a "try" block 3. The exception within the checkNum function is thrown 4. Creating a Custom Exception Class Creating a custom exception handler is quite simple. We simply create a special class with functions that can be called when an exception occurs in PHP.

The class must be an extension of the exception class. The custom exception class inherits the properties from PHP's exception class and you can add custom functions to it.

Lets create an exception class: The new class is a copy of the old exception class with an addition of the errorMessage function. Since it is a copy of the old class, and it inherits the properties and methods from the old class, we can use the exception class methods like getLine and getFile and getMessage. The code above throws an exception and catches it with a custom exception class: The customException class is created as an extension of the old exception class.

This way it inherits all methods and properties from the old exception class 2. The errorMessage function is created. This function returns an error message if an e-mail address is invalid 3. The "try" block is executed and an exception is thrown since the email address is invalid 5.

The "catch" block catches the exception and displays the error message. Multiple Exceptions It is possible for a script to use multiple exceptions to check for multiple conditions. It is possible to use several if.. These exceptions can use different exception classes and return different error messages: The code above tests two conditions and throws an exception if any of the conditions are not met: The "try" block is executed and an exception is not thrown on the first condition 5.

The second condition triggers an exception since the e-mail contains the string "example" Page 62 of The "catch" block catches the exception and displays the correct error message If there was no customException catch, only the base exception catch, the exception would be handled there.

Re-throwing Exceptions Sometimes, when an exception is thrown, you may wish to handle it differently than the standard way. It is possible to throw an exception a second time within a "catch" block. A script should hide system errors from users. System errors may be important for the coder, but is of no interest to the user.

To make things easier for the user you can re-throw the exception with a user friendly message: The code above tests if the email-address contains the string "example" in it, if it does, the exception is re-thrown: The "try" block contains another "try" block to make it possible to rethrow the exception 5.

The exception is triggered since the e-mail contains the string "example" 6. The "catch" block catches the exception and re-throws a "customException" 7. The "customException" is caught and displays an error message If the exception is not caught in its current "try" block, it will search for a catch block on "higher levels". Uncaught Exception occurred. In the code above there was no "catch" block.

Instead, the top level exception handler triggered. This function should be used to catch uncaught exceptions.

MySQL Part 1 - English

Code may be surrounded in a try block, to help catch potential exceptions Each try block or "throw" must have at least one corresponding catch block Multiple catch blocks can be used to catch different classes of exceptions Exceptions can be thrown or re-thrown in a catch block within a try block. What is a PHP Filter? A PHP filter is used to validate and filter data coming from insecure sources.

To test, validate and filter user input or custom data is an important part of any web application. The PHP filter extension is designed to make data filtering easier and quicker.

Why use a Filter? Almost all web applications depend on external input. Usually this comes from a user or another application like a web service. By using filters you can be sure your application gets the correct input type.

Page 65 of You should always filter all external data! Input filtering is one of the most important application security issues. What is external data? Input data from a form Cookies Web services data Server variables Database query results. Functions and Filters To filter a variable, use one of the following filter functions: Since the integer is valid, the output of the code above will be: If we try with a variable that is not an integer like "abc" , the output will be: Page 66 of Validating and Sanitizing There are two kinds of filters: Validating filters: Are used to allow or disallow specified characters in a string No data format rules Always return the string.

Options and Flags Options and flags are used to add additional filtering options to the specified filters. Different filters have different options and flags. Like the code above, options must be put in an associative array with the name "options". If a flag is used it does not need to be in an array. Since the integer is "" it is not in the specified range, and the output of the code above will be: Check each filter to see what options and flags are available. Validate Input Let's try validating input from a form.

The first thing we need to do is to confirm that the input data we are looking for exists. In the example below, the input variable "email" is sent to the PHP page: Check if an "email" input variable of the "GET" type exist 2.

If the input variable exists, check if it is a valid e-mail address. Let's try cleaning up an URL sent from a form. First we confirm that the input data we are looking for exists. In the example below, the input variable "url" is sent to the PHP page: Check if the "url" input of the "POST" type exists 2. Filter Multiple Inputs A form almost always consist of more than one input field.

MySQL Part 1 - English

The received GET variables is a name, an age and an e-mail address: Example Explained The example above has three inputs name, age and email sent to it using the "GET" method: Set an array containing the name of input variables and the filters used on the specified input variables 2.

Page 70 of If the parameter is a single filter ID all values in the input array are filtered by the specified filter. If the parameter is an array it must follow these rules: Must be an associative array containing an input variable as an array key like the "age" input variable The array value must be a filter ID or an array specifying the filter, flags and options.

This way, we have full control of the data filtering. You can create your own user defined function or use an existing PHP function The function you wish to use to filter is specified the same way as an option is specified. What is MySQL? MySQL is a database. The data in MySQL is stored in database objects called tables. A table is a collections of related data entries and it consists of columns and rows.

Databases are useful when storing information categorically. A company may have a database with the following tables: Database Tables A database most often contains one or more tables. Each table is identified by a name e. Tables contain records rows with data. Below is an example of a table called "Persons": With MySQL, we can query a database for specific information and have a recordset returned. Look at the following query: The query above selects all the data in the "LastName" column from the "Persons" table, and will return a recordset like this: LastName Hansen Svendson Pettersen.

Perhaps it is because of this reputation that many people believe that MySQL can only handle small to medium-sized systems. The truth is that MySQL is the de-facto standard database for web sites that support huge volumes of both data and end users like Friendster, Yahoo, Google. Look at http: Page 73 of Parameter Description servername Optional. Specifies the server to connect to. Default value is "localhost: Specifies the username to log in with.

Default value is the name of the user that owns the server process Optional. Specifies the password to log in with. Default is "". There are more available parameters, but the ones listed above are the most important. The "die" part will be executed if the connection fails: Closing a Connection The connection will be closed automatically when the script ends. This function is used to send a query or command to a MySQL connection. Page 75 of The following example creates a table named "Persons", with three columns.

Page 76 of A database must be selected before a table can be created. When you create a database field of type varchar, you must specify the maximum length of the field, e. The data type specifies what type of data the column can hold. A primary key is used to uniquely identify the rows in a table. Each primary key value must be unique within the table. Furthermore, the primary key. The following example sets the personID field as the primary key field.

The first form doesn't specify the column names where the data will be inserted, only their values: The second form specifies both the column names and the values to be inserted: In the previous chapter we created a table named "Persons", with three columns; "Firstname", "Lastname" and "Age". We will use the same table in this example. The following example adds two new records to the "Persons" table: Here is the HTML form: When a user clicks the submit button in the HTML form in the example above, the form data is sent to "insert.

The "insert. Here is the "insert. The while loop loops through all the records in the recordset. Page 81 of If you want to sort the records in a descending order, you can use the DESC keyword. The following example selects all the data stored in the "Persons" table, and sorts the result by the "Age" column: Order by Two Columns It is also possible to order by more than one column. When ordering by more than one column, the second column is only used if the values in the first column are equal: Earlier in the tutorial we created a table named "Persons".

Here is how it looks: The following example updates some data in the "Persons" table: After the update, the "Persons" table will look like this: Look at the following "Persons" table: After the deletion, the table will look like this: Open the Administrative Tools icon in your Control Panel.

Choose the System DSN tab. Select the Microsoft Access Driver. Click Finish. In the next screen, click Select to locate the database. Click OK. Note that this configuration has to be done on the computer where your web site is located.

If you are running Internet Information Server IIS on your own computer, the instructions above will work, but if your web site is located on a remote server, you have to have physical access to that server, or ask your web host to to set up a DSN for you to use.

The function takes four parameters: The following example creates a connection to a DSN called northwind, with no username and no password. It then creates an SQL and executes it: This function returns true if it is able to return rows, otherwise false. The function takes two parameters: This function takes two parameters: The code line below returns the value of the first field from the record: The code line below returns the value of a field called "CompanyName": What is XML?

XML is used to describe data and to focus on what data is. An XML file describes the structure of the data. In XML, no tags are predefined. You must define your own tags. What is Expat? There are two basic types of XML parsers:. Tree-based parser: This parser transforms an XML document into a tree structure. It analyzes the whole document, and provides access to the tree elements. Views an XML document as a series of events. When a specific event occurs, it calls a function to handle it Page 91 of The Expat parser is an event-based parser.

Event-based parsers focus on the content of the XML documents, not their structure. Because of this, event-based parsers can access data faster than tree-based parsers.

Mysql pdf php tutorial

Look at the following XML fraction: However, this makes no difference when using the Expat parser. Expat is a non-validating parser, and ignores any DTDs. XML documents must be well-formed or Expat will generate an error. There is no installation needed to use these functions. Tove From: Jani Heading: Reminder Message: Don't forget me this weekend! How it works: Create functions to use with the different event handlers 3. Parse the file "test. What is DOM? It analyzes the whole document, and provides access to the tree elements Event-based parser: When a specific event occurs, it calls a function to handle it.

The DOM parser is an tree-based parser. Look at the following XML document fraction: Level 1: XML Document Level 2: Root element: Text element: Tove Jani Reminder Don't forget me this weekend! The url would look like download.

To see a working example click here. I saved several images in my database, you can try downloading them. We can use this id to identify which files to get from the database. They are : 1. Some browser need it to be able to download the file properly. Anyway it's a good manner telling how big the file is.

Pdf tutorial php mysql

That way anyone who download the file can predict how long the download will take. If you don't send this header the browser will try to save the file using the script's name download. After sending the file the script stops executing by calling exit. As for the error message above it happens because i "accidentally" add one space right after the PHP closing tag? So if you see this error message when you're sending a header just make sure you don't have any data sent before calling header.

Check the file mentioned in the error message and go to the line number specified Recent Comments By: eclehn Posted on AM Razorgum You have an exit statement before the code that downloads the file. I'm still new to PHP, but that might be the problem. By: prashant kumar Posted on AM I am facing problem at the time of downloading a file through database.

For this i have to taken realted id to whom i click "view" and sent to another php file. For that i have written a separate code which is given below download2. So, where is the problem plz give me some suggestion and correct code for this.