PHP Day 15

Day 15



Submit Article Functionality:

Now we want to develop a functionality that will facilitate our website content or article authors to write and submit articles. So, let’s first create a link in our links.php file and give the file name here ‘submit_article.php’ and link text as Submit Article. Now let’s copy this file name as we need to create a PHP file with the same name. Let’s create a new PHP file and paste this name of file here and this is our new file that will be used to submit articles. Let’s close PHP tags as we need to write some HTML here. Let’s give heading ‘New Article’ as when author will click this link and will be on this page he will see this heading and will find a form below. I am just pasting a simple HTML page here. In this simple HTML form we have three fields ‘Title’ and ‘Name of Article’ are two input fields of type text and we have put a small PHP code for user friendliness as we did many times before. One text area that will contain the content of the article. This field also has the PHP code that will return the submitted content back to user if any error occurs and the user will get his whole content back in the fields. Let’s put some br tags between fields. Let’s view this form in browser and this is the form author will find when he will click on submit Article link.

Let’s code to get this form data and save it in Database. So, if the form is submitted only then echo ‘Article Submitted’ just to check if the form is being submitted correctly. Let’s check this in browser put some dummy data and submit and we get the message. So, let’s get back to the code and remove this message. Now, let’s use ‘EXTRACT’ internal function to grab all the values from this submitted form fields. Let’s write if condition to check if $title is empty and if it is, store an error in errors field, let’s declare errors array above. Store the concerned error for title in the errors array. And do this for all of the fields as we did many times before. Now, let’s create an ‘if’ statement and count values in errors array, and if there is count of values greater than 0, we will run foreach for errors array and show all the errors to the user. Now within this if statement, let’s count values in errors array and if it’s equals to 0, then we can insert this data in DB after sanitizing. So, we need to include two files on this page and those are sanitize and connection.php. Now let’s quickly sanitize all the fields and store them in variables.

Now, let’s write an insert query to insert these values in ‘articles’ table. ‘Insert into articles ()’ let’s go to the articles table. Here you can see we need ‘userID’ of this particular author to store along with his article. Also, we need to store ‘art_name’, ‘title’, ‘content’ and‘uploaded_on’ data. Let’s put all of these here. Now we need to get the ‘userID’ that’slittle tricky, but very helpful method. So, for this what we can do here is, at ‘login.php’ page when author will login we will store his ‘userID’ in a session and his userID will be available on all session pages.

Let’s get this userID from query. And just create another session, and name this session as ‘userID’ and its value is going to be the ‘userID’ we just stored in the variable from the query. So, we need to select ‘userID’ as well within our query, so, let’s just add this one here too. Let’s get back to submit_article.php page and start session on this page too. Now here we can simply have a variable ‘$userID’ and give it the value, that is the session ‘userID’. Now, let’s just echo all of these to check if everything is working fine. Comment this query out for the moment. Now get back to the browser. First thing we should do is logout and login back. As you should know that our newly defined userID session will be generated at the time of login. So, if we need it, we need to logout of this session and then log back in. So, let’s put the correct credentials and ‘Login’ and let’s go to ‘Submit Article’, fill this form with some dummy data and click ‘Publish’ and you can see we have all the values here. 1 you can see here is the ‘userID’ that we are grabbing from the session. Let’s go to the users table and this is the userID and that will be stored in session when any of the user will get logged in. Now we have everything sethere that is title, article name and content of the article. Now we are ready to fit all of these in our query to insert data in database. Uncomment the query. Remove all echo from here. In values $userID, and then in single quotes ‘$art_name’, ‘$title’, ‘$content’ and a ‘now()’ function to put the current date in mysql format. Just place the other stuff of catching the errors if any. Let’s just store this whole query within a variable $qr. Let’s write the if statement, if this query works and runs well then just echo ‘Article was submitted successfully.’ Otherwise echo ‘Some internal error. Please try later!’. Let’s go to the browser and put some dummy data for article again and submit. Here we have an error. OK, it’s spelling error, let’s correct it, go back to the browser, push F5 to resubmit the form and this time we get the success message.Let’s go to the ‘articles’ table and now you can see the data has been recorded successfully. We need links at the top of this page as well so, let’s include ‘links.php’ file at the top of its content. Now all the links are visible. Now one thing more here, if we logout, let’s click on logout. Try to go to ‘control panel’ but it’s not possible but if we try to go to submit article page, we can. Although we have already been logged out. So, we need to create the same functionality we created in index.php page.Also, as submit_article.php page is specifically for authors only so, we want to restrict admins to access this page as well. So, let’s do this now. Start session at the top and declare an ‘if’ statement. In this if statement first we would like to check, if not isset $_SESSION[‘role’], means if the session ‘role’ is not set, OR, I am using OR here as we would like to execute if statement if any of the conditions returns true, and the second thing we would like to check is the value of session ‘role’, if it’s not equals to 1. We set 1 for author in DB and let’s verify it one more time in table. This condition will restrict any role session that has value other than 1 to stay on this page. So, if any of these conditions returns true, this if statement will execute. In the execution area we are just writing a redirect statement. So, headers, Location and login.php. So, if any of the conditions returns true, either session ‘role’ is not set, or this session value is not equals to 1, this script will take the user out of here to login.php page.

Now this part of the code is specifically meant for authors. This code doesn’t allow any other user to stay on all of the pages where this code is written. So, we can cut this code from here and just create a new file, name it as ‘session_author’ so, we can guess what this file contains, and paste all of the code here. So, now we have a separate session file that is particularly meant to permit authors only, and we can require this file on any page. So, let’s just require this file here on submit_article.php file.

