Saving quiz results to database - php

I have created a multiple choice quiz/questionnaire. The questions and answers are pulling from the database and I have sessions setup on the webpage. At the minute the user can only print the webpage when they get their results.
I am using phpmyadmin and php for the quiz. I am currently pulling from one database table called questions with the fields, questionID, question, ansYes and ansNo.
<?
//Always start this first
session_start();
include ("dbConnect.php");
if ( isset( $_SESSION['user_email'] ) ) {
//Grab user data from the database using user email
} else {
// Redirect them to the login page
header("login.php");
}
$sql = "SELECT * FROM questions";
$dbQuery = $db->prepare($sql);
$dbQuery->execute();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>List</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<style>
/* CSS animation */
#-webkit-keyframes fadeIn {
0% {
opacity:0;
transform: scale(0.6);
}
100% {
opacity:100%;
transform: scale(1);
}
}
#keyframes fadeIn {
0% { opacity:0; }
100% { opacity:100%; }
}
</style>
<?php include("navIn.php"); ?>
<body>
<div class="container-fluid">
<br>
<?php
/*Printing out questions*/
if(!isset($_POST["submitForm"])) {
echo "<form method='post' action='checklist.php'>";
if (isset($_SESSION["first_name"])) {
echo '<span style="color:#000000;position:left; left:1060px;">Hello '.$_SESSION["first_name"].'!<br></span>';
}
while($dbRow = $dbQuery->fetch(PDO::FETCH_ASSOC)) {
echo"<div class=container-fluid text-center>";
echo "<h4>" . $dbRow["question"] . "</h4>";
echo "<h4><input type='radio' required name='" . $dbRow["questionID"] . "' value='Yes'> Yes <br></h4?";
echo "<h4><input type='radio' required name='" . $dbRow["questionID"] . "' value='No'> No <br><br></h4>";
echo "</div>";
}
echo "<input type='submit' name='submitForm' value='Submit'>";
echo "</form>";
echo"</div>";
} else {
if (isset($_SESSION["first_name"])) {
echo '<span style="color:#000000;position:left; left:1060px;">Hello '.$_SESSION["first_name"].'!<br></span>';
}
/*printing out results from questions */
echo"<div class=container-fluid text-center>";
while($dbRow = $dbQuery->fetch(PDO::FETCH_ASSOC)) {
if($_POST[$dbRow["questionID"]] == "Yes") {
echo '<h4 span style="color:blue;"> '.$dbRow["question"].'</span>';
/*echo "<h4>" .$dbRow["question"]."<br></h4><br>";*/
echo "<h4>" . $dbRow["ansYes"] . "</h4><br>";
} else {
echo '<h4 span style="color:blue;"> '.$dbRow["question"].'</span>';
/* echo "<h4>" .$dbRow["question"]."<br></h4><br>";*/
echo "<h4>" . $dbRow["ansNo"] . "</h4><br>";
}
}
echo"Click the button bellow to print this page!";
echo'<br><form> <input type=button value="Print me!" onClick="javascript:window.print()"> </form>';
echo"</div>";
}
?>
</div>
</body>
<?php include ("footer.php"); ?>
</html>
I would like to be able to save the users results so anytime they access checklist.php their results are there instead of having to print the page out.

Related

Putting items from a database into an HTML page and formatting them to be side by side

