Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
HOPE PHP & MySQL Stewart Blakeway FML 213 [email protected] www.hope.ac.uk Faculty of Sciences and Social Sciences What will we cover • Basic SQL commands HOPE – Inserting Records – Selecting Records – Filtering Records • Some formatting of controls and displaying of data www.hope.ac.uk Faculty of Sciences and Social Sciences Why HOPE • As part of your assessment you will be expected to 1. Create a link to the SQL Server 2. Select a database 3. Talk to the database (retrieve, add, append, etc) www.hope.ac.uk Faculty of Sciences and Social Sciences Data Types HOPE • MySQL uses all the standard numeric data types. • Some you will have come across – – – – – INT TINYING SMALLINT MEDIUMINT BIGINT – FLOAT – DOUBLE -2147483648 to 2147483647 -128 to 127 or 0 to 255 -32768 to 32767 or 0 to 65535 -8388608 to 8388607 or 0 to 16777215 -9223372036854775808 to 9223372036854775807 or 0 to 18446744073709551615 -10,2 up to 24 places -16,4 up to 53 places www.hope.ac.uk Faculty of Sciences and Social Sciences Date and Time Types • DATE • DATETIME HOPE • TIMESTAMP • TIME • YEAR(x) - A date in YYYY-MM-DD format - A combination of both the date and the time, in YYYY-MM-DD & HH:MM:SS - Similar to DATETIME with hyphens an colons omitted - A time in format HH:MM:SS - The year, the length is specified by x. www.hope.ac.uk Faculty of Sciences and Social Sciences String Types HOPE CHAR (x) VARCHAR (x) BLOB or TEXT TINYBLOB or TINYTEXT MEDIUMBLOB or MEDIUMTEXT LONGBLOB or LONGTEXT ENUM www.hope.ac.uk Fixed length Variable length Max of 65535 chars Max of 255 chars Max of 255 chars Max of 255 chars A list with a max 65535 values Faculty of Sciences and Social Sciences MySQL HOPE • In order to complete your assignment you will need to create a database • The database will be empty, the structure you will need to define • The database and the tables should be named appropriately • The fields within the database should be of a suitable type www.hope.ac.uk Faculty of Sciences and Social Sciences Talking to the DATBASE HOPE 1. 2. 3. 4. Create a connection with the SQL Server Select the appropriate database Construct the SQL Query Execute the SQL Query Have you created the DATABASE yet? Although you could use SQL statements to create the database and the tables within the database, a utility called phpMyAdmin offers an GUI to do the same task. www.hope.ac.uk Faculty of Sciences and Social Sciences 1. The Connection mysql_connect($host,$user,$password) HOPE • host is the SQL server address • user is the username to login to the database • password is the password associated with the username www.hope.ac.uk Faculty of Sciences and Social Sciences 1. The Connection Syntax • Storing and testing the connection HOPE $conn = mysql_connect (“localhost",“root","") or die(mysql_error()); echo $conn; • Should echo out: Resource id #1 or Resource id #2 www.hope.ac.uk Faculty of Sciences and Social Sciences 2. Selecting the database HOPE • There could be many databases on the SQL server. You need to ensure you select the correct one: mysql_select_db(database,connection) • database is the name of the database • connection is the connection parameters to connect to the SQL server as seen in the previous slide www.hope.ac.uk Faculty of Sciences and Social Sciences http://hopelive.hope.ac.uk 2. Selecting the database Syntax HOPE • There could be many databases on the SQL server. You need to ensure you select the correct one: mysql_select_db(“student",$conn) or die(mysql_error()); www.hope.ac.uk Faculty of Sciences and Social Sciences 3. Constructing the SQL Query • To interact with the database you construct standard MYSQL statements HOPE $sql = “CREATE TABLE tablename ( fieldname1 datatype, fieldname2 datatype )”; www.hope.ac.uk Faculty of Sciences and Social Sciences 4. Executing the SQL Query $sql = "CREATE TABLE student( studentId int not null primary key, surname varchar (25), HOPE firstname varchar (25) )"; String Variable mysql_query ($sql, $conn); PHP command to The variable that The variable that run the SQL contains the SQL contains the connection www.hope.ac.uk Faculty ofsettings Sciences and Social Sciences Retrieving Error Messages • To ensure that the SQL works you can retrieve error messages and display them! HOPE $result = mysql_query ($sql, $conn) or die(mysql_error()); echo $result; die is optional for all mysql statements www.hope.ac.uk As is mysql_error Faculty of Sciences and Social Sciences So far! HOPE • We have connected to the SQL Server • We have selected the correct database • We have created a table called student with 3 fields. • studentId • surname • firstname www.hope.ac.uk Faculty of Sciences and Social Sciences http://hopelive.hope.ac.uk All together $conn = mysql_connect (“localhost",“root",""); HOPE mysql_select_db(“student",$conn); $sql = "CREATE TABLE student( studentId int not null primary key, surname varchar (25), firstname varchar (25) )"; mysql_query ($sql, $conn); www.hope.ac.uk Faculty of Sciences and Social Sciences Inserting DATA The next step is to insert data into your table. $sql = "INSERT INTO student VALUES ( HOPE ‘100100100’, ‘Blakeway’, ‘Stewart’ )"; mysql_query ($sql,$conn) or die(mysql_error()); www.hope.ac.uk Faculty of Sciences and Social Sciences Unlikely! HOPE • It is very unlikely that you will enter predetermined data into a database • This is very useful for testing purposes • More likely you will need to obtain the data via the user • How do we achieve this? www.hope.ac.uk Faculty of Sciences and Social Sciences 2 Methods HOPE • Create the form in html and send the data to another file – we have all been doing this already • Create the form in php and send the data to the same file – it is easier to work with one file rather than switching between two www.hope.ac.uk Faculty of Sciences and Social Sciences if ($_POST[viewed] != "yes") { echo “<form method=\"POST\“ action=\"$SERVER[PHP_SELF]\"> <input type=\"hidden\“ name=\"viewed\" value=\"yes\"> </form>”; HOPE } else { } Alternative method. Both the get data and the do data are contained within the one file www.hope.ac.uk Faculty of Sciences and Social Sciences http://hopelive.hope.ac.uk Using Forms HOPE if ($_POST[op]!="viewed") { echo "<form id=\"form1\" name=\"form1\" method=\"post\" action=\"$_SERVER[PHP_SELF]\"> Student ID Number <input type=\"text\" name=\"studID\" /> <br /> Student Forename <input type=\"text\" name=\"studFN\" /> <br /> Student Surname <input type=\"text\" name=\"studSN\" /> <br /> <input type=\"hidden\" name=\"op\" value=\"viewed\"> <input type=\"submit\" name=\"submit\" value=\"Add Record\"> </form>"; } www.hope.ac.uk Faculty of Sciences and Social Sciences Processing data from forms HOPE else // if it has then add the data { //set sql string using values as indicated by the form $sql = "INSERT INTO tblstudent VALUES ( '$_POST[studID]', '$_POST[studSN]', '$_POST[studFN]')"; } if (mysql_query($sql,$conn)) // is it valid? { echo "Record Added!"; } Why not use Can you spot else // if not die(mysql_error()) ? the error? { echo "Record not Added!"; } www.hope.ac.uk Faculty of Sciences and Social Sciences Retrieving Data HOPE • At some point you will want to retrieve the data from the database. Immediately after you insert data for the first time would be a good time! $sql = "SELECT * FROM student“; $result = mysql_query ($sql,$conn); • Where does the data go? www.hope.ac.uk Into a RESOURCE Faculty of Sciences and Social Sciences Getting the data from the RESOURCE HOPE $newArray = mysql_fetch_array($result); $newArray = array ( “studentId” => “05004343”, “surname” => “Blakeway”, “firstname” => “Stewart” ) PHP Function to fetch data from the RESOURCE The RESOURCE www.hope.ac.uk Faculty of Sciences and Social Sciences Moving through multiple records HOPE • Dealing with more than one record! while ($newArray = mysql_fetch_array($result)) { $sn = $newArray[‘surname’]; echo $sn . “<br />”; } www.hope.ac.uk Faculty of Sciences and Social Sciences Combo Boxes HOPE • As you can see from the last slide each surname is displayed on screen • What if you wanted to put the names in a big list for the user to select one? • This is fairly straightforward once it has been thought through www.hope.ac.uk Faculty of Sciences and Social Sciences Overall structure of the page! if ($_POST[viewed] != "yes") { HOPE // display the form // allow user to choose a record } else { // display what was selected } www.hope.ac.uk Faculty of Sciences and Social Sciences Forms! HOPE <form> <select name=“list”> <option value=“surname 1”> <option value=“surname 2”> <option value=“surname …”> </select> </form> How many surnames will there be? www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE 3 Steps 1. First bit of the form 2. THE LOOPING (SURNAMES or whatever) 3. The last bit of the form www.hope.ac.uk Faculty of Sciences and Social Sciences The first bit echo "<form method=\"POST\“ action=\"$SERVER[PHP_SELF]\"> HOPE Select a Record to View <select name=\"sel_SN\"> <option value=\"\">-- Select One --</option>"; www.hope.ac.uk Faculty of Sciences and Social Sciences The complicated bit HOPE while ($newArray = mysql_fetch_array($result)) { $sn = $newArray[‘surname’]; echo "<option value=\"$sn\"> $sn</option>"; } www.hope.ac.uk Faculty of Sciences and Social Sciences The end bit echo =" </select> HOPE <input type=\"hidden\" name=\"viewed\" value=\"yes\"> <input type=\"submit\" name=\"submit\" value=\"View Selected Entry\"> </form>"; www.hope.ac.uk Faculty of Sciences and Social Sciences Overall structure of the page! if ($_POST[viewed] != "yes") { // display the form HOPE } else { // display what was selected } www.hope.ac.uk Faculty of Sciences and Social Sciences Displaying the specific record or the ELSE section HOPE 1. 2. 3. 4. 5. 6. Create a connection to the SQL Server Select the required database Construct the SQL Execute the SQL Extract the required data Display the record www.hope.ac.uk Faculty of Sciences and Social Sciences 3. Constructing the SQL HOPE • Now we have specific criteria for data that needs to be SELECTED from our record set $sql = "SELECT * FROM student"; $sql = "SELECT * FROM student WHERE surname = '$_POST[sel_SN]'"; www.hope.ac.uk Faculty of Sciences and Social Sciences 4. Executing the SQL $result = mysql_query ($sql, $conn); HOPE A variable to hold the results of executing the SQL The PHP command to execute an SQL statement www.hope.ac.uk The variable containing SQL statement The variable containing the connection settings Faculty of Sciences and Social Sciences 5. Extracting the required data from the results while ($newArray = mysql_fetch_array($result)) { $studID = $newArray[‘studentId’]; HOPE $studFN = $newArray[‘firstname’]; $studSN = $newArray[‘surname’]; } www.hope.ac.uk Faculty of Sciences and Social Sciences 6. Displaying the Record echo $studFN.$studSN.$studID; HOPE or echo “<table><tr><td>Id Number</td><td>Forename</td><td>s urname</td><tr> <tr><td>$studID</td><td>$studFN</td ><td>$studSN</td></tr></table>”; www.hope.ac.uk Faculty of Sciences and Social Sciences What have we covered? HOPE 1. 2. 3. 4. 5. 6. Create a connection to the SQL Server Select the required database Construct the SQL Execute the SQL Extract the required data Display the record www.hope.ac.uk Faculty of Sciences and Social Sciences Class Exercise (time permitting) HOPE • Create a function called nowAdd that will add the data obtained from a form to a database called dbCourse. • • • • • Posted name attributes are: fName, sName Database table is: tblStudent SQL server is located at: localhost SQL Username is: tutor SQL Password is: mypw www.hope.ac.uk Faculty of Sciences and Social Sciences Spot the errors HOPE $sql = “CREATE TABLE tablename ( fieldname1 varchar(30), fieldname2 varchar(30), ) www.hope.ac.uk Faculty of Sciences and Social Sciences Spot the errors HOPE while ($newArray == mysql_fetch($result)) { $studID => $newArray[‘studentID’]; $studFN => $newArray[‘firstname’]; $studSN => $newArray[‘surname’]; }; www.hope.ac.uk Faculty of Sciences and Social Sciences What next? • Independent Study: http://www.w3schools.com/sql/default.asp HOPE • Begin database design and implementation for assessment www.hope.ac.uk Faculty of Sciences and Social Sciences HOPE Any Questions? www.hope.ac.uk Faculty of Sciences and Social Sciences