Now as the session has been terminated and we have placed the code in submit_article.php page, so let’s just refresh it and it sends us to login.php page. Now let’s login back again and now we can access ‘submit article’ page, let’s just copy link, and logout. Paste the link in address bar and you can see we have been sent to login page. This is all for ‘submit_article.php’ file.

 






Facilitate Author to View His submitted Articles:

Now we need a link for authors to facilitate them to view all of their submitted articles. So, let’s create this link first. Hyper reference is going to be ‘view_articles.php’ that we will create in a moment and text to show ‘View Articles’. So, this is the link authors will find in their control panel to view all of their articles. Let’s just copy this name and create a new PHP file with this same name, just paste it in here and click OK. So, this is our new file and we need all the files and session to be included here too. Let’s just copy all these from submit_article.php file and paste them in here. We can comment out this sanitize.php file as we don’t need it here. We are just going to show all the articles to the author.

So, here I have a simple HTML table with one row and three table headings inside it which are ‘Article Name’, ‘Title’ and ‘Content’. Below here we need another row that will contain the dynamic data. So, within this we need three table datas. Now we need a heading at the top of this table ‘All Your Articles’, and make it heading 1.  Let’s just browse to see the look of this table. Here is our ‘view_articles.php’ page and we don’t have links here, let’s just include ‘links.php’ file here too. Now we need to run MySQL query to get the concerned data out of the ‘crud’ database. So, mysql_query and all the stuff to chache the errors. “SELECT all From Articles where userID = ” and this userID, we can grab from the session we started when any user logs in, so, let’s grab it above here $_SESSION and that was userID and let’s just put this in a variable $userID and just put this variable insdie the select query. This is userID coming from the articles here, that is here and you remember we store it when author submits the article along with article content and other stuff. One particular author can have many articles so, we need to run a while loop to grab all the results out of this query. Store all the results in $row variable from mysql_fetch_assoc($qr) within parenthesis. Now, let’s grab the field values we want to show to this author and those are ‘art_name’, ‘title’ and content. Let’s just store all of these in variables. Now we need to bring this whole ‘tr’ within while loop. So, for each and every record a new ‘tr’ will be created and data will be displayed dynamically. So, let’s just cut it from here and within while loop let’s just close and open php tags to bring our HTML code here and let’s just paste it here and simply echo all of the variables using PHP shorthand method. Now, let’s get back to the browser and refresh ‘view_articles.php’ page. You can see our data is being displayed dynamically now. Let’s submit another article and see what happens. Here the message is messing up, let’s correct it. Let’s just move it in $errors array as well. Although it’s not an error but will be displayed at the right spot. Let’s post another article and click publish and this time the message is displayed at perfect place. Let’s go to ‘View Articles’ page and this is how any author can view his all articles. We can off-course and should provide facility to the author to update any of his articles if he made a mistake while writing and submitting the article, but for now that’s all for this session.




DevelopingFunctionalityfor Admin Account:

Now we want to create a user which has admin role and will be able to control other users like, admin will be able to view all other users’ information and can activate users waiting for approval. So, let’s register a new user first. Fill data in all fields and agree to terms and click ‘Register’ button. Now we have another user in our database. Here you can see the success message with some information. It’s also messed up. We can fix it as we did before, by just adding these two messages in $errors array. Now let’s go to ‘users’ table and here you can see we have the second user registered. So, here role is by default 1 that is specified for author, and 1 for is_active that this user is pending for approval. Let’s change this to 2, that makes it activated and let’s just change role to 2 that is defined for admin. So, now this user is activated and has become admin. Now let’s go to the browser and try to login. Put the correct credentials and it’s logged in. You can see the welcome message. Now, let’s just click ‘Submit Article’ link, that is only for authors and rightly so, it sends us to login page as admins don’t have access to this page. Let’s click ‘View Articles’ link and this sends us to login page as well. That’s perfectly fine. Now, if we click on ‘Control Panel’ link it takes us to Control Panel as we are logged in already. So, now we want to create functionality for the users having admin rights.





View All Users Functionality:

