PHP and MySQL Cyclesheet

PHP and MySQL Cyclesheet

Vellore Institute of Technology,Vellore Campus

ยท

24 min read

Table of contents

No heading

No headings in the article.

1)

i) Implement a sign up page for student registration. The page should be in the format given below:

ii) The JavaScript should do validation with alert box display

iii) The server (PHP) registers the user and stores the user info containing username, gender and address in database(MySQL), if the user name does not exist in the database already.

Code:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "cyclesheet";
// Create connection
$conn = mysqli_connect($servername, $username,$password,$dbname);
// Check connection
if (!$conn)
{
die("Connection failed: ".mysqli_connect_error()); }
/*$sql = "CREATE TABLE student
( name VARCHAR(30) PRIMARY KEY, gender VARCHAR(30) NOT NULL, address VARCHAR(50), reg_date TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "Table student created successfully"; }
else {
echo "Error creating table: ". mysqli_error($conn); }
*/
if(isset($_POST['submit'])){
$sql = "INSERT INTO student (name, gender, address)VALUES('".$_POST["name"]."','".$_POST["sex"]."','".$_POST[ "pe_address"]."')";
$result = mysqli_query($conn,$sql);
}
?>
<html>
<head>
<title>Naveen</title>
<style>
table{
background-color:#00ffff;
}
</style>
<script>
function validateform()
{
var a=document.forms["myform"]["name"].value;
var b=document.forms["myform"]["pe_address"].value; 
var c=document.forms["myform"]["sex"]; avali(a);
bvali(b);
cvali(c);
}
function
avali(a){ if(a==""){
alert("please provide your name");
return false;
}}
function
bvali(b){ if(b==""){
alert("please provide your personal address"); return false;
}}
function cvali(c)
{
for(var i=0;i<c.length;i++){ if(c[i].checked==true||
c[i+1].checked==true)
{ return true;
}
else {
alert("please provide your gender"); return false;
}
} }
</script>
</head>
<body>
<form name="myform" onsubmit="returnvalidateform()"method="post">
<table cellpadding="10"cellspacing="10"> <tr><th colspan="2"><h2>Student Registration Form</h2></th></tr>
<tr>
<td>Name</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>Father Name</td>
<td><input type="text" name="fname"/></td>
</tr>
<tr>
<td>Postal Address</td>
<td><input type="text" name="po_address" /></td>
</tr>
<tr>
<td>Personal Address</td>
<td><input type="text" name="pe_address" /></td>
</tr>
<tr>
<td>Sex</td>
<td><input type="radio" name="sex" value="male"/>Male<input type="radio" name="sex" value="female" />Female</td>
</tr>
<tr>
<td>City</td>
<td><select name="city"><option value="">select..</option></select></td>
</tr>
<tr><td>Course</td>
<td><select name="course"><option value="">select..</option></select></td>
</tr>
<tr>
<td>District</td>
<td><select name="district"><option value="">select..</option></select></td>
</tr>
<tr><td>MobileNo</td>
<td><input type="text" name="number"/></td>
</tr>
<tr><td><input type="reset" value="reset" /></td>
<td><button type="submit" name="submit" />SubmitForm</button></td>
</tr>
</table>
</form>
</body>
</html>

OUTPUT:

image.png

image.png

2.Implement an online quiz application.

i) The timer is set for each question. If timer elapses the next question is automatically displayed.

ii) Going back to previous question is disabled and going to next question before time should also be possible.

iii) The app should store the results of the user in the database. The database also stores the number of attempts made by the user.

Code:

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Naveen</title>
    <link rel="stylesheet" href="style.css">
    <!-- FontAweome CDN Link for Icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
</head>
<body>
    <!-- start Quiz button -->
    <div class="start_btn"><button>Naveen's Quiz-Start</button></div>

    <!-- Info Box -->
    <div class="info_box">
        <div class="info-title"><span>Some Rules of this Quiz</span></div>
        <div class="info-list">
            <div class="info">1. You will have only <span>15 seconds</span> per each question.</div>
            <div class="info">2. Once you select your answer, it can't be undone.</div>
            <div class="info">3. You can't select any option once time goes off.</div>
            <div class="info">4. You can't exit from the Quiz while you're playing.</div>
            <div class="info">5. You'll get points on the basis of your correct answers.</div>
        </div>
        <div class="buttons">
            <button class="quit">Exit Quiz</button>
            <button class="restart">Continue</button>
        </div>
    </div>

    <!-- Quiz Box -->
    <div class="quiz_box">
        <header>
            <div class="title">Awesome Quiz Application</div>
            <div class="timer">
                <div class="time_left_txt">Time Left</div>
                <div class="timer_sec">15</div>
            </div>
            <div class="time_line"></div>
        </header>
        <section>
            <div class="que_text">
                <!-- Here I've inserted question from JavaScript -->
            </div>
            <div class="option_list">
                <!-- Here I've inserted options from JavaScript -->
            </div>
        </section>

        <!-- footer of Quiz Box -->
        <footer>
            <div class="total_que">
                <!-- Here I've inserted Question Count Number from JavaScript -->
            </div>
            <button class="next_btn">Next Que</button>
        </footer>
    </div>

    <!-- Result Box -->
    <div class="result_box">
        <div class="icon">
            <i class="fas fa-crown"></i>
        </div>
        <div class="complete_text">You've completed the Quiz!</div>
        <div class="score_text">
            <!-- Here I've inserted Score Result from JavaScript -->
        </div>
        <div class="buttons">
            <button class="restart">Replay Quiz</button>
            <button class="quit">Quit Quiz</button>
        </div>
    </div>

    <!-- Inside this JavaScript file I've inserted Questions and Options only -->
    <script src="js/questions.js"></script>

    <!-- Inside this JavaScript file I've coded all Quiz Codes -->
    <script src="js/script.js"></script>

</body>
</html>
</html>

Style.css:

/* importing google fonts */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap');
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}

body{
    background: #007bff;
}

::selection{
    color: #fff;
    background: #007bff;
}

.start_btn,
.info_box,
.quiz_box,
.result_box{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 
                0 6px 20px 0 rgba(0, 0, 0, 0.19);
}

.info_box.activeInfo,
.quiz_box.activeQuiz,
.result_box.activeResult{
    opacity: 1;
    z-index: 5;
    pointer-events: auto;
    transform: translate(-50%, -50%) scale(1);
}

.start_btn button{
    font-size: 25px;
    font-weight: 500;
    color: #007bff;
    padding: 15px 30px;
    outline: none;
    border: none;
    border-radius: 5px;
    background: #fff;
    cursor: pointer;
}

