Monday, November 21, 2016

Notes to W11 Forms

The task is, basically, in the combination of my post "Simple PHP form explained" with Demo File from week 11.
In the first post, cited above,  I showed how in the processing program defined in the action parameter of the form you should use $_POST[...] for getting access to the values in the form.
So you just need to declare some PHP variables and get those values into them, like:
$name = $_POST["name"];
....
If in the form you had a field name as "name".

After that you use the part from from the Demo File (only one INSERT statement) but instead of the hard coded values  - use the variables from shown above with values from the form

...

 mysql_query("INSERT INTO people (FirstName, LastName, Age) 
 VALUES ('$name', and other similar variables here)");


The reading program is actually in the same Demo File after the comment:

 //Read the result

 $result = mysql_query("select * from people");

 if (!$result)
   {
   die('Could not read: ' . mysql_error());
   }
   echo "got records!";

 echo "Passed!";

 while($row = mysql_fetch_array($result))
   {
   echo $row['FirstName'] . " " . $row['LastName'];

   }

 mysql_close($con);

   echo "Finished";
 ?>

You just need to use this code in a separate program where you first select the database (all my code from the Demo File up to the couple of INSERT statements) and then skipping INSERT statements in the Demo File use the code after    "//Read the result " comment.

And that's it!


Make this lab work (who couldn't ) to get the grade that you deserve, resubmit the forum and the assignment A11.2 and email me about the completion. Your grade might be somewhat increased but, what is more important, you will be able to get a better course grade. Otherwise, even if all other labs work - it cannot be more than a B, since this lab uses cumulative knowledge from the previous weeks on PHP and MySQL.

Alternatively, you can use the code from w3schools where the same form file was calling itself for processing (I described it in my another post), but still will need to use the variables taking info from $_POST[...] method. But I think what I showed above is simpler (but for real life code remember that for simplicity in the shown code we didn't use protection against PHP injection as described on w3schools site).

Ajax with Database

In this video, I am giving more explanations to the examples from w3schools.
These examples combine all main parts that you've learned in the course in some real life examples using XML and SQL database on the server side working together with HTML, JavaScript and AJAX on the server side.

Note that in my example I added the check of the parameter passed from AJAX to the PHP file:

<?php
$q=$_GET['q'];
// check what has been passed as "q"
echo "parameter". $q;

So if you have a message "parameter " and nothing in it - this means that the q parameter was not passed to the PHP file. Please check the whole chain of getting the value into q and properly passing it to php.

For debugging purposes, you can test your PHP files separately to see if your table and the KEY search field work in the SELECT statement. For this just start your PHP file, where you can comment $q out:

// $q=$_GET['q'];

And after that your SELECT statement  formed with WHERE clause and directly inserted field value should return a record corresponding to that value. Just use your own table name after the connection to your database works correctly:

$sql="SELECT * FROM user WHERE id = 'your key/unique field name'";

If  $result = mysqli_query($con,$sql); will not return anything  - you can check the same SELECT command manually from the SQL section of phpMyAdmin interface to see if the database, table, and key field names where spelled properly.

Wednesday, November 16, 2016

Simple PHP security

Although PHP security is outside of this course, I want to say a few words about it.
There are a number of JS and PHP attacks possible. Code injection is only one of them. Everybody is solving it differently (yes, usually checking the string for suspicious characters) since all possible inputs have different possible dangers. If you want something simple and you have a string input like "name" then you can check for the existence of various tags that shouldn't be there but might redirect the code if placed into the input doing something like:

$name = strip_tags( trim( $_POST[ 'name' ] ) );

The functions functions strip_tags() strips all HTML and PHP tags from a variable. Since we know that name is just the name of a person, and does not need links, or possibly malicious code, we don’t need any tags. So if a person was to add <a href=”http://www.mysite.com”>Mary</a>, it would only let the string ‘Mary’ to be assigned to the variable. The trim() function just strips any white space from beginning and end of the string ( actually it can do more - just google it for the future).

Monday, November 7, 2016

SQL Exercises

After reading the recommended materials about relational databases you can learn/try the use of SQL language for table manipulation. A simple way of trying SQL out  is shown in this video.

Monday, October 31, 2016

Simple PHP form explained

Creation of  a pair of programs dealing with forms is very simple. The first program can be just an HTML file with the form and a reference to the second program processing this form on the server (in our case using PHP). Please watch the video on how to do this.

Wednesday, October 26, 2016

Code explanation for Ajax with XML lab

The required work with Ajax and XML using examples from w3schools  might require some clarifications on how each line of code there works. Understanding this clearly you can somehow reuse the code dynamically creating HTML code for certain parts of the page (like a table) for presenting XML data. Explanations in this video will also allow you to make the examples more complicated and thus learn more.

Ajax code made simple

An HTTP request consists of four parts:


the HTTP request method or "verb" (GET or POST)
the URL being requested
an optional set of request headers, which may include authentication information
an optional request body

The "GET" and "POST" methods are universally supported. "GET" is used for most "regular" requests, and it is appropriate when the URL completely specifies the requested resource, when the request has no side effects on the server, and when the server’s response is cacheable. The "POST" method is what is typically used by HTML forms. The parts of an HTTP request have a specific order: the request method and URL must come first, then the request headers, and finally the request body. XMLHttpRequest implementations generally do not initiate any networking until the send() method is called.

The HTTP response sent by a server has three parts:

a numeric and textual status code that indicates the success or failure of the request (good to check)
a set of response headers (you do not have to use these)
the response body (your information from the server)
 

Below is the code example used in this video lecture

 

 

<!DOCTYPE html>
<html>
<head>

<script>
function loadData()
{
var xhr;
xhr=new XMLHttpRequest();
xhr.onreadystatechange=function()
{
if (xhr.status==200 && xmlhttp.readyState==4 )
{document.getElementById("myDiv").innerHTML=xhr.responseText;}
}
xhr.open("GET","ajax_info.txt",true); // or just xhr.open("GET", url);
xhr.send(); // GET requests never have a body, so pass null or omit 
}
</script>

</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadData()">Change Content</button>
</body>
</html>



XMLHttpRequest Properties

onreadystatechange
An event handler for an event that fires at every state change.
readyStateThe readyState property defines the current state of the XMLHttpRequest object.
Here are the possible values for the readyState propery:


State

Description
0The request is not initialized
1The request has been set up
2The request has been sent
3The request is in process
4The request is completed and data received


readyState=0 after you have created the XMLHttpRequest object, but before you have called the open() method.
readyState=1 after you have called the open() method, but before you have called send().
readyState=2 after you have called send().
readyState=3 after the browser has established a communication with the server, but before the server has completed the response.
readyState=4 after the request has been completed, and the response data have been completely received from the server.
responseText
Returns the response as a string.
responseXML
Returns the response as XML. This property returns an XML document object, which can be examined and parsed using W3C DOM node tree methods and properties.
status
Returns the status as a number (e.g. 404 for "Not Found" and 200 for "OK").
statusText
Returns the status as a string (e.g. "Not Found" or "OK").