Now, let’s create a new link in ‘links.php’ file and give it a link text that is ‘All Users’ and give the hyper reference ‘users.php’. Let’s create this page now, just right click here and put users here. This is our users file. So, we are going to show all the users here as well as we will create functionality for admins to activate users who are pending approval. So, let’s start coding now.Put a heading here ‘All Users’. Now we need a table below here, let’s paste a partial table. This table has one row and 5 columns with headings ‘name’, ‘User Name’, ‘Joined On’, ‘Status’ and ‘Action’. Now let’s create another row and within this row we need 5 columns as well. Now, let’s get data out of the database, so here we need to write PHP code and run queries to get data out of database. So, we need few files to work with database. Let’s copy files to be included from ‘submit_article.php’ page and paste all of these right at top in here. This file here, ‘session_author.php’ is especially developed only for authors’ access. So, we don’t need it here but a same file that will be only for admins’ authentication. Let’s just copy all of the code of this file, create a new file that is session_admin.php and paste all the code here, and here we just need to append this 1 to 2. This is for admins only. Now, let’s go to the ‘users.php’ file and change this file name to session_admin.php. So, now this page is only accessible to admins’. Let’s go to the browser and check this functionality. Just refresh it and we have new link here. Let’s click it and you can see we are on ‘users.php’ page and its working fine. Here we don’t have any links to navigate to other pages. So, let’s just include links file here. Go back to the browser, refresh and now we have links menu at the top. Just to verify the functionality let’s logout and login back with author role. Now if we click ‘All Users’ link we are sent to login page. So, we are right on track. Although if we click ‘Submit Article’ we do have access, control panel and view all articles we can easily access these all. Only ‘All Users’ link is sending us to login page. Now again logout of this user and login back with admin role. Let’s click ‘All Users’ link. But when admin will click on ‘Submit Article’ he will be sent to login page and same is the case with ‘View Articles.’ Now let’s code to grab data to show in this table. Let’s start PHP tags. Within these tags, let’s write a MySQL query to select data. ‘Select all from users’. Let’s put this whole query in a variable $qr. Start while loop and put a variable $row and this is going to store each record coming from the query as an associative array. So, now we can grab all the values from each array of record. So, first is name, let’s just copy and paste for several times and change this to ‘username’, ‘email’, ‘joined’, ‘role’ and ‘is_active’. Let’s just store all of these values in variables. As you know we will get 1 or 2 for role so, we need to declare an ‘if’ statement and we need to check if, $role variable is equals to 1 then define $role as ‘Author’ otherwise we define $role as ‘Admin’. Same like this we need to declare an ‘if’ statement for ‘is_active’ variable. So, here in table you can see we have set 1 for pending users and 2 for active users, so, here if we get ‘is_active’ 1 we will assign value ‘Pending’ to a new variable ‘activation’ and if ‘is_active’ is other than 1, we assign value ‘Active’ to ‘activation’ variable. So, now we are ready to display all of these variables atrelativeplaces. We need to bring this whole table row within while loop up here. So, let’s cut it and within while loop close and open PHP tags and within this area, paste the table row. Now we can echo all the variables here we defined above using short hand PHP method. We also need ‘Role’ to show, so let’s create heading for this column and down here let’s just echo this out too. Let’s just create another table data here and write ‘Action’ here. Now is the time to go to the browser and click the link ‘All Users’ and here you can see we have a nicely formatted data and detailed list of all users we have in our database. Here you can see we have two types of users right now and all the details of these users. But in ‘Action’ column we have only written ‘Action’ right now. So, what we need here is, when any of the user is awaiting approval, a link will appear here to activate this user. So, admin will be able to click that link or tab and the concerned user will be activated. Let’s make one of our user’s status ‘Pending Approval’ by just changing this 2 to 1 and this user now is not activated. Let’s go to the browser and refresh and you can see in status column ‘Pending’ for this user. So, users having this pending status are in need to be activated by ‘Admin’. So, we need to create a link here. Let’s create it now and write a text ‘Activate’ here. Now here let’s just give a hash here to make it a link. Let’s go to the browser and now you can see, we have ‘Activate’ link against each user detail that is absolutely not correct. As we don’t need this link against the user that is already active like this one. So, we want this ‘Activate’ link appear only when the user is ‘Pending for Approval’. For this we just need to declare an ‘if’ statement. Let’s start PHP tags here and write ‘if’ and here we would just check ‘status’ is equals to 1, let’s confirms this variable above here and it’s ‘is_active’ variable. So, if ‘is_active’ variable is equals to 1, means, if the user is pending for approval, only then in the execution area this link will appear, and if this is not the case this link will not appear. Really simple. Let’s just close and open PHP tags and bring this link within this ‘if’ execution area. Let’s go to the browser and refresh and here we go, you can see link appears only with the user that is ‘Pending Approval’. So, now this is the link that an Admin will click and the ‘Pending for approval’ user will be activated. Let’s put a file name here, ‘activate_user.php’. This is a file that we’ll create in a moment and will process the request of user activation. Along with this link request we need to send the userID as well, for which the code will run to make it activate. Let’s just put ‘user_id’. The value is going to be the userID that we can grab out of this data too. Let’s create a variable ‘user_id’ and the value is that we are grabbing from the $row array and that is ‘userID’. So, let’s just copy this variable ‘$user_id’ and paste that here within PHP short code. Let’s go to the browser and refresh the page and you can see we have ‘user_id’ and its value within the link URL. Here in the users table we have this user ‘pending for approval’ and the link we created here will send request for this user to activate it. Now let’s go and create this file that is ‘activate_user’. This is the file where we are going to handle this request and will activate user. So, here let’s write an ‘if’ statement and check the condition ‘if’ $_GET is set means if we have this Super-global array set on this page and ‘$_GET[‘user_id’]’ is available only then we will proceed. In the execution area let’s create a variable ‘$user_id’ and assign it the value that we will grab from ‘$_GET’ super global array for ‘user_id’. Let’s copy all the required files from ‘users.php’ page and we don’t need this ‘links.php’. Go back to ‘activate_user.php’ page and paste all in here. Now we are ready to update the user record. So, start query and write all the stuff and then just a simple update query ‘UPDATE users SET ‘is_active’ = 2 where userID = $user_id’ and that’s it. This is the only purpose of this whole file to have this functionality created here. Let’s enclose this whole query within a variable. We can display messages depending on the result of the query by saving these in sessions and then display these sessions at users.php page, but that will get more complex for you.Last thing we need here, no matter whatever happens here, we need to move our user from this file back to ‘users.php’, so we can put header function below here and supply location ‘users.php’ and that’s it. So, we have all setup here. Let’s go back to the browser and refresh and here is one ‘activate’ link displayed. If we click it, it should activate this user and we will see status of this user, ‘Active’ instead. Let’s click this link. As soon as we clicked the ‘Activate’ link, our query executed on ‘activate_user.php’ page and at the same time we were sent back to this page again. So, here we can see this user is active now. Let’s go to the table to verify this. Just refresh table and here now we have 2 in ‘is_active’ column for this user. So we have successfully created all the functionality we wanted to develop for users having role ‘Admin’.