I have made a database and connected it properly. I am trying to display the database contents to be side by side. I have tried to create a div but everything is jumbled up. The items are floating left but are not showing up side by side.
<html>
<head>
<style>
.menu{
float:left;
}
p{
text-align:left;
float:left;
inline-size:300px;
overflow:hidden;
}
</style>
</head>
<body>
<main>
<section>
<h3>Inventory</h3>
<?php include 'db.php';
$ID = $_GET['ID'];
$query = "SELECT * FROM inventory ORDER BY ID";
/* Try to query the database */
if ($result = $mysqli->query($query)) {
// Don't do anything if successful
}
else
{
echo "Sorry, an item with the ID of $ID cannot be found " . mysql_error()."<br>";
}
while ($result_ar = mysqli_fetch_assoc($result)) {
//Display food image and image source
$image = $result_ar['Image'];
echo "<div class = 'menu'>" . $result_ar['Image_Source'] . "<br>".
"<IMG src= 'images/$image' style = height:200px; width:300px;>". "</div>";
//Display name and description
echo "<p>".$result_ar['Name'] . "<br>"
. $result_ar['Description'] ."</p>";
}
$mysqli->close();
?>
</section>
</main>
</body>
</html>

how to add ajax to a php file

how could i add ajax to my php file ,that when i delete an item of the list the data should automatically reload and my list should be updated to the new list?
I made list of all my data with a button of delete
here is my code for php
<?php
function tableV1 ($row) {
echo '<tr>';
echo '<td>' .$row['id']. '</td>';
echo '<td>' . $row['firstname'] . '</td>';
echo '<td>' . $row['lastname'] . '</td>';
}
$dbPassword = "micr2001";
$dbUserName = "PHPFundamentals";
$dbServer = "localhost";
$dbName = "PHPfundamentals";
// Create connection
$conn = mysqli_connect($dbServer , $dbUserName , $dbPassword,$dbName) or die("unable to connect to host");
// Check connection
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css">
<style type="text/css">
table {font-size: 27px; }
tbody {}
td {border-bottom: 1px solid bisque;padding:15px;}
th {border-bottom: 1px solid bisque;padding:15px;}
thead {}
tr {}
</style>
</head>
<body>
<center>
<table>
<thead>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Action</th>
<th> </th>
</thead>
<?php
// Takes all the results from the table with genre 5.
$sql = "SELECT id,firstname, lastname FROM persons";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
tableV1($row);
$rowId = $row['id'];
$first_name = $row['firstname'];
$last_name = $row['lastname'];
echo '<td>'
. ' <a class="edit_btn btn" href=edit.php?id='.$rowId.'&lname='.$last_name.'&fname='.$first_name. '>Edit</a>'
. ' </td>';
echo '<td><a class="del_btn btn" href=delete.php?id='.$rowId.'>Delete</a></td>';
echo' </tr>';
}
} else {
echo '<tr><td colspan="3">0 results</td></tr>';
}
?>
</table>
</center>
</body>
</html>
<?php
$conn->close();
?>
here is the code for delete.php
<?php
require 'connection.php';
$id = $_GET['id'];
$sql = "DELETE FROM persons WHERE id = ".$id ;
if(mysqli_query($conn, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
mysqli_close($conn);
?>
i want the item that i delete should get off my list
Why do you even need AJAX? As user clicks Delete, she / he is redirected to the delete.php script. In that script after sucessful deletion you should just redirect the user back to the listing. This can be achieved by HTTP redirect (https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection). Keep it simple!

PHP textarea problem, $_POST returns empty array

I already read a lot of google results about my problem and any methods don't help me. print_r($_POST) returns me empty array, i try fix this for two days. I was try really a lot of methods, from stackoverlow, from other websites and any from this methods don't work for me. $_POST is empty array.
My code
<?php
require_once 'config.php';
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function updateRec($tbl, $index) {
if($GLOBALS['connection'] !== null) {
$connection = $GLOBALS['connection'];
if($tbl == 'users') {
//if(isset($_POST['id']) && isset($_POST['username']) && isset($_POST['password']) && isset($_POST['rank'])) {
$id = $_POST['id'];
$login = test_input($_POST['username']);
$pass = password_hash(test_input($_POST['password']), PASSWORD_DEFAULT);
$rank = test_input($_POST['rank']);
$q = "UPDATE $tbl SET id='$id', username='$login', password='$pass', rank='$rank' WHERE id='$index'";
echo "<script type='text/javascript'>alert(".$login.");</script>";
//}
}
//mysqli_query($connection, $q);
header('location: '.$tbl.'.php?page=1');
}
}
function createForm($a) {
if ($a === 'edit') {
echo "<center><div id='editForm'>";
$q = "DESCRIBE ".$_GET['tbl']."";
$qr = mysqli_query($GLOBALS['connection'], $q);
while ($rw = mysqli_fetch_array($qr)) {
echo "<tr>";
echo "<td> " . $rw['Field'] . "</td><br/>";
echo "<td><textarea rows='4' cols='50' name='".$rw['Field']."' required></textarea></td>";
echo "<br/>";
echo "</tr>";
}
echo '<form action="forms.php?action=saveE&tbl='.$_GET['tbl'].'&row='.$_GET['row'].'" method="post" accept-charset="utf-8" style="transform: translate(5vw, -20vh); height: 0vh;">';
echo '<button id="fButton" name="submit" style="">Zapisz</button></form>'. '<button id="fButton" style="transform: translate(5vw, 8vh); margin-left: 6%;">Anuluj</button>';
print_r($_POST);
echo "</div></center>";
};
if ($a === 'saveE') {
updateRec($_GET['tbl'], $_GET['row']);
};
}
?>
<!DOCTYPE html>
<html lang="pl">
<head>
<title>Control Panel</title>
<link rel="stylesheet" type="text/css" href="global.css">
<meta charset="utf-8" name="viewport" content="width=device.width, initial-scale=1">
</head>
<body>
<header>
<p>Admin Control Panel</p>
</header>
</body>
</html>
My textarea
while ($rw = mysqli_fetch_array($qr)) {
echo "<tr>";
echo "<td> " . $rw['Field'] . "</td><br/>";
echo "<td><textarea rows='4' cols='50' name='".$rw['Field']."' required></textarea></td>";
echo "<br/>";
echo "</tr>";
}
I was too try use id instead name and it don't help me.

Why is PHP not displaying all values correctly?

Unfortunately my code isn't working quite well.
The source code:
<!DOCTYPE html>
<html>
<head>
<title>Query data from News database and display in table</title>
<meta charset="UTF-8">
<meta name="description" content="" />
<meta name="author" content="WRBikAir" />
<meta name="keywords" content="" />
<style>
table, th, td{
border: 1px solid black;
}
</style>
</head>
<body>
<?php
error_reporting(E_ALL);
echo "Test 1";
$con = mysqli_connect("mysql.hostinger.com","u441817146_admin","CBGApp","u441817146_cbg");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM News";
if ($result = mysqli_query($con, $sql)) {
echo "<table>";
while($row = $result->fetch_assoc()) {
$r = json_encode($row);
echo "<tr><td>" . $r['NID'] . "</td><td>" . $r['headline'] . "</td><td>" . $row['text'] . "</td><td>" . $r['timestamp'] . "</td></tr>";
}
echo "</table>";
} else {
echo "no result.";
}
mysqli_close($con);
echo "2";
?>
</body>
</html>
Everything works fine, except of the output of the NID, headline and timestamp. There are all '{'. Does it mean, that there is now value? because if I simply print them out (encoded of course) there are values e.g.:
{"NID":"1","headline":"Testartikel 2","text":"test test test","timestamp":"15.11.2017, 18:13"}
Does somebody knows a solution?
You are using $result 2 times on $result = mysqli_query($con, $sql) and in your foreach loop. I changed the one in the foreach loop to $results instead of $result.
Also try turning on error reporting using:
error_reporting(E_ALL);
Try using:
<!DOCTYPE html>
<html>
<head>
<title>Query data from News database and display in table</title>
<meta charset="UTF-8">
<meta name="description" content="" />
<meta name="author" content="WRBikAir" />
<meta name="keywords" content="" />
<style>
table, th, td{
border: 1px solid black;
}
</style>
</head>
<body>
<?php
echo "Test 1";
$con = mysqli_connect(CENSORED (but working in other classes fine);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM News";
if ($result = mysqli_query($con, $sql)) {
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object()) {
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo "<table>";
foreach ($resultArray as $results) {
$r = json_encode($results);
echo "<tr><td>" . $results['headline'] . "</td><td>" . $results['text'] . "</td></tr>";
}
echo "</table>"
}
mysqli_close($con);
echo "2";
?>
</body>
</html>
For everybody who need the working answer.
Thank you to MasterOfCoding, GrumpyCrouton, Paul Spiegel and prodigitalson.
Special thanks to tadman for the insider information.
Now the code:
<!DOCTYPE html>
<html>
<head>
<title>Query data from News database and display in table</title>
<meta charset="UTF-8">
<meta name="description" content="" />
<meta name="author" content="WRBikAir" />
<meta name="keywords" content="" />
<style>
table, th, td{
border: 1px solid black;
}
</style>
</head>
<body>
<?php
error_reporting(E_ALL);
echo "Test 1";
$con = mysqli_connect("...","...","...","...");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM News";
if ($result = mysqli_query($con, $sql)) {
echo "<table>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row['NID'] . "</td><td>" . $row['headline'] . "</td><td>" . $row['text'] . "</td><td>" . $row['timestamp'] . "</td></tr>";
}
echo "</table>";
} else {
echo "no result.";
}
mysqli_close($con);
echo "2";
?>
</body>
</html>

Load Google Maps on webpage using Javascript and PHP through drop down form

I am having two drop down lists on a html page. The data is coming from a mysql database and contains information like latitude, longitude and address. The user selects one item from the drop down and clicks on submit.
At this stage, I want to display a google map and put a marker at the latitude and longitude. Then, when the user selects the option from second drop down, I want to just add a marker on that map.
Currently, I am able to load the map once he clicks the submit from first drop down but all the options I tried to drop the pins are not working.
Here is the code I have achieved till now:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once('auth.php');
include ('LoginConfig.php');
include ('FetchAgentDetails.php');
include ('FetchDeliveryDetails.php');
?>
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Delivery Management System</title>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyA0Rm5aK0BYu1f_TzhjkG97cchHHlQfrQY&sensor=false">
</script>
<style type="text/css">
html {height:100%}
body {height:100%;margin:0;padding:0}
#googleMap {height:100%}
</style>
<script>
function initialize()
{
var mapProp = {
center:new google.maps.LatLng(51.508742,-0.120850),
zoom:5,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap")
,mapProp);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<style type="text/css">
<!--
.style1 {
font-size: 20px;
font-weight: bold;
}
-->
</style>
<style type="text/css">
table.collection {width:250px;border:2px solid black;border-style: outset;border-collapse:collapse;}
table.collection tr {background-color:#fff; border-bottom: 1px #99b solid;padding:10px;}
table.collection tr:hover {background-color:#ffe;}
table.collection td {display:table-cell;border-bottom: 1px #99b solid; padding:10px;}
table.collection td a {text-decoration:none; display:table-row; padding:0px; height:100%;}
</style>
</head>
<body bgcolor="#8E8E38"
<div style="clear: right;">
<p align="left" class="style1">Welcome Delivery Manager! </p>
<img style="position: absolute; top: 0; right: 0;" src="./Images/logo.jpg" alt="Company Logo" width="90" height="60" align="middle"></img>
</div>
<p align="left">Home</p>
<hr></hr>
<!-- START Main Wrap -->
<form method="post">
<fieldset>
<div style="clear: left;float:left;">
<label for="deliveryList">Delivery Items:</label>
<select name="deliveryList" id="deliveryList">
<option value="Select delivery item" selected="selected">Select delivery item</option>
<?php
$deliveryHandler = new FetchDeliveryDetails();
$itemNameArray = $deliveryHandler->getItemNames();
foreach ($itemNameArray as $innerArray) {
if (is_array($innerArray)) {
$value = $innerArray['itemName'];
echo "<option value=\"$value\"";
if (isset($_POST['deliveryList']) && $_POST['deliveryList'] == $value)
echo 'selected';
echo ">" . $value . "</option>\n";
}
}
?>
</select>
<input type="submit" name="submit" id="submit" value="Submit"/>
</div>
<div style="clear: right;float:right;">
<label for="agentList">Avaliable Agent:</label>
<select name="agentList" id="agentList">
<option value="" selected="selected">Select agent to assign</option>
<?php
$agentHandler = new FetchAgentDetails();
$agentNameArray = $agentHandler->getAgentNames();
foreach ($agentNameArray as $innerArray) {
if (is_array($innerArray)) {
$agentId = $innerArray['agentId'];
$firstNameValue = $innerArray['firstname'];
$lastNameValue = $innerArray['lastname'];
$fullName = $firstNameValue . ' ' . $lastNameValue;
echo "<option value=\"$agentId\">$fullName</option>\n";
}
}
?>
</select>
<input type="submit" name="agentSubmit" id="agentSubmit" value="Check Location"/>
</div>
</fieldset>
</form>
<?php
if (isset($_POST['deliveryList'])) {
$selectedItemName = $_POST['deliveryList'];
$deliveryHander = new FetchDeliveryDetails();
$itemDetailsArray = $deliveryHander->getAllDeliveryDetails($selectedItemName);
foreach ($itemDetailsArray as $valuesArray) {
$itemNameValue = $valuesArray['itemName'];
$itemDescriptionValue = $valuesArray['itemDescription'];
$ownerFirstname = $valuesArray['firstName'];
$ownerLastname = $valuesArray['lastName'];
$dateAdded = $valuesArray['dateAdded'];
$deliveryDate = $valuesArray['deliveryDate'];
$deliveryAddress = $valuesArray['deliveryAddress'];
$deliveryLatitude = $valuesArray['deliveryLatitude'];
$deliveryLongitude = $valuesArray['deliveryLongitude'];
$assignedAgent = $valuesArray['assignedAgentId'];
if ($assignedAgent == 0) {
$assignedAgent = "-";
}
echo "<table border=\"1\" align=\"left\" class =\"collection\">\n";
echo "<tr>\n";
echo "<td >Item Name:<b>$itemNameValue</td>\n";
echo "</tr>\n";
echo "<tr>\n";
echo "<td>Item Description: <b>$itemDescriptionValue</td>\n";
echo "</tr>\n";
echo "<tr>\n";
echo "<td>Owner Name: <b>$ownerFirstname $ownerLastname</td>\n";
echo "</tr>\n";
echo "<tr>\n";
echo "<td>Date Added: <b>$dateAdded</td>\n";
echo "</tr>\n";
echo "<tr>";
echo "<td>Delivery Date: <b>$deliveryDate</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Delivery Address: <b>$deliveryAddress</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Assigned Agent: <b>$assignedAgent</td>";
echo "</tr>";
echo "</table>";
echo "<div id=\"googleMap\" style=\"width:500px;height:380px;\"></div>";
}
}
if (isset($_POST['agentList'])) {
}
?>
</body>
</html>
I almost forgot, this is my first PHP application, in fact my first web application. So please go easy on me. Point out other errors also, but please stick to the question.
Ok got it working by using iframe :) and a bit of php
Reference:
http://www.youtube.com/watch?v=HTm-3Cduafw
echo "<iframe style =\"display: block;
width: 800px;
padding-top: 2px;
height: 400px;
margin: 0 auto;
border: 0;\" width=\"425\" height=\"350\" align=\"center\" frameborder=\"0\" scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\"
src=\"https://maps.google.com/maps?f=d&source=s_d&saddr=$agent_map_url&
daddr=$map_url&hl=en&z=10&t=m&mra=ls&ie=UTF8&output=embed\"></iframe><br/>";

Categories