.info_box{
    width: 540px;
    background: #fff;
    border-radius: 5px;
    transform: translate(-50%, -50%) scale(0.9);
    opacity: 0;
    pointer-events: none;
    transition: all 0.3s ease;
}

.info_box .info-title{
    height: 60px;
    width: 100%;
    border-bottom: 1px solid lightgrey;
    display: flex;
    align-items: center;
    padding: 0 30px;
    border-radius: 5px 5px 0 0;
    font-size: 20px;
    font-weight: 600;
}

.info_box .info-list{
    padding: 15px 30px;
}

.info_box .info-list .info{
    margin: 5px 0;
    font-size: 17px;
}

.info_box .info-list .info span{
    font-weight: 600;
    color: #007bff;
}
.info_box .buttons{
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 0 30px;
    border-top: 1px solid lightgrey;
}

.info_box .buttons button{
    margin: 0 5px;
    height: 40px;
    width: 100px;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    border: none;
    outline: none;
    border-radius: 5px;
    border: 1px solid #007bff;
    transition: all 0.3s ease;
}

.quiz_box{
    width: 550px;
    background: #fff;
    border-radius: 5px;
    transform: translate(-50%, -50%) scale(0.9);
    opacity: 0;
    pointer-events: none;
    transition: all 0.3s ease;
}

.quiz_box header{
    position: relative;
    z-index: 2;
    height: 70px;
    padding: 0 30px;
    background: #fff;
    border-radius: 5px 5px 0 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0px 3px 5px 1px rgba(0,0,0,0.1);
}

.quiz_box header .title{
    font-size: 20px;
    font-weight: 600;
}

.quiz_box header .timer{
    color: #004085;
    background: #cce5ff;
    border: 1px solid #b8daff;
    height: 45px;
    padding: 0 8px;
    border-radius: 5px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 145px;
}

.quiz_box header .timer .time_left_txt{
    font-weight: 400;
    font-size: 17px;
    user-select: none;
}

.quiz_box header .timer .timer_sec{
    font-size: 18px;
    font-weight: 500;
    height: 30px;
    width: 45px;
    color: #fff;
    border-radius: 5px;
    line-height: 30px;
    text-align: center;
    background: #343a40;
    border: 1px solid #343a40;
    user-select: none;
}

.quiz_box header .time_line{
    position: absolute;
    bottom: 0px;
    left: 0px;
    height: 3px;
    background: #007bff;
}

section{
    padding: 25px 30px 20px 30px;
    background: #fff;
}

section .que_text{
    font-size: 25px;
    font-weight: 600;
}

section .option_list{
    padding: 20px 0px;
    display: block;   
}