Welcome Message and Profile in Control Panel:

Now we want to show the welcome message to our logged in users by name when they login and get to their Control Panel. Also, we want to show them their profile information. This is really a simple task. We can grab all the information from database by just running a select query. So, let’s write a ‘select query’, so, ‘SELECT all FROM users WHERE userID = ’ and we can grab ‘userID’ easily from session that we stored in an earlier tutorial. Let’s just create a variable ‘$userID’ and get the value from ‘$_SESSION[‘userID’]’ and just put this variable here in this query. Complete rest of the query to cache any problems if query fails. So, this query is definitely going to give us one result only, so, we don’t need to run a while loop. Just fetch this result in $row array and off-course we need to create this variable ‘$qr’ here. Now we can grab all the values from this associative array, $row[‘name’] and put this in variable ‘$name’. Now we can easily echo this variableanywhere we want. Let’s put it right after ‘Hello’ using PHP short tags and put a sign of exclamation. Now let’s grab the other information as well, ‘username’, ‘email’ and ‘password’. Let’s just put a heading here that is ‘Profile’ and echo all the variables using shorthand method of PHP. Now let’s create a link below here.

This link will let any user update his own profile, who is logged in. Let’s just provide it a hyper reference that is ‘update_profile.php’ page and just put a link text ‘Update Profile’.  Now let’s go to the update_profile.php page for further coding. This file is more or less same like registration.php file. As we need a form here that will have its fields already filled with data from database and will allow user to change these details and update. Very simple.So, let’s create a simple form here. This is our form having three fields that will contain data from database in the value= “” attribute that is empty right now, and will display that to the user and user can off-course change that. And a submit button with value ‘Submit’ as well as name ‘Update’.We can copy all the required files from ‘index.php’ page as well as this session over here. We are dealing with database and here we didn’t required the connection file. Let’s check this in browser and off-course connection file is missing. Let’s just require ‘connection’ file here, refresh the browser and now it’s all fine, let’s just put some br tags to format the profile a little bit, let’s just view index.php page and this time it’s perfect. Now, let’s click on ‘update’ button and here we are on the ‘update_profile.php’ page and you can see we don’t have any labels of the fields nor the data within the fields right now. Let’s just copy all the required fields from ‘index.php’ page and session code as well and paste it in ‘update_profile.php’. This is the session code which is only verifying the logged in user, as we just checking for session variable ‘role’ is set or not. We need a select query that will select data for this particular user as we did in ‘index.php’ page, so, let’s just past the same code here as well and remove the items we don’t need. Now let’s display these variables as values within the form fields using PHP shorthand method, $name, $email and $password. Let’s also put labels for these fields. Let’s go to the browser, refresh and this is perfect now. We have our form fields labeled and data filled within these fields. Let’s just change value of submit button to ‘Update Profile’.

Now we can grab this submitted data up here right in this page. So, let’s write an ‘if’ statement and check if the form is submitted only then we will run the ‘EXTRACT’ function on $_POST super global associative array. As we are getting data through a form so we should sanitize this data. Let’s require ‘sanitize.php’ file. We also need to check the whether fields are empty or not, so let’s start ‘if’ statement and check if ‘empty($name)’ and to store the error in this case we need to have an array first that is $errors and keep it empty here and store an error here ‘Name is required’. Now write the same conditional statement for rest of the fields too. Now only if count of values in errors array is equals to zero only then we are going to process further. Let’s first sanitize all the fields. Now we can write the update query to update this user’s profile record in database. So, ‘Update users SET name = “$name”, email = “$email”, password = “$password” WHERE userID = ’ and this userID we can grab from $_session[‘userID’], so let’s get it now and simply put this userID here in Update query. So, if this query runs successfully, then we will redirect this user to ‘index.php’ file and if the query doesn’t run successfully we will add an error in the ‘$errors’ array ‘Internal Error. Please try again.’ and this will be displayed right above the form of this page. This is all for coding point of view. Let’s just include ‘links.php’ file as well. Now it’s time to verify the functionality, so let’s go to the browser, back to the control panel and click on ‘Update Profile’ link. Let’s change name to ‘Johonson’, click update and there we go, we are sent to the ‘Control Panel’ and you can see the name has been changed successfully. Let’s go to the ‘users’ table, refresh and now you can see the name has been updated. Let’s go back to the browser and click ‘Update Profile’ again and change email and click ‘Update’ and here you can see email is changed. This is it, we have successfully created the functionality that provides the facility to every registered user to update his own profile.

 


User-wise Menu Configuration:

If we look at our menu links, it’s strange to have all those link where the logged in user is unable to access or not allowed to access. Like if this user is having role of ‘Author’ he cannot access ‘All Users’ page and if the logged in user has role of ‘Admin’ he cannot access ‘Submit Article’ and ‘View Articles’ pages. So, we need to deal with this issue. Let’s first make links separate keeping the role in consideration. So, control panel that is main page is for all, ‘All Users’ link is only for Admins, ‘Submit Article’ and ‘View Articles’ links only for authors. ‘Login’ and ‘Registration’ pages are free to access, no role or session or logged in status required. Logout link is accessible for every logged in user. So, we can combine this with ‘Control Panel’ link. So, now we have 4 groups of links which are accessible for 4 different types of users. ‘Control Panel’ and ‘Logout’ pages are accessible for all logged in users, ‘All Users’ link is only accessible to ‘Admins’, ‘Submit Article’ and ‘View Articles’ links accessible only to ‘Authors’ and ‘Login’ and ‘Registration’ links are for non-logged in users. Now I am going to write a script that will show only related links to the logged in user depending on his role and or not-logged in users.

Let’s create an ‘if’ statement and check if the session role is equals to 2 only then, and this execution area will contain the links that are allowed only for admins. Let’s comment here that will keep us remember that it’s for admins only. Create another if statement and here if the session role is equals to 1 and that is for authors. Comment this out too ‘links for authors only’.

Third one is going to be for all registered and logged in users, means admin and authors all can have access to. Let’s create another‘if’ statement and here we are just verifying the session role.

The final one is for when no one is logged in, so in this case we will show ‘login’ and ‘registration’ links. So, in this if statement we will check if not isset session that is role.

Let’s just append these with another condition and that is it will check session role too. So, if any one of these returns false this statement will not execute. Now as we want to put HTML links within these execution areas of ‘if’ statements.So let’s close and start PHP tags and place a comment here ‘Links here’. Just copy all of this snippet and paste within all of the execution areas in‘if’ statements. Cut the admin links and paste within admins access, cut authors links only and paste in second if condition’s execution area, cut links for all loggedin users and paste them in logged in users access area and finally cut links allowed for all non-logged in users and paste them in here. That’s all. Let’s go to the browser and refresh the page and there we go, only links available to ‘Admin’ role are displayed and rest of all are gone. Control panel and All Users. Let’s logout and login back with the user having ‘Author’ role and now you can see this user has only access to ‘Submit Article’, ‘View Articles’, ‘Control Panel’ and logout and every logged in user can update his profile as well. Let’s logout and you can see at this point we can see two links that are ‘Login’ and ‘Register’ that were invisible when we were logged in. This is all for menu links.

Developing Rest of the Articles Site:

Now we have completed whole of the functionality of our ‘crud’ that’s only meant for ‘Admins’ and ‘Authors’ to facilitate them manage, users, upload site content and maintain it. Now we need the front-end side of our site that is for general public or you can say the visitors of our site. So, let’s create a new folder that is going to be main folder or directory that will hold each and everything relating our site, let’s name it ‘article-site’ and cut the whole ‘crud’ folder and move it inside this ‘article-site’ folder. Now, let’s open this folder in ‘PHPStorm’, now this is our whole site containing ‘crud’. Now if we want to access ‘crud’ in browser we will add ‘article-site’ and rest of the URL, and if we erase this part of the URL, we are at the main level of our site. So, here we will create pages for our site visitors and display rest of the content. Let’s go back in coding area and let’s just minimize ‘crud’ folder as we don’t need this and create a new PHP file at top level by right clicking here and name it as ‘index.php’, that is going to be main page of our site.

INDEX.PHP page:

Let’s just first close PHP tag as we want to write lots of HTML below here. Put h1 tags and here we are just writing a welcome message for our site visitors.Right below this we are going to display all of the articles and we can display them by date or may be by author, but in most of the cases these are displayed by date. So, for now let’s just write an h2 tag and write ‘Title of Article’ and below this within ‘p’ tag ‘Article Content’, so this is the way we will show our articles here on first page. Let’s copy this and paste it several times. Let’s go to the browser and now we are at main page, just refresh this page and you can see this is the first landing page for our site visitors displaying them just static content only. At the top, visitors will see a welcome message and below they will find all of the articles, ‘title’ and ‘content’ of the article respectively. Let’s go back to code and make this page dynamic by fetching data directly from database. First thing we need in PHP code is, we would like to connect to database so, let’s just require_once and here we need to mention ‘crud/connection.php’ as connection file is in ‘crud’ folder. Now we can write any query we want and here we need to write a ‘select’ query that will select all the articles. So, ‘select ‘title’, ‘content’ from articles’ and let’s just enclose this query in a variable ‘qr’. Let’s write PHP tags here to get data out of the query we wrote above. Let’s write an ‘if’ statement and if our query has some results in it only then we will go ahead. So, we need while loop here as there will be more than 1 records for sure. Let’s just fetch each record as an associative array and give it to the variable ‘row’ and within execution area simply grab ‘title’ and ‘content’ from this ‘$row’ associative array and store them in variables as well. So, we will get first article in first iteration, in second iteration second article and so on. So, we need to cut this HTML from here and take this within the while loop. Let’s just close and open PHP tags and bring this first static article sample within while loop and let’s just delete rest of these static articles. Let’s make these tags dynamic by echoing variable ‘title’ here and ‘content’ here instead of the static data using PHP short-hand method and that’s it. We have done it, let’s go to the browser and verify if everything is working fine. Just refresh this page and we have our dynamic website online. First article directly from database, second article and third one all displayed dynamically. Now, let’s create a ‘Read More’ link at the end of each article that will take the visitors to full view of single article page. Let’s view this in browser and you can see we have ‘Read More’ link with each article, although these are in place but don’t have functionality to take us to somewhere. So, let’s just give a link here ‘single-article.php’ and off-course we need to send some information, probably the article ID that we will be displayed when its relevant link will be clicked. Let’s just put a question mark and artID and off-course we would like to get this too in our query to show here. Let’s just mention this in ‘select’ query ‘artID’ and grab its value here in a variable ‘$artID’ and place this variable as a value in the URL. Now we want to create ‘single-article.php’ page.



Show One Complete Article on a Single Page:

Let’s create a new php file and name it ‘single-article.php’. This is the page where we get the request, so write an‘if’ statement to verify Super Global ‘$_GET’ and off-course we would like to check ‘artID’ is set or not, so, only when both of these are true we will process further. For now let’s just echo ‘Show the article’. Just to check if everything is working fine. Let’s go to browser and refresh index page and click any of the ‘Read More’ link and you can see it’s taking us to ‘single-article.php’ page and a message is displayed, ‘Show the article.’ So, we are on right track. Let’s remove this message from here as we don’t want it anymore and just put a comment here to let us know what we are doing here. Let’s write a select query here. ‘SELECT all from articles’ as we want to get all the details of one specific article, ‘WHERE artID’ as we want only one record which was requested through URL. We can get this artID from Super Global $_GET easily just mention ‘artID’ as position and that’s it. Let’s just put this id in ‘SELECT’ query. Put rest of the stuff to cache the errors in case the query fails. Put this whole query in a variable ‘qr’. As this query is capable to get only one record, so we don’t need to run while loop here. Let’s fetch the record as associative array in ‘$row’. Let’s just grab everything we need from this array, let’s check this in table. Here we need userID as well from which we will get name of the author of this article. We can off-course use join within our query and only one query will be sufficient but as this was not a part of this course, so we will write another query for this. Let’s get back to the code. Get all the required values from ‘row’ array. ‘title’, ‘content’ and ‘uploaded_on’ and store all of them in variables. Let’s create another variable ‘$qr2’ and write another select query, ‘SELECT name from users’ table as we need only the author name ‘WHERE userID = ’ and here we will simply put the ‘userID’ we grabbed up here that is ‘$userID’ and complete the query. Declare ‘$row2’ variable and fetch associative array from ‘$qr2’ that is second query and let’s just get name from ‘$row2’. Store this in a variable ‘$name’ as well.

Display Data on Single Article Page:

Now we can easily display all the data on this page.Let’s close and open PHP tags and within these let’s first put some static data with HTML tags. Let’s just check if everything is working fine in browser go to single page and we missed to include the connection file. Let’s just require_once this file. Now we can replace this static data with dynamic data using PHP shorthand method. Let’s just go to the browser and refresh. Let’s click any of the ‘Read More’ button and this is it we are sent to the ‘single-article.php’ page and data is fetched from database dynamically according to the article that was clicked, but we don’t have navigation link here that will take us back to home page. Let’s just create an HTML link here and put the hyper reference ‘index.php’ and place the link text ‘Home’ and copy this link to index.php page as well. This is it, we have done everything for our Articles site that has dynamic content in it and a fully functional control panel. You can keep all of this code as a reference and can use in your real projects. This is not everything you need but this is just to put you on track that will eventually make you a dynamic website developer. I wish you a really prosperous professional career in PHP. Thanks for being with me.

 


 

CRUD

Registration.php

 

<?php
require_once
'connection.php'
;
require_once 'sanitize.php';

$errors = array();

if($_POST){

$name = sanitize($_POST['name']);
if(empty($name)){
$errors[] = 'Name is required!';
    }
$username = sanitize($_POST['username']);
if(empty($username)){
$errors[] = 'Username is required!';
    }
$email = sanitize($_POST['email']);
if(empty($email)){
$errors[] = 'Email is required!';
    }
$password = sanitize($_POST['password']);
if(empty($password)){
$errors[] = 'Password is required!';
    }
$password_again = sanitize($_POST['password_again']);
if(empty($password_again) || $password_again != $password){
$errors[] = 'Password again is required and must match the password';
    }


if(!isset($_POST['terms']) || empty($_POST['terms'])){
$errors[] = 'You must agree to our terms of service.';
    }


if(count($errors) == 0){

$qr = mysql_query("
            INSERT INTO users
            (`name`, `username`, `email`, `password`)
            VALUES
            ('
$name', '$username', '$email', '$password')
            "
) or die(mysql_error());

if($qr){
$errors[] = 'You have been registered successfully. Admin will authenticate you soon!';
        }
else {
$errors[] = 'Some internal error please try again later!';
        }


    }

}


include_once 'links.php';
?>


<h1>User Registration</h1>
<?php


if
(count($errors) >0){
foreach($errors as $error){
echo $error, '<br>';
    }
}


?>



<form method="post" action="">

    Name: <input type="text" name="name" value="<?php echo isset($name) ? $name :''; ?>"><br>
    Email: <input type="email" name="email" value="<?php echo isset($email) ? $email :''; ?>"><br>
    Username: <input type="text" name="username" value="<?php echo isset($username) ? $username : ''; ?>"><br>
    Password: <input type="password" name="password" value=""><br>
    Password again: <input type="password" name="password_again" value=""><br>

<input type="checkbox" name="terms" value="1">Agree to Our Terms of Service
<br>
<input type="submit" value="Register" name="register">
<input type="reset" value="Reset">
</form>
 

Login.php

 

<?php
require_once
'connection.php';
require_once 'sanitize.php';


$errors = array();

if($_POST){


$username = sanitize($_POST['username']);
if(empty($username)){
$errors[] = 'Username is required!';
    }

$password = sanitize($_POST['password']);
if(empty($password)){
$errors[] = 'Password is required!';
    }

if(count($errors) == 0){

$qr = mysql_query("SELECT userID, username, password, role FROM users WHERE username = '$username' AND
          password = '
$password' AND is_active = 2
          "
) or die(mysql_error());



if(mysql_num_rows($qr) >0){
$row = mysql_fetch_assoc($qr);
$role = $row['role'];
$userID = $row['userID'];
session_start();
$_SESSION['role'] = $role;
$_SESSION['userID'] = $userID;
header(
"LOCATION: index.php");
        }
else {
echo 'Invalid login credentials.';
        }




    }

}





include_once 'links.php';
?>



<h1>Login</h1>
<?php

if
(count($errors) >0){
foreach($errors as $error){
echo $error, '<br>';
    }
}

?>

<form method="post" action="">

    Username: <
input type="text" name="username" value="<?php echo isset($username) ? $username :''; ?>"><br>
    Password: <
input type="password" name="password" value=""><br>

<
input type="submit" value="Login" name="login">
<
input type="reset" value="Reset">


</
form>

 

Connection.php

 

<?php

$con = mysql_connect('127.0.0.1', 'root', '') or die(mysql_error(). 'Could not connect to MySQL');

mysql_select_db(
'crud', $con) or die(mysql_error(). 'Could not connect to MySQL');

 

Index.php

<?php
session_start();

if(!isset($_SESSION['role'])){
header(
"LOCATION: login.php");
}
require_once 'connection.php';

include_once 'links.php';
$userID = $_SESSION['userID'];
$qr = mysql_query("SELECT * FROM users WHERE userID = $userID") or die(mysql_error());
$row = mysql_fetch_assoc($qr);
$name = $row['name'];
$username = $row['username'];
$email = $row['email'];
$password = $row['password'];
$joined = $row['joined'];
?>


<h1>Hello <?=$name?>! Welcome to Control Panel</h1>
<
h3>Profile</h3>
<
p>

<?=$name?><br>
<?=$username?><br>
<?=$email?><br>
<?=$joined?><br>

</
p>

<
a href="update_profile.php">Update Profile</a>


 

Sanitize.php

<?php



function
sanitize($data){
$data = trim(stripcslashes(htmlspecialchars($data)));
return $data;
}

 

Logout.php

<?php

session_start();

session_unset();

header(
"LOCATION: login.php");

 

Links.php

<?php
//links for admins only
if(isset($_SESSION['role']) &&$_SESSION['role'] == 2){

?>
<!--links here -->
<a href="users.php">All Users</a>
&nbsp;&nbsp;

<?php

}

//links for authors only
if(isset($_SESSION['role']) &&$_SESSION['role'] == 1){

?>
<!--links here-->
<a href="submit_article.php">Submit Article</a>
&nbsp;&nbsp;
<a href="view_articles.php">View Articles</a>
&nbsp;&nbsp;

<?php

}

//links for all registered and activated users
if(isset($_SESSION['role'])){
?>
<!--links here -->

<a href="index.php">Control Panel</a>
&nbsp;&nbsp;
<a href="logout.php">Logout</a>
&nbsp;&nbsp;

<?php
}

//links when no one is logged in
if(!isset($_SESSION['role'])){
?>
<!--links here -->
<a href="login.php">Login</a>
&nbsp;&nbsp;
<a href="registration.php">Registration</a>


<?php
}

?>

 

Session_author.php

<?php

if
(!isset($_SESSION['role']) || $_SESSION['role'] != 1){
header(
"LOCATION: login.php");
}

 

Session_admin.php

<?php

if
(!isset($_SESSION['role']) || $_SESSION['role'] != 2){
header(
"LOCATION: login.php");
}

 

Submit_article.php

<?php
session_start();

require_once 'session_author.php';
require_once 'sanitize.php';
require_once 'connection.php';

$errors = array();

if($_POST){
    EXTRACT(
$_POST);
if(empty($title)){
$errors[] = 'Title is required!';
    }
if(empty($art_name)){
$errors[] = 'Article Name is required!';
    }
if(empty($content)){
$errors[] = 'Article content is required';
    }


if(count($errors) == 0){
$userID = $_SESSION['userID'];
$art_name = sanitize($art_name);
$title = sanitize($title);
$content = sanitize($content);


$qr = mysql_query("INSERT INTO articles (userID, art_name, title, content, uploaded_on)
          VALUES (
$userID, '$art_name', '$title', '$content', now())
          "
) or die(mysql_error());

if($qr){
$errors[] = 'Article was submitted successfully.';
        }
else {
$errors[] = 'Some internal error. Please try later!';
        }

    }

}

include_once 'links.php';

?>

<h1>New Article</h1>

<?php

if
(count($errors) >0){
foreach($errors as $error){
echo $error, '<br>';
    }
}

?>

<form method="post" action="">
    Title:<
br>
<
input type="text" name="title" value="<?php echo (isset($title)) ? $title :''; ?>"><br>
    Name of Article:<
br>
<
input type="text" name="art_name" value="<?php echo (isset($art_name)) ? $art_name :''; ?>"><br>
    Article:<
br>
<
textarea name="content" cols="25" rows="10"><?php echo (isset($content)) ? $content :''; ?></textarea><br>
<
input type="submit" value="Publish" name="submit">
<
input type="reset" value="Reset">
</
form>

 

View_articles.php

<?php
session_start();

require_once 'session_author.php';
//require_once 'sanitize.php';
require_once 'connection.php';

include_once 'links.php';
?>

<h1>All Your Articles</h1>
<
table border="1">
<
tr>
<
th>Article Name</th>
<
th>Title</th>
<
th>Content</th>
</
tr>


<?php
$userID = $_SESSION['userID'];
$qr = mysql_query("SELECT * FROM articles WHERE userID = $userID") or die(mysql_error());
while($row = mysql_fetch_assoc($qr)){
$art_name = $row['art_name'];
$title = $row['title'];
$content = $row['content'];
?>

<tr>
<
td><?=$art_name?></td>
<
td><?=$title?></td>
<
td><?=$content?></td>
</
tr>


<?php

}

?>

</table>

 

 

Users.php

 

<?php
session_start();

require_once 'session_admin.php';
require_once 'sanitize.php';
require_once 'connection.php';
include_once 'links.php';
?>

<h1>All Users</h1>
<
table border="1">
<
tr>
<
th>Name</th>
<
th>User Name</th>
<
th>Email</th>
<
th>Joined On</th>
<
th>Role</th>
<
th>Status</th>
<
th>Action</th>
</
tr>

<?php

$qr = mysql_query("SELECT * FROM users") or die(mysql_error());
while($row = mysql_fetch_assoc($qr)){
$user_id = $row['userID'];
$name = $row['name'];
$username = $row['username'];
$email = $row['email'];
$joined = $row['joined'];
$role = $row['role'];


if($role == 1){
$role = 'Author';
    }
else {
$role = 'Admin';
    }

$is_active = $row['is_active'];
if($is_active == 1){
$activation = 'Pending';
    }
else {
$activation = 'Active';
    }
?>

<tr>
<
td><?=$name?></td>
<
td><?=$username?></td>
<
td><?=$email?></td>
<
td><?=$joined?></td>
<
td><?=$role?></td>
<
td><?=$activation?></td>
<
td>
<?php
            if
($is_active == 1){
?>

<a href="activate_user.php?user_id=<?=$user_id?>">Activate</a>
<?php


}
?>

</td>
</
tr>

<?php

}

?>
</table>

 

Activate_user.php

<?php
session_start();

require_once 'session_admin.php';
require_once 'sanitize.php';
require_once 'connection.php';

if($_GET &&$_GET['user_id']){
$user_id = $_GET['user_id'];
$qr = mysql_query("UPDATE users SET is_active = 2 WHERE userID = $user_id")
or die(mysql_error());
}

header(
"LOCATION: users.php");

 

 

Update_profile.php

 

<?php
session_start();

if(!isset($_SESSION['role'])){
header(
"LOCATION: login.php");
}
require_once 'connection.php';
require_once 'sanitize.php';

$errors = array();

if($_POST){
    EXTRACT(
$_POST);
if(empty($name)){
$errors[] = 'Name is required';
    }
if(empty($email)){
$errors[] = 'Email is required';
    }
if(empty($password)){
$errors[] = 'Password is required';
    }

if(count($errors) == 0){
$userID = $_SESSION['userID'];
$name = sanitize($name);
$email = sanitize($email);
$password = sanitize($password);

$qr = mysql_query("UPDATE users SET `name` = '$name', `email` = '$email', `password` = '$password'
        WHERE `userID` =
$userID
")
or die(mysql_error());

if($qr){
header(
"LOCATION: index.php");
        }
else {
$errors[] = 'Internal error. Please try again.';
        }



    }

}

include_once 'links.php';
?>

<h1>Update Profile</h1>

<?php
$userID = $_SESSION['userID'];
$qr = mysql_query("SELECT * FROM users WHERE userID = $userID") or die(mysql_error());
$row = mysql_fetch_assoc($qr);

$name = $row['name'];
$email = $row['email'];
$password = $row['password'];

?>
<form method="post" action="">


    Name: <
input type="text" name="name" value="<?=$name?>"><br>
    Email: <
input type="email" name="email" value="<?=$email?>"><br>
    Password: <
input type="password" name="password" value="<?=$password?>"><br>

<
input type="submit" value="Update Profile" name="update">

</
form>



Article-Site

 

Index.php

<?php
require_once
'crud/connection.php';

$qr = mysql_query("SELECT artID, title, content FROM articles") or die(mysql_error());

?>

<h1>Welcome to Articles Site</h1>
<
a href="index.php">Home</a>
<?php
if
(mysql_num_rows($qr) >0){
while($row = mysql_fetch_assoc($qr)){
$artID = $row['artID'];
$title = $row['title'];
$content = $row['content'];
?>

<h2><?=$title?></h2>
<
p><?=$content?></p>
<
a href="single-article.php?artID=<?=$artID?>">Read More</a>


<?php

}
}

?>

 

Single-article.php

<?php
require_once
'crud/connection.php';

?>
<a href="index.php">Home</a>
<?php

if
($_GET &&isset($_GET['artID'])) {

//get article details as well as author details

$artID = $_GET['artID'];
$qr = mysql_query("SELECT * FROM articles WHERE artID = $artID") or die(mysql_error());
$row = mysql_fetch_assoc($qr);
$userID = $row['userID'];
$title = $row['title'];
$content = $row['content'];
$uploaded_on = $row['uploaded_on'];

$qr2 = mysql_query("SELECT name FROM users WHERE userID = $userID") or die(mysql_error());
$row2 = mysql_fetch_assoc($qr2);
$name = $row2['name'];

?>

<h1><?=$title?></h1>
<
p><?=$content?></p>
<
p><b>Author: </b><i><?=$name?></i></p>


<?php

}



                 Project files

               Download 

Download SQL File 15 days




Related Posts:

Leave a reply

Required fields are marked *

Login to Post Comment