section .option_list .option{
    background: aliceblue;
    border: 1px solid #84c5fe;
    border-radius: 5px;
    padding: 8px 15px;
    font-size: 17px;
    margin-bottom: 15px;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

section .option_list .option:last-child{
    margin-bottom: 0px;
}

section .option_list .option:hover{
    color: #004085;
    background: #cce5ff;
    border: 1px solid #b8daff;
}

section .option_list .option.correct{
    color: #155724;
    background: #d4edda;
    border: 1px solid #c3e6cb;
}

section .option_list .option.incorrect{
    color: #721c24;
    background: #f8d7da;
    border: 1px solid #f5c6cb;
}

section .option_list .option.disabled{
    pointer-events: none;
}

section .option_list .option .icon{
    height: 26px;
    width: 26px;
    border: 2px solid transparent;
    border-radius: 50%;
    text-align: center;
    font-size: 13px;
    pointer-events: none;
    transition: all 0.3s ease;
    line-height: 24px;
}
.option_list .option .icon.tick{
    color: #23903c;
    border-color: #23903c;
    background: #d4edda;
}

.option_list .option .icon.cross{
    color: #a42834;
    background: #f8d7da;
    border-color: #a42834;
}

footer{
    height: 60px;
    padding: 0 30px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-top: 1px solid lightgrey;
}

footer .total_que span{
    display: flex;
    user-select: none;
}

footer .total_que span p{
    font-weight: 500;
    padding: 0 5px;
}

footer .total_que span p:first-child{
    padding-left: 0px;
}

footer button{
    height: 40px;
    padding: 0 13px;
    font-size: 18px;
    font-weight: 400;
    cursor: pointer;
    border: none;
    outline: none;
    color: #fff;
    border-radius: 5px;
    background: #007bff;
    border: 1px solid #007bff;
    line-height: 10px;
    opacity: 0;
    pointer-events: none;
    transform: scale(0.95);
    transition: all 0.3s ease;
}

footer button:hover{
    background: #0263ca;
}

footer button.show{
    opacity: 1;
    pointer-events: auto;
    transform: scale(1);
}

.result_box{
    background: #fff;
    border-radius: 5px;
    display: flex;
    padding: 25px 30px;
    width: 450px;
    align-items: center;
    flex-direction: column;
    justify-content: center;
    transform: translate(-50%, -50%) scale(0.9);
    opacity: 0;
    pointer-events: none;
    transition: all 0.3s ease;
}

.result_box .icon{
    font-size: 100px;
    color: #007bff;
    margin-bottom: 10px;
}

.result_box .complete_text{
    font-size: 20px;
    font-weight: 500;
}

.result_box .score_text span{
    display: flex;
    margin: 10px 0;
    font-size: 18px;
    font-weight: 500;
}

.result_box .score_text span p{
    padding: 0 4px;
    font-weight: 600;
}

.result_box .buttons{
    display: flex;
    margin: 20px 0;
}

.result_box .buttons button{
    margin: 0 10px;
    height: 45px;
    padding: 0 20px;
    font-size: 18px;
    font-weight: 500;
    cursor: pointer;
    border: none;
    outline: none;
    border-radius: 5px;
    border: 1px solid #007bff;
    transition: all 0.3s ease;
}

.buttons button.restart{
    color: #fff;
    background: #007bff;
}

.buttons button.restart:hover{
    background: #0263ca;
}

.buttons button.quit{
    color: #007bff;
    background: #fff;
}

.buttons button.quit:hover{
    color: #fff;
    background: #007bff;
}

script.js:

//selecting all required elements
const start_btn = document.querySelector(".start_btn button");
const info_box = document.querySelector(".info_box");
const exit_btn = info_box.querySelector(".buttons .quit");
const continue_btn = info_box.querySelector(".buttons .restart");
const quiz_box = document.querySelector(".quiz_box");
const result_box = document.querySelector(".result_box");
const option_list = document.querySelector(".option_list");
const time_line = document.querySelector("header .time_line");
const timeText = document.querySelector(".timer .time_left_txt");
const timeCount = document.querySelector(".timer .timer_sec");

// if startQuiz button clicked
start_btn.onclick = ()=>{
    info_box.classList.add("activeInfo"); //show info box
}

// if exitQuiz button clicked
exit_btn.onclick = ()=>{
    info_box.classList.remove("activeInfo"); //hide info box
}

// if continueQuiz button clicked
continue_btn.onclick = ()=>{
    info_box.classList.remove("activeInfo"); //hide info box
    quiz_box.classList.add("activeQuiz"); //show quiz box
    showQuetions(0); //calling showQestions function
    queCounter(1); //passing 1 parameter to queCounter
    startTimer(15); //calling startTimer function
    startTimerLine(0); //calling startTimerLine function
}

let timeValue =  15;
let que_count = 0;
let que_numb = 1;
let userScore = 0;
let counter;
let counterLine;
let widthValue = 0;

const restart_quiz = result_box.querySelector(".buttons .restart");
const quit_quiz = result_box.querySelector(".buttons .quit");

// if restartQuiz button clicked
restart_quiz.onclick = ()=>{
    quiz_box.classList.add("activeQuiz"); //show quiz box
    result_box.classList.remove("activeResult"); //hide result box
    timeValue = 15; 
    que_count = 0;
    que_numb = 1;
    userScore = 0;
    widthValue = 0;
    showQuetions(que_count); //calling showQestions function
    queCounter(que_numb); //passing que_numb value to queCounter
    clearInterval(counter); //clear counter
    clearInterval(counterLine); //clear counterLine
    startTimer(timeValue); //calling startTimer function
    startTimerLine(widthValue); //calling startTimerLine function
    timeText.textContent = "Time Left"; //change the text of timeText to Time Left
    next_btn.classList.remove("show"); //hide the next button
}

// if quitQuiz button clicked
quit_quiz.onclick = ()=>{
    window.location.reload(); //reload the current window
}

const next_btn = document.querySelector("footer .next_btn");
const bottom_ques_counter = document.querySelector("footer .total_que");

// if Next Que button clicked
next_btn.onclick = ()=>{
    if(que_count < questions.length - 1){ //if question count is less than total question length
        que_count++; //increment the que_count value
        que_numb++; //increment the que_numb value
        showQuetions(que_count); //calling showQestions function
        queCounter(que_numb); //passing que_numb value to queCounter
        clearInterval(counter); //clear counter
        clearInterval(counterLine); //clear counterLine
        startTimer(timeValue); //calling startTimer function
        startTimerLine(widthValue); //calling startTimerLine function
        timeText.textContent = "Time Left"; //change the timeText to Time Left
        next_btn.classList.remove("show"); //hide the next button
    }else{
        clearInterval(counter); //clear counter
        clearInterval(counterLine); //clear counterLine
        showResult(); //calling showResult function
    }
}

// getting questions and options from array
function showQuetions(index){
    const que_text = document.querySelector(".que_text");

    //creating a new span and div tag for question and option and passing the value using array index
    let que_tag = '<span>'+ questions[index].numb + ". " + questions[index].question +'</span>';
    let option_tag = '<div class="option"><span>'+ questions[index].options[0] +'</span></div>'
    + '<div class="option"><span>'+ questions[index].options[1] +'</span></div>'
    + '<div class="option"><span>'+ questions[index].options[2] +'</span></div>'
    + '<div class="option"><span>'+ questions[index].options[3] +'</span></div>';
    que_text.innerHTML = que_tag; //adding new span tag inside que_tag
    option_list.innerHTML = option_tag; //adding new div tag inside option_tag

    const option = option_list.querySelectorAll(".option");

    // set onclick attribute to all available options
    for(i=0; i < option.length; i++){
        option[i].setAttribute("onclick", "optionSelected(this)");
    }
}
// creating the new div tags which for icons
let tickIconTag = '<div class="icon tick"><i class="fas fa-check"></i></div>';
let crossIconTag = '<div class="icon cross"><i class="fas fa-times"></i></div>';

//if user clicked on option
function optionSelected(answer){
    clearInterval(counter); //clear counter
    clearInterval(counterLine); //clear counterLine
    let userAns = answer.textContent; //getting user selected option
    let correcAns = questions[que_count].answer; //getting correct answer from array
    const allOptions = option_list.children.length; //getting all option items

    if(userAns == correcAns){ //if user selected option is equal to array's correct answer
        userScore += 1; //upgrading score value with 1
        answer.classList.add("correct"); //adding green color to correct selected option
        answer.insertAdjacentHTML("beforeend", tickIconTag); //adding tick icon to correct selected option
        console.log("Correct Answer");
        console.log("Your correct answers = " + userScore);
    }else{
        answer.classList.add("incorrect"); //adding red color to correct selected option
        answer.insertAdjacentHTML("beforeend", crossIconTag); //adding cross icon to correct selected option
        console.log("Wrong Answer");

        for(i=0; i < allOptions; i++){
            if(option_list.children[i].textContent == correcAns){ //if there is an option which is matched to an array answer 
                option_list.children[i].setAttribute("class", "option correct"); //adding green color to matched option
                option_list.children[i].insertAdjacentHTML("beforeend", tickIconTag); //adding tick icon to matched option
                console.log("Auto selected correct answer.");
            }
        }
    }
    for(i=0; i < allOptions; i++){
        option_list.children[i].classList.add("disabled"); //once user select an option then disabled all options
    }
    next_btn.classList.add("show"); //show the next button if user selected any option
}

function showResult(){
    info_box.classList.remove("activeInfo"); //hide info box
    quiz_box.classList.remove("activeQuiz"); //hide quiz box
    result_box.classList.add("activeResult"); //show result box
    const scoreText = result_box.querySelector(".score_text");
    if (userScore > 3){ // if user scored more than 3
        //creating a new span tag and passing the user score number and total question number
        let scoreTag = '<span>and congrats! ๐ŸŽ‰, You got <p>'+ userScore +'</p> out of <p>'+ questions.length +'</p></span>';
        scoreText.innerHTML = scoreTag;  //adding new span tag inside score_Text
    }
    else if(userScore > 1){ // if user scored more than 1
        let scoreTag = '<span>and nice ๐Ÿ˜Ž, You got <p>'+ userScore +'</p> out of <p>'+ questions.length +'</p></span>';
        scoreText.innerHTML = scoreTag;
    }
    else{ // if user scored less than 1
        let scoreTag = '<span>and sorry ๐Ÿ˜, You got only <p>'+ userScore +'</p> out of <p>'+ questions.length +'</p></span>';
        scoreText.innerHTML = scoreTag;
    }
}

function startTimer(time){
    counter = setInterval(timer, 1000);
    function timer(){
        timeCount.textContent = time; //changing the value of timeCount with time value
        time--; //decrement the time value
        if(time < 9){ //if timer is less than 9
            let addZero = timeCount.textContent; 
            timeCount.textContent = "0" + addZero; //add a 0 before time value
        }
        if(time < 0){ //if timer is less than 0
            clearInterval(counter); //clear counter
            timeText.textContent = "Time Off"; //change the time text to time off
            const allOptions = option_list.children.length; //getting all option items
            let correcAns = questions[que_count].answer; //getting correct answer from array
            for(i=0; i < allOptions; i++){
                if(option_list.children[i].textContent == correcAns){ //if there is an option which is matched to an array answer
                    option_list.children[i].setAttribute("class", "option correct"); //adding green color to matched option
                    option_list.children[i].insertAdjacentHTML("beforeend", tickIconTag); //adding tick icon to matched option
                    console.log("Time Off: Auto selected correct answer.");
                }
            }
            for(i=0; i < allOptions; i++){
                option_list.children[i].classList.add("disabled"); //once user select an option then disabled all options
            }
            next_btn.classList.add("show"); //show the next button if user selected any option
        }
    }
}

function startTimerLine(time){
    counterLine = setInterval(timer, 29);
    function timer(){
        time += 1; //upgrading time value with 1
        time_line.style.width = time + "px"; //increasing width of time_line with px by time value
        if(time > 549){ //if time value is greater than 549
            clearInterval(counterLine); //clear counterLine
        }
    }
}

function queCounter(index){
    //creating a new span tag and passing the question number and total question
    let totalQueCounTag = '<span><p>'+ index +'</p> of <p>'+ questions.length +'</p> Questions</span>';
    bottom_ques_counter.innerHTML = totalQueCounTag;  //adding new span tag inside bottom_ques_counter
}

questions.js:

// creating an array and passing the number, questions, options, and answers
let questions = [
    {
    numb: 1,
    question: "What does HTML stand for?",
    answer: "Hyper Text Markup Language",
    options: [
      "Hyper Text Preprocessor",
      "Hyper Text Markup Language",
      "Hyper Text Multiple Language",
      "Hyper Tool Multi Language"
    ]
  },
    {
    numb: 2,
    question: "What does CSS stand for?",
    answer: "Cascading Style Sheet",
    options: [
      "Common Style Sheet",
      "Colorful Style Sheet",
      "Computer Style Sheet",
      "Cascading Style Sheet"
    ]
  },
    {
    numb: 3,
    question: "What does PHP stand for?",
    answer: "Hypertext Preprocessor",
    options: [
      "Hypertext Preprocessor",
      "Hypertext Programming",
      "Hypertext Preprogramming",
      "Hometext Preprocessor"
    ]
  },
    {
    numb: 4,
    question: "What does SQL stand for?",
    answer: "Structured Query Language",
    options: [
      "Stylish Question Language",
      "Stylesheet Query Language",
      "Statement Question Language",
      "Structured Query Language"
    ]
  },
    {
    numb: 5,
    question: "What does XML stand for?",
    answer: "eXtensible Markup Language",
    options: [
      "eXtensible Markup Language",
      "eXecutable Multiple Language",
      "eXTra Multi-Program Language",
      "eXamine Multiple Language"
    ]
  },
  // you can uncomment the below codes and make duplicate as more as you want to add question
  // but remember you need to give the numb value serialize like 1,2,3,5,6,7,8,9.....

  //   {
  //   numb: 6,
  //   question: "Your Question is Here",
  //   answer: "Correct answer of the question is here",
  //   options: [
  //     "Option 1",
  //     "option 2",
  //     "option 3",
  //     "option 4"
  //   ]
  // },
];

OUTPUT:

image.png

image.png

image.png

3.Ten students are appearing for the Dream Company Interview in VIT.

i) Interview has 3 rounds and marks will be awarded for each round for a maximum of 50,25 and 25 in each rounds.

ii) Based on the student who has got the maximum marks, a ranking system is to be applied and only 5 students will be selected to get the job.

iii) Consider two student score the same marks. Then they will have different ranks. Write a PHP code to help the employer.

Code:

naveen.php:

<html>
<head>
<style>
body{
margin-top:70px;
width: 50%;
}
table{
box-shadow: -7px 5px 2px 1px rgba(62, 102, 255, 0.43);
height:auto;
width:auto;
transition: 0.3s;
background: #FF40E6;
background: #CFE7fA;
background: -webkit-linear-gradient(to right, #CFE7fA 0%, #6393C1
100%);
background: -moz-linear-gradient(to right, #CFE7fA 0%, #6393C1
100%);
background: linear-gradient(to right, #CFE7fA 0%, #6393C1 100%);
}
</style>
</head>
<body>
<form a method=post name="myform" action="dreamoutput.php"> <tr>
<h2 style="background-color: pink;">VIT Dream company Interview
Ranking System</h2>
<table align="center">
<tr>
<td>Name </td>
<td>Round1 Marks<br>(Maximum Marks-50)</td>
<td>Round2 Marks<br>(Maximum Marks-25)</td>
<td>Round3 Marks<br>(Maximum Marks-25)</td>
<td>Total Marks</td>
</tr>
<tr>
<td><input type="text" name="myname1" id="myname1" /> </td>
<td> <input type="number" name="r1m1" id="r1m" /></td>
<td> <input type="number" name="r2m1" id="r2m" /></td>
<td> <input type="number" name="r3m1" id="r3m" /></td>
<td><input type="number" /></td>
</tr>
<tr>
<td> <input type="text" name="myname2" id="myname2" /></td>
<td> <input type="number" name="r1m2" id="r1m" /></td>
<td> <input type="number" name="r2m2" id="r2m" /></td>
<td> <input type="number" name="r3m2" id="r3m" /></td><td><input type="number" /></td>
</tr>
<tr>
<td> <input type="text" name="myname3" id="myname3" /></td>
<td> <input type="number" name="r1m3" id="r1m" /></td>
<td> <input type="number" name="r2m3" id="r2m" /></td>
<td> <input type="number" name="r3m3" id="r3m" /> </td><td><input type="number" /></td>
</tr>
<tr>
<td> <input type="text" name="myname4" id="myname4" /></td>
<td> <input type="number" name="r1m4" id="r1m" /></td>
<td> <input type="number" name="r2m4" id="r2m" /></td>
<td> <input type="number" name="r3m4" id="r3m" /></td><td><input type="number" /></td>
</tr>
<tr>
<td> <input type="text" name="myname5" id="myname5" /></td>
<td> <input type="number" name="r1m5" id="r1m" /></td>
<td> <input type="number" name="r2m5" id="r2m" /></td>
<td> <input type="number" name="r3m5" id="r3m" /></td><td><input type="number" /></td>
</tr>
<tr>
<td> <input type="text" name="myname6" id="myname6" /></td>
<td> <input type="number" name="r1m6" id="r1m" /></td>
<td> <input type="number" name="r2m6" id="r2m" /></td>
<td> <input type="number" name="r3m6" id="r3m" /></td><td><input type="number" /></td>
</tr>
<tr>
<td> <input type="text" name="myname7" id="myname7" /></td>
<td> <input type="number" name="r1m7" id="r1m" /></td>
<td> <input type="number" name="r2m7" id="r2m" /></td>
<td> <input type="number" name="r3m7" id="r3m" /></td><td><input type="number" /></td>
</tr>
<tr>
<td> <input type="text" name="myname8" id="myname8" /></td>
<td> <input type="number" name="r1m8" id="r1m" /></td>
<td> <input type="number" name="r2m8" id="r2m" /></td>
<td> <input type="number" name="r3m8" id="r3m" /></td><td><input type="number" /></td>
</tr>
<tr>
<td> <input type="text" name="myname9" id="myname9" /></td>
<td> <input type="number" name="r1m9" id="r1m" /></td>
<td> <input type="number" name="r2m9" id="r2m" /></td>
<td> <input type="number" name="r3m9" id="r2m" /></td><td><input type="number" /></td>
</tr>
<tr>
<td> <input type="text" name="myname10" id="myname10" /></td>
<td> <input type="number" name="r1m10" id="r1m" /></td>
<td> <input type="number" name="r2m10" id="r2m" /></td>
<td> <input type="number" name="r3m10" id="r3m" /></td><td><input type="number" /></td>
</tr>
<tr>
<td colspan="5"><input type="Submit" name="Submit"value="Submit"/> </td>
</tr>
</table>
</form></body>
</html>

dreamout.php:

<?php
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$one=(int)$_POST['r1m1']+(int)$_POST['r2m1']+(int)$_POST['r3m1'];
$two=(int)$_POST['r1m2']+(int)$_POST['r2m2']+(int)$_POST['r3m2'];
$three=(int)$_POST['r1m3']+(int)$_POST['r2m3']+(int)$_POST['r3m3'];
$four=(int)$_POST['r1m4']+(int)$_POST['r2m4']+(int)$_POST['r3m4'];
$five=(int)$_POST['r1m5']+(int)$_POST['r2m5']+(int)$_POST['r3m5'];
$six=(int)$_POST['r1m6']+(int)$_POST['r2m6']+(int)$_POST['r3m6'];
$seven=(int)$_POST['r1m7']+(int)$_POST['r2m7']+(int)$_POST['r3m7'];
$eight=(int)$_POST['r1m8']+(int)$_POST['r2m8']+(int)$_POST['r3m8'];
$nine=(int)$_POST['r1m9']+(int)$_POST['r2m9']+(int)$_POST['r3m9'];
$ten=(int)$_POST['r1m10']+(int)$_POST['r2m10']+(int)$_POST['r3m10'];
echo '<table border="5" cellspacing="2" cellpadding="2" bordercolor ="blue">
<tr>
<td> <font face="Arial">Student Name</font> </td>
<td> <font face="Arial">Total Marks</font> </td>
</tr>';
echo '<tr>
<td>'.$_POST['myname1'].'</td>
<td>'.$one.'</td>
</tr>
<tr>
<td>'.$_POST['myname2'].'</td>
<td>'.$two.'</td>
</tr>
<tr>
<td>'.$_POST['myname3'].'</td>
<td>'.$three.'</td>
</tr>
<tr>
<td>'.$_POST['myname4'].'</td>
<td>'.$four.'</td>
</tr>
<tr>
<td>'.$_POST['myname5'].'</td>
<td>'.$five.'</td>
</tr>
<tr>
<td>'.$_POST['myname6'].'</td>
<td>'.$six.'</td>
</tr>
<tr>
<td>'.$_POST['myname7'].'</td>
<td>'.$seven.'</td>
</tr>
<tr>
<td>'.$_POST['myname8'].'</td>
<td>'.$eight.'</td>
</tr>
<tr>
<td>'.$_POST['myname9'].'</td>
<td>'.$nine.'</td>
</tr>
<tr>
<td>'.$_POST['myname10'].'</td>
<td>'.$ten.'</td>
</tr>
</table>';
$numbers = array( $one,$two, $three, $four, $five, $six, $seven, $eight, $nine, $ten);rsort($numbers);
$arrlength = count($numbers);
$rank = 1;
$prev_rank = $rank;
echo "<h2 >Rankings</h2>";
for($x = 0; $x < $arrlength; $x++) {
if ($x==0) {
echo $numbers[$x]."- Rank ".($rank);
}
elseif ($numbers[$x] != $numbers[$x-1]) {
$rank++;
$prev_rank = $rank; echo $numbers[$x]."- Rank ".($rank);
}else{
$rank++;echo $numbers[$x]."- Rank ".($prev_rank);
}
echo "<br>";
}
echo "<h4>Students upto Rank 5 are Selected for Dream company";
}
?>

OUTPUT:

image.png

image.png

4.Design the following form and

image.png

i) create a shipping address database which gets the input from the form and

ii) store it into the database using PHP/MySQL.

Code:

<html>
<head>
<title>Naveen</title>
<script>
function validate()
{
var a=document.forms["myform"]["name"].value;
var b=document.forms["myform"]["address"].value; var
d=document.forms["myform"]["city"].value;
var e=document.forms["myform"]["state"].value; var
f=document.forms["myform"]["zip"].value; if(!a.match(/^[a-zA-Z ]+$/))
{
alert("Fill your name with alphabets!"); return false;
}
if(!b.match(/[a-zA-Z0-9. ]+$/))
{
alert("Please fill the address!"); return false;
}
if(!d.match(/^[a-zA-Z ]+$/))
{
alert("Please provide your city name!"); return false;
}
if(!e.match(/^[a-zA-Z ]+$/))
{
alert("Please provide your state name!"); return false;
}
if(!f.match(/^[0-9 ]+$/))
{
alert("Please provide zip code!"); return false;
}
return true;}
</script>
<style> caption{
background-color:blue; color:white; text-align:left; font-size:20;
}
table{
background-color:#FFFF99; width: 98%;
border: 2px solid black;
}
p{ color:red;
}
div
{
width: 40%;
margin-left: 20%;
margin-top: 2%;
}
td{
text-align:left;
}
</style>
</head>
<body>
<div>
<p>* Required</p>
<table align="center" cellpadding="5px">
<caption>Shipping Address</caption>
<form name="myform" method="post">
<tr><td><b style="color:red;">*</b><b>Name:</b></td><td><input type="text" name="name"></td></tr>
<tr><td><b style="color:red;">*</b><b>Address:</b></td><td><input type="text" name="address"></td></tr>
<tr><td><b style="color:red;">*</b><b>City:</b></td><td><input type="text" name="city"></td></tr>
<tr><td><b style="color:red;">*</b><b>State:</b></td><td><input type="text" name="state"></td></tr>
<tr><td><b style="color:red;">*</b><b>Zip:</b></td><td><input type="text" name="zip"></td></tr>
<tr><td></td><td><button onclick="validate()">Submit</button></td></tr>
</form>
</table>
</div>
<?php
error_reporting(0); if($_POST){
$name=$_POST['name'];
$address=$_POST['address'];
$city=$_POST['city'];
$state=$_POST['state'];
$zip=$_POST['zip'];
}
$servername = "localhost";
$username = "root";
$password = "";
$db = "shipping";
$conn = new mysqli($servername, $username, $password, $db); if
($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO customer(name,address,city,state,zip) VALUES
('$name','$address','$city','$state','$zip')";
if(mysqli_query($conn, $sql)){
echo "Database connected successfully";
} else{
$temp= "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
?>
</body>
</html>

OUTPUT:

image.png

image.png

5.Implement Shopping Cart application in the form given below using PHP sessions.

I) Usage of sessions is mandatory.

ii) The Shopping cart app should keep track of buyers information such as name of customer and product purchased.

iii) Display the same when buyer logins again.

Code:

index.php:

<?php
session_start();
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_GET["action"])) {
switch($_GET["action"]) {
    case "add":
        if(!empty($_POST["quantity"])) {
            $productByCode = $db_handle->runQuery("SELECT * FROM tblproduct WHERE code='" . $_GET["code"] . "'");
            $itemArray = array($productByCode[0]["code"]=>array('name'=>$productByCode[0]["name"], 'code'=>$productByCode[0]["code"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["price"], 'image'=>$productByCode[0]["image"]));

            if(!empty($_SESSION["cart_item"])) {
                if(in_array($productByCode[0]["code"],array_keys($_SESSION["cart_item"]))) {
                    foreach($_SESSION["cart_item"] as $k => $v) {
                            if($productByCode[0]["code"] == $k) {
                                if(empty($_SESSION["cart_item"][$k]["quantity"])) {
                                    $_SESSION["cart_item"][$k]["quantity"] = 0;
                                }
                                $_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"];
                            }
                    }
                } else {
                    $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
                }
            } else {
                $_SESSION["cart_item"] = $itemArray;
            }
        }
    break;
    case "remove":
        if(!empty($_SESSION["cart_item"])) {
            foreach($_SESSION["cart_item"] as $k => $v) {
                    if($_GET["code"] == $k)
                        unset($_SESSION["cart_item"][$k]);                
                    if(empty($_SESSION["cart_item"]))
                        unset($_SESSION["cart_item"]);
            }
        }
    break;
    case "empty":
        unset($_SESSION["cart_item"]);
    break;    
}
}
?>
<HTML>
<HEAD>
<TITLE>Simple PHP Shopping Cart</TITLE>
<link href="style.css" type="text/css" rel="stylesheet" />
</HEAD>
<BODY>
<form method="post" >
<table>
    <tr>
        <td colspan="2"><h2>Buyer's Details</h2></td>
    </tr>
 <tr>
 <td>Enter Your Name: </td>
 <td><input type="text" name="id" ></td>
 </tr>

 <tr>
 <td>Delivery Details: </td>
 <td><input type="text" name="amount" ></td>
 </tr>
 <tr>
 <td colspan="2"><input type="submit" name="submit" value="submit"></td>
 </tr>
</table> 

<div id="shopping-cart">
<div class="txt-heading">Shopping Cart</div>

<a id="btnEmpty" href="index.php?action=empty">Empty Cart</a>
<?php
if(isset($_SESSION["cart_item"])){
    $total_quantity = 0;
    $total_price = 0;
?>    
<table class="tbl-cart" cellpadding="10" cellspacing="1">
<tbody>
<tr>
    <th style="text-align:left;">Customer Name</th>
<th style="text-align:left;">Name</th>
<th style="text-align:left;">Code</th>
<th style="text-align:right;" width="5%">Quantity</th>
<th style="text-align:right;" width="10%">Unit Price</th>
<th style="text-align:right;" width="10%">Price</th>
<th style="text-align:center;" width="5%">Remove</th>
</tr>    
<?php        
    foreach ($_SESSION["cart_item"] as $item){
        $item_price = $item["quantity"]*$item["price"];
        ?>
                <tr>
                    <td><?php echo $_POST["id"] ?></td>
                <td><img src="<?php echo $item["image"]; ?>" class="cart-item-image" /><?php echo $item["name"]; ?></td>
                <td><?php echo $item["code"]; ?></td>
                <td style="text-align:right;"><?php echo $item["quantity"]; ?></td>
                <td  style="text-align:right;"><?php echo "$ ".$item["price"]; ?></td>
                <td  style="text-align:right;"><?php echo "$ ". number_format($item_price,2); ?></td>
                <td style="text-align:center;"><a href="index.php?action=remove&code=<?php echo $item["code"]; ?>" class="btnRemoveAction"><img src="icon-delete.png" alt="Remove Item" /></a></td>
                </tr>
                <?php
                $total_quantity += $item["quantity"];
                $total_price += ($item["price"]*$item["quantity"]);
        }
        ?>

<tr>
<td colspan="2" align="right">Total:</td>
<td align="right"><?php echo $total_quantity; ?></td>
<td align="right" colspan="2"><strong><?php echo "$ ".number_format($total_price, 2); ?></strong></td>
<td></td>
</tr>
</tbody>
</table>        
  <?php
} else {
?>
<div class="no-records">Your Cart is Empty</div>
<?php 
}
?>
</div>

<div id="product-grid">
    <div class="txt-heading">Products</div>
    <?php
    $product_array = $db_handle->runQuery("SELECT * FROM tblproduct ORDER BY id ASC");
    if (!empty($product_array)) { 
        foreach($product_array as $key=>$value){
    ?>
        <div class="product-item">
            <form method="post" action="index.php?action=add&code=<?php echo $product_array[$key]["code"]; ?>">
            <div class="product-image"><img src="<?php echo $product_array[$key]["image"]; ?>" width="100"  height="100"></div>
            <div class="product-tile-footer">
            <div class="product-title"><?php echo $product_array[$key]["name"]; ?></div>
            <div class="product-price"><?php echo "$".$product_array[$key]["price"]; ?></div>
            <div class="cart-action"><input type="text" class="product-quantity" name="quantity" value="1" size="2" /><input type="submit" value="Add to Cart" class="btnAddAction" /></div>
            </div>
            </form>
            </form> 
        </div>
    <?php
        }
    }
    ?>
</div>
</BODY>
</HTML>

dbcontroller.php:

<?php
class DBController {
    private $host = "localhost";
    private $user = "root";
    private $password = "";
    private $database = "tblproduct";
    private $conn;

    function __construct() {
        $this->conn = $this->connectDB();
    }

    function connectDB() {
        $conn = mysqli_connect($this->host,$this->user,$this->password,$this->database);
        return $conn;
    }

    function runQuery($query) {
        $result = mysqli_query($this->conn,$query);
        while($row=mysqli_fetch_assoc($result)) {
            $resultset[] = $row;
        }        
        if(!empty($resultset))
            return $resultset;
    }

    function numRows($query) {
        $result  = mysqli_query($this->conn,$query);
        $rowcount = mysqli_num_rows($result);
        return $rowcount;    
    }
}
?>

tblproduct.sql:

--
-- Table structure for table `tblproduct`
--

CREATE TABLE `tblproduct` (
  `id` int(8) NOT NULL,
  `name` varchar(255) NOT NULL,
  `code` varchar(255) NOT NULL,
  `image` text NOT NULL,
  `price` double(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tblproduct`
--

INSERT INTO `tblproduct` (`id`, `name`, `code`, `image`, `price`) VALUES
(1, 'FinePix Pro2 3D Camera', '3DcAM01', 'product-images/camera.jpg', 1500.00),
(2, 'EXP Portable Hard Drive', 'USB02', 'product-images/external-hard-drive.jpg', 800.00),
(3, 'Luxury Ultra thin Wrist Watch', 'wristWear03', 'product-images/watch.jpg', 300.00),
(4, 'XP 1155 Intel Core Laptop', 'LPN45', 'product-images/laptop.jpg', 800.00);

--
-- Indexes for table `tblproduct`
--
ALTER TABLE `tblproduct`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `product_code` (`code`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tblproduct`
--
ALTER TABLE `tblproduct`
  MODIFY `id` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
COMMIT;

Product image zip file link click here

OUTPUT:

image.png

image.png

6.PDFFreeConverter wants to provide an online Word to PDF file converter using PHP. The converter application has a form that gets the e-mail of the user in a textbox and a button for word file upload.

i) The application permits free conversion for file size less than 1MB and charges Rs. 50 above it. If a user is sending a free conversion request for multiple word files then the time interval between them must be a minimum of ยฝ an hour.

ii) Write the PHP script for checking the file types (If the file entered is not a word file then an error message must be specified in the form) and checking the file sizes.

Code:

Freepdf.html:

<html>
<body>
<head><title>Naveen</title></head>
<form enctype="multipart/form-data" method="POST" action="pdfupload.php">
<table border="0">
<tbody>
<tr>
<td align="left">E-mail:</td>
<td><input name="email" size="50"type="email"/></td>
</tr>
<tr>
<td align="left">File:</td>
<td><input accept="doc/docx" name="filename" size="40"
type="file"/></td>
</tr>
<tr>
<td><input name="Upload" type="submit" value="Upload" /></td>
</tr> </tbody></table>
</form></body></html>

pdfupload.php:

<?php
//if we clicked on Upload button
if($_POST['Upload'] == 'Upload') {
//make the allowed extensions
$goodExtensions= array( '.doc','.docx', );
$error='';
//set the current directory where you wanna upload the doc/docx files
$uploaddir = './ ';
$name = $_FILES['filename']['name'];//get the name of the file that will be uploaded
$min_filesize=1024;//set up a minimum file size(a doc/docx can't be lowerthen 1 MB)
$stem=substr($name,0,strpos($name,'.')); //take the file extension
$extension = substr($name, strpos($name,'.'),strlen($name)-1); //verify if the file extension is doc or docx
if(!in_array($extension,$goodExtensions))
$error='Extension not allowed<br>';
echo "<span> </span>"; //verify if the file size of the file being uploaded is greater then 1
if(filesize($_FILES['filename']['tmp_name']) < $min_filesize)
$error='File size is greater than 1 MB <br>You have to pay Rs. 50'."\n";
/*USER VALIDATION WHO UPLOADED BEFORE
if($_POST['email'] == 'ragul.v2018@vitstudent.ac.in')
$error.='You uploaded a file for few minutes before try after 30
minutes'."\n";*/
$uploadfile = $uploaddir.$stem.$extension;
$filename=$stem.$extension;
if ($error=='')
{
//upload the file to
if (move_uploaded_file($_FILES['filename']['tmp_name'], $uploadfile))
{ echo 'Your File is Uploaded for converting to PDF <br> Thank You.';
}}
else
echo $error;
}
?>

OUTPUT:

image.png

image.png

7.Consider the database schema for IPL_Cricket_2015 table with attributes team_name, number_of_matches_played, number_of_matches_won, number_of_matches_lost and points.

i) Design a PHP application with three forms for insertion, updation and display of match statistics. Perform insertion of initial team information in the table.

ii) Perform an updation of number of matches played, won, lost and points for a given team.

iii) Perform selection and display of match statistics for a specified team.

Code:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ipldb";
// Create connection
$conn = mysqli_connect($servername, $username,$password,$dbname);
// Check connection
if (!$conn) {
die("Connection failed: ".mysqli_connect_error()); }
if(isset($_POST['insert'])){
$sql = "INSERT INTO ipl (team_name , no_of_matches_played,no_of_matches_won ,no_of_matches_lost ,points )
VALUES
('".$_POST["name"]."','".$_POST["no"]."','".$_POST["won"]."','".$_POST["lost"]."','".$_POST["points"]."')";
$result = mysqli_query($conn,$sql);
}
if(isset($_POST['update']))
{ $name = $_POST['name'];
$no = $_POST['no'];
$won=$_POST['won'];
$lost = $_POST['lost'];
$points = $_POST['points'];
$sql1 = "UPDATE ipl SET no_of_matches_played = '$no', no_of_matches_won = '$won', no_of_matches_lost = '$lost',points ='$points' WHERE team_name= '$name'";
$result =mysqli_query($conn,$sql1); }
/*if(isset($_POST['display'])){
$name = $_POST['name'];
$sql2 = "select no_of_matches_played , no_of_matches_won,no_of_matches_lost ,points from ipl where
team_name='$name'"; $_GET['no'] ='no_of_matches_played';$_POST['won'] = ' no_of_matches_won';
$_POST['lost'] ='no_of_matches_lostlost';
$_POST['points'] = 'points';
$result =mysqli_query($conn,$sql2); }
*/
?>
<html>
<head><title>Naveen</title></head>
<script>
</script>
<body>
<form name="ipl" method="post" >
<table border="2" bgcolor="#ffff80">
<tr>
<td>Team Name</td>
<td><input type="text" name="name"/></td> </tr>
<tr>
<td>No of Matches Played</td>
<td><input type="number" name="no"/></td> </tr>
<tr>
<td>No of Matches Won</td>
<td><input type="number" name="won"/></td> </tr>
<tr>
<td>No of Matches Lost</td>
<td><input type="number" name="lost"/></td> </tr>
<tr>
<td>Points</td>
<td><input type="number" name="points"/></td> </tr>
<tr>
<td><button type="submit" name="insert" value="insert"/>insert</button> </td>
<td><button type="submit" name="update" value="update"/>update</button> <button type="submit" name="display" value="display"/>display</button> </td>
</tr>
</table>
</form>
</html>
<?php
if(isset($_POST['display'])){
$sql2 = "SELECT * FROM ipl where
team_name='".$_POST["name"]."'";
if($result = mysqli_query($conn,$sql2))
{ if(mysqli_num_rows($result) >0)
{ echo "<table border=2 bgcolor=#ffb3ec >";
echo "<tr>";
echo "<th> team name</th>";
echo "<th>No of matchesplayed</th>";
echo "<th>No of matches won</th>";
echo "<th>No of matches lost</th>";
echo "<th>points</th>";
echo "</tr>";
while($row =mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['team_name']. "</td>";
echo "<td>" . $row['no_of_matches_played'] ."</td>"; echo "<td>" . $row['no_of_matches_won'] ."</td>"; echo "<td>" . $row['no_of_matches_lost'] ."</td>"; echo "<td>" . $row['points'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found."; }
} else{
echo "ERROR: Could not able to execute $sql2 ".mysqli_error($conn);
}}
?>

OUTPUT:

INSERTION:

image.png

image.png

UPDATION:

image.png

image.png DISPLAY STATISTICS FOR A SPECIFIED TEAM:

image.png

8.Design a form as given below using different form elements and perform the validation on the following fields:

i) Phone number should contain digits only and restricted to ten digits.

iii) Number and Name should not be null. On submit, the form details should be displayed in a separate web page using PERL/PHP script.

Code:

index.php:

<html>
<head>
<title>Naveen</title>
<script>
function validate()
{
if( document.myForm.no.value == "" )
{
alert( "Please enter your number" ); return false;
}
if( document.myForm.name.value == "" )
{
alert( "Please enter your name" ); return false;
}
if(document.myForm.pno.value=="")
{
alert("Mobile number must be filled"); return false;
}
if(!/^[0-9]+$/.test(document.myForm.pno.value))
{
alert("Mobile number should contain only digits"); return false;
}
if(document.myForm.pno.value.length<10 ||
document.myForm.pno.value.length>10)
{
alert("Mobile number should contain exactly 10 numbers"); return false;
}
return true ;
}
</script>
</head>
<style>
td:nth-child(1)
{
background-color:#009999;
}
td:nth-child(2)
{
background-color: rgb(215, 215, 219);
}
body{
margin-top: 4%; background-color: #e6ffff;
}
</style>
</head>
<body>
<form name="myForm" onsubmit="return validate();" method="POST" action="naveen.php">
<h1 align="center">Student Information</h1>
<table align="center"border="1" cellpadding="10">
<tr>
<span class="one"><td>No</td></span>
<td><input type="text" name="no"/></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>Address</td>
<td>
<textarea name="address" cols="18" rows="5">
</textarea >
</td>
</tr>
<tr>
<td>City</td>
<td><input type="text" name="city"/></td>
</tr>
<tr>
<td>Phone no</td>
<td><input type="text" name="pno"></td>
</tr>
<tr><td>Gender</td>
<td>
<input type="radio" name="rad1" value="male"/>Male
<input type="radio" name="rad1"value="female"/>Female</td>
</tr>
<tr>
<td> Hobby
</td>
<td>
<input type="checkbox" name="hobby" value="Singing"/>Singing
<input type="checkbox" name="hobby" value="Bird Watching"/>bird watching
<input type="checkbox" name="hobby" value="Bird Watching"/>reading
</td>
</tr>
<tr>
<tr>
<td>Education</td>
<td>
<select name="edu">
<option value="B.E" selected>B.E</option>
<option value="Mtech">Mtech</option>
<option value="Btech">Btech</option>
</td>
</tr>
<tr>
<td></td>
<td>
<button type="submit" name="submit">Submit</button>
<input type="reset"value="reset"/></td></tr>
</table>
</form>

naveen.php:

<?php
//creating connection to database
$con=mysqli_connect("localhost","root","","studentdb") or die(mysqli_error());
//check whether submit button is pressed or not if((isset($_POST['submit'])))
{
//fetching and storing the form data in variables
$Number = $con->real_escape_string($_POST['no']);
$Name = $con->real_escape_string($_POST['name']);
$Address = $con->real_escape_string($_POST['address']);
$City = $con->real_escape_string($_POST['city']);
$PhoneNumber = $con->real_escape_string($_POST['pno']);
$Gender = $con->real_escape_string($_POST['rad1']);
$Hobby = $con->real_escape_string($_POST['hobby']);
$Education = $con->real_escape_string($_POST['edu']);
//query to insert the variable data into the database
$sql="INSERT INTO student2 (number, name,address, city, pno, gender, hobby, education) VALUES ('".$Number."','".$Name."','".$Address."',
'".$City."','".$PhoneNumber."','".$Gender."','".$Hobby."','".$Education."')";
//Execute the query and returning a message if(!$result = $con->query($sql)){
die('Error occured [' . $con->error . ']');} else
echo "<h1>"."Thank you!"."</h1>"; "<br> <br>";
echo "<h1>"."No:".$Number."</h1>";
echo "<h1>"."Name:".$Name."</h1>"; echo "<h1>"."Address:".$Address."</h1>";
echo "<h1>"."City:".$City."</h1>";
echo "<h1>"."Phone No:".$PhoneNumber."</h1>";
echo "<h1>"."Gender:".$Gender."</h1>"; echo "<h1>"."Hobby:".$Hobby."</h1>";
echo "<h1>"."Education:".$Education."</h1>";
}
?>
</body>
</html>

OUTPUT:

image.png

image.png

image.png

Did you find this article valuable?

Support naveenkumar j's Blog by becoming a sponsor. Any amount is appreciated!

ย