Survey details won't go through using php, ajax, Mysql

Joined
Oct 25, 2023
Messages
1
Reaction score
0
Hey guys, I'm new here. I was working on a school project about making a survey for a company. But I'm stuck. I made all the questions to be dynamically taken from the database and come with an answer part in form of an input.Clients table. So theres' my survey.php file code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<link rel="stylesheet" href="Sondage.css">
<script src="https://kit.fontawesome.com/0000000000.js" crossorigin="anonymous"></script>
<title>Survey UbiPharm Cameroon</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">
<img src="images/Ubipharm Cameroun.png" alt="Company Logo" class="logo">
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
</div>
<div id="content">
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="Survey.php">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="Comments.php">Comments</a>
</li>
<li class="nav-item">
<a class="nav-link" href="help.html">Help</a>
</li>
<li class="nav-item">
<a class="nav-link" href="LogoutClients.php">Logout</a>
</li>
</ul>
</div>
</div>
</div>
</nav>
<div class="container">
<h1>Customer Satisfaction Survey</h1>
<form id="survey-form" method="Post">
<div class="question">
<label for="clientName">Client Name:</label>
<input type="text" id="clientName" name="clientName" class="clientType" required>
</div>
<div class="rating-container2">
<input type="checkbox" class="checkbox" id="clientTypePharmacy" name="clientType" value="1">
<label for="clientTypePharmacy">Pharmacy</label>
<input type="checkbox" class="checkbox" id="clientTypeClinic" name="clientType" value="0">
<label for="clientTypeClinic">Clinic</label>
<input type="checkbox" class="checkbox" id="clientTypeSubDistributor" name="clientType" value="2">
<label for="clientTypeSubDistributor">Sub-distributor</label>
</div>
<script>
document.querySelectorAll('.checkbox').forEach(el => el.addEventListener('change', function () {
document.querySelectorAll('.checkbox').forEach(otherEl => {
if (otherEl !== el) otherEl.checked = false;
});
}));
</script>
<?php
$servername = "localhost"; // your host name
$username = "root"; // your database username
$password = ""; // your database password
$dbname = "second_ubipharm"; // your database name
// Create a new mysqli object for database connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Sql query to fetch all questions with their id_sondage as 1
$sql = "SELECT * FROM sondage_questions WHERE id_sondage = 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data for each row
while($row = $result->fetch_assoc()) {
?>
<form id="survey-form" method="post">
<div class="question">
<label for="q<?=$row['Question_id']?>" name="Quest"><?=$row['Question_id']?>. <?=$row['Question_body']?></label>
<div class="rating-container">
<select id="q<?=$row['Question_id']?>" name="q<?=$row['Question_id']?>rating" aria-describedby="q<?=$row['Question_id']?>ratingHelp" required>
<option selected disabled value="">Select rating</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</div>
</div>
<?php
}
} else {
echo "No more questions.";
}
$conn->close();
?>
<div class="comment-box">
<label for="comment">Additional comments or suggestions:</label>
<textarea id="comment" name="comment" placeholder="Enter your comment" maxlength="255"></textarea>
<p id="charCount">0 / 255 characters</p>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
$("#survey-form").submit(function(e) {
e.preventDefault();
$.ajax({
url: "ajax_survey.php", // Replace with the actual file name
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function(response) {
if (response.status === "success") {
// Handle success case
window.location.href = "thankyou.php"; // Redirect to thankyou.php
} else if (response.status === "error") {
// Handle error case
showErrorMessage("Error occurred while submitting the survey!");
}
},
error: function() {
// Handle error case
showErrorMessage("Error occurred while submitting the survey!");
}
});
});
function showErrorMessage(message) {
var toast = '<div class="toast" role="alert" aria-live="assertive" aria-atomic="true" style="position: absolute; top: 0; right: 0;">' +
'<div class="toast-header">' +
'<strong class="mr-auto">Error</strong>' +
'<button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">' +
'<span aria-hidden="true">&times;</span>' +
'</button>' +
'</div>' +
'<div class="toast-body">' +
message +
'</div>' +
'</div>';
$('#content').prepend(toast);
$('.toast').toast({ autohide: false }).toast('show');
}
});
</script>
<style>
.rating-container2 {
display: flex;
align-items: center;
gap: 10px;
}
.checkbox {
display: none;
}
.checkbox + label {
position: relative;
padding: 10px;
border-radius: 10px;
background-color: #f5f5f5;
cursor: pointer;
}
.checkbox + label:before {
content: "";
position: absolute;
top: 3px;
left: 3px;
width: 20px;
height: 20px;
border-radius: 50%;
background-color: #f5f5f5;
box-shadow: 3px 3px 6px #d9d9d9, -3px -3px 6px #ffffff;
transition: 0.3s;
}
.checkbox:checked + label:before {
background-color: #51D78E;
box-shadow: none;
}
.checkbox + label:after {
content: "";
position: absolute;
top: 7px;
left: 7px;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #f5f5f5;
transition: 0.3s;
}
.checkbox:checked + label:after {
background-color: #ffffff;
transform: translateX(10px);
}
</style>
</body>
</html>
Using an ajax_survey.php file:
<?php
$servername = "localhost"; // your host name
$username = "root"; // your database username
$password = ""; // your database password
$dbname = "second_ubipharm"; // your database name
// Create a new mysqli object for database connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Get the client name and type
$clientName = $_POST['clientName'];
$clientType = $_POST['clientType'];
// Insert the client data into the clients table
$insertClientSql = "INSERT INTO answers (nom_client, client_type) VALUES (?, ?)";
$stmt = $conn->prepare($insertClientSql);
$stmt->bind_param("ss", $clientName, $clientType);
if ($stmt->execute()) {
$clientId = $stmt->insert_id;
$stmt->close();
// Get the survey questions
$surveyQuestionsSql = "SELECT question_body FROM sondage_questions WHERE id_sondage = 1;";
$surveyQuestionsResult = $conn->query($surveyQuestionsSql);
if ($surveyQuestionsResult->num_rows > 0) {
while ($row = $surveyQuestionsResult->fetch_assoc()) {
$questionId = $row['Question_id'];
$questionBody = $row['Question_body'];
$answerRating = $_POST['q' . $questionId . 'rating'];
// Insert the answer into the answers table
$insertAnswerSql = "INSERT INTO answers (id_client, question_id, question_body, answer, comment) VALUES (?, ?, ?, ?)";
$stmt = $conn->prepare($insertAnswerSql);
$stmt->bind_param("iisi", $clientId, $questionId, $questionBody, $answerRating $comment);
$stmt->execute();
$stmt->close();
}
}
// Get the comment
$comment = $_POST['comment'];
// Calculate the average rating for the client
$averageRatingSql = "SELECT AVG(answer) AS average_rating FROM answers WHERE client_id = ?";
$stmt = $conn->prepare($averageRatingSql);
$stmt->bind_param("i", $clientId);
$stmt->execute();
$averageRatingResult = $stmt->get_result();
$averageRatingRow = $averageRatingResult->fetch_assoc();
$averageRating = $averageRatingRow['average_rating'];
$stmt->close();
// Update the client's average rating
$updateClientSql = "UPDATE clients SET average_rating = ? WHERE client_id = ?";
$stmt = $conn->prepare($updateClientSql);
$stmt->bind_param("di", $averageRating, $clientId);
$stmt->execute();
$stmt->close();
// Calculate the overall average rating
$overallAverageRatingSql = "SELECT AVG(average_rating) AS overall_average_rating FROM clients";
$overallAverageRatingResult = $conn->query($overallAverageRatingSql);
$overallAverageRatingRow = $overallAverageRatingResult->fetch_assoc();
$overallAverageRating = $overallAverageRatingRow['overall_average_rating'];
// Update the overall average rating
$updateOverallAverageSql = "UPDATE results SET average_rating = ?";
$stmt = $conn->prepare($updateOverallAverageSql);
$stmt->bind_param("d", $overallAverageRating);
$stmt->execute();
$stmt->close();
// Send the response
$response = array("status" => "success");



Sorry if i'm not posting correctly, it's my first time asking for help online. I've been struggling for the past weeks. Thank you for your help and have a great day!
echo json_encode($response);
} else {
// Send the error response
$response = array("status" => "error");
echo json_encode($response);
}
} else {
// Send the response for invalid request
$response = array("status" => "error");
echo json_encode($response);
}
$conn->close();
?>
ScreenShot_20231026021249.png
ScreenShot_20231026021350.png

ScreenShot_20231026021232.png
 
Joined
Nov 7, 2024
Messages
12
Reaction score
5
You could've used the 'code feature' for writing this long code. Have to scroll very much for reaching the replies.
 
Joined
Jan 13, 2025
Messages
27
Reaction score
7
Hey guys, I'm new here. I was working on a school project about making a survey for a company. But I'm stuck. I made all the questions to be dynamically taken from the database and come with an answer part in form of an input.Clients table. So theres' my survey.php file code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<link rel="stylesheet" href="Sondage.css">
<script src="https://kit.fontawesome.com/0000000000.js" crossorigin="anonymous"></script>
<title>Survey UbiPharm Cameroon</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">
<img src="images/Ubipharm Cameroun.png" alt="Company Logo" class="logo">
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
</div>
<div id="content">
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="Survey.php">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="Comments.php">Comments</a>
</li>
<li class="nav-item">
<a class="nav-link" href="help.html">Help</a>
</li>
<li class="nav-item">
<a class="nav-link" href="LogoutClients.php">Logout</a>
</li>
</ul>
</div>
</div>
</div>
</nav>
<div class="container">
<h1>Customer Satisfaction Survey</h1>
<form id="survey-form" method="Post">
<div class="question">
<label for="clientName">Client Name:</label>
<input type="text" id="clientName" name="clientName" class="clientType" required>
</div>
<div class="rating-container2">
<input type="checkbox" class="checkbox" id="clientTypePharmacy" name="clientType" value="1">
<label for="clientTypePharmacy">Pharmacy</label>
<input type="checkbox" class="checkbox" id="clientTypeClinic" name="clientType" value="0">
<label for="clientTypeClinic">Clinic</label>
<input type="checkbox" class="checkbox" id="clientTypeSubDistributor" name="clientType" value="2">
<label for="clientTypeSubDistributor">Sub-distributor</label>
</div>
<script>
document.querySelectorAll('.checkbox').forEach(el => el.addEventListener('change', function () {
document.querySelectorAll('.checkbox').forEach(otherEl => {
if (otherEl !== el) otherEl.checked = false;
});
}));
</script>
<?php
$servername = "localhost"; // your host name
$username = "root"; // your database username
$password = ""; // your database password
$dbname = "second_ubipharm"; // your database name
// Create a new mysqli object for database connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Sql query to fetch all questions with their id_sondage as 1
$sql = "SELECT * FROM sondage_questions WHERE id_sondage = 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data for each row
while($row = $result->fetch_assoc()) {
?>
<form id="survey-form" method="post">
<div class="question">
<label for="q<?=$row['Question_id']?>" name="Quest"><?=$row['Question_id']?>. <?=$row['Question_body']?></label>
<div class="rating-container">
<select id="q<?=$row['Question_id']?>" name="q<?=$row['Question_id']?>rating" aria-describedby="q<?=$row['Question_id']?>ratingHelp" required>
<option selected disabled value="">Select rating</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</div>
</div>
<?php
}
} else {
echo "No more questions.";
}
$conn->close();
?>
<div class="comment-box">
<label for="comment">Additional comments or suggestions:</label>
<textarea id="comment" name="comment" placeholder="Enter your comment" maxlength="255"></textarea>
<p id="charCount">0 / 255 characters</p>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
$("#survey-form").submit(function(e) {
e.preventDefault();
$.ajax({
url: "ajax_survey.php", // Replace with the actual file name
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function(response) {
if (response.status === "success") {
// Handle success case
window.location.href = "thankyou.php"; // Redirect to thankyou.php
} else if (response.status === "error") {
// Handle error case
showErrorMessage("Error occurred while submitting the survey!");
}
},
error: function() {
// Handle error case
showErrorMessage("Error occurred while submitting the survey!");
}
});
});
function showErrorMessage(message) {
var toast = '<div class="toast" role="alert" aria-live="assertive" aria-atomic="true" style="position: absolute; top: 0; right: 0;">' +
'<div class="toast-header">' +
'<strong class="mr-auto">Error</strong>' +
'<button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">' +
'<span aria-hidden="true">&times;</span>' +
'</button>' +
'</div>' +
'<div class="toast-body">' +
message +
'</div>' +
'</div>';
$('#content').prepend(toast);
$('.toast').toast({ autohide: false }).toast('show');
}
});
</script>
<style>
.rating-container2 {
display: flex;
align-items: center;
gap: 10px;
}
.checkbox {
display: none;
}
.checkbox + label {
position: relative;
padding: 10px;
border-radius: 10px;
background-color: #f5f5f5;
cursor: pointer;
}
.checkbox + label:before {
content: "";
position: absolute;
top: 3px;
left: 3px;
width: 20px;
height: 20px;
border-radius: 50%;
background-color: #f5f5f5;
box-shadow: 3px 3px 6px #d9d9d9, -3px -3px 6px #ffffff;
transition: 0.3s;
}
.checkbox:checked + label:before {
background-color: #51D78E;
box-shadow: none;
}
.checkbox + label:after {
content: "";
position: absolute;
top: 7px;
left: 7px;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #f5f5f5;
transition: 0.3s;
}
.checkbox:checked + label:after {
background-color: #ffffff;
transform: translateX(10px);
}
</style>
</body>
</html>
Using an ajax_survey.php file:
<?php
$servername = "localhost"; // your host name
$username = "root"; // your database username
$password = ""; // your database password
$dbname = "second_ubipharm"; // your database name
// Create a new mysqli object for database connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Get the client name and type
$clientName = $_POST['clientName'];
$clientType = $_POST['clientType'];
// Insert the client data into the clients table
$insertClientSql = "INSERT INTO answers (nom_client, client_type) VALUES (?, ?)";
$stmt = $conn->prepare($insertClientSql);
$stmt->bind_param("ss", $clientName, $clientType);
if ($stmt->execute()) {
$clientId = $stmt->insert_id;
$stmt->close();
// Get the survey questions
$surveyQuestionsSql = "SELECT question_body FROM sondage_questions WHERE id_sondage = 1;";
$surveyQuestionsResult = $conn->query($surveyQuestionsSql);
if ($surveyQuestionsResult->num_rows > 0) {
while ($row = $surveyQuestionsResult->fetch_assoc()) {
$questionId = $row['Question_id'];
$questionBody = $row['Question_body'];
$answerRating = $_POST['q' . $questionId . 'rating'];
// Insert the answer into the answers table
$insertAnswerSql = "INSERT INTO answers (id_client, question_id, question_body, answer, comment) VALUES (?, ?, ?, ?)";
$stmt = $conn->prepare($insertAnswerSql);
$stmt->bind_param("iisi", $clientId, $questionId, $questionBody, $answerRating $comment);
$stmt->execute();
$stmt->close();
}
}
// Get the comment
$comment = $_POST['comment'];
// Calculate the average rating for the client
$averageRatingSql = "SELECT AVG(answer) AS average_rating FROM answers WHERE client_id = ?";
$stmt = $conn->prepare($averageRatingSql);
$stmt->bind_param("i", $clientId);
$stmt->execute();
$averageRatingResult = $stmt->get_result();
$averageRatingRow = $averageRatingResult->fetch_assoc();
$averageRating = $averageRatingRow['average_rating'];
$stmt->close();
// Update the client's average rating
$updateClientSql = "UPDATE clients SET average_rating = ? WHERE client_id = ?";
$stmt = $conn->prepare($updateClientSql);
$stmt->bind_param("di", $averageRating, $clientId);
$stmt->execute();
$stmt->close();
// Calculate the overall average rating
$overallAverageRatingSql = "SELECT AVG(average_rating) AS overall_average_rating FROM clients";
$overallAverageRatingResult = $conn->query($overallAverageRatingSql);
$overallAverageRatingRow = $overallAverageRatingResult->fetch_assoc();
$overallAverageRating = $overallAverageRatingRow['overall_average_rating'];
// Update the overall average rating
$updateOverallAverageSql = "UPDATE results SET average_rating = ?";
$stmt = $conn->prepare($updateOverallAverageSql);
$stmt->bind_param("d", $overallAverageRating);
$stmt->execute();
$stmt->close();
// Send the response
$response = array("status" => "success");



Sorry if i'm not posting correctly, it's my first time asking for help online. I've been struggling for the past weeks. Thank you for your help and have a great day!
echo json_encode($response);
} else {
// Send the error response
$response = array("status" => "error");
echo json_encode($response);
}
} else {
// Send the response for invalid request
$response = array("status" => "error");
echo json_encode($response);
}
$conn->close();
?>
View attachment 2701View attachment 2702
View attachment 2700
  1. The form is nested within another form, which is not valid HTML. This can lead to unexpected behavior when submitting the form.
  2. The $comment variable is being used in the SQL statement before it is defined, which will cause an error.
  3. The bind_param method in the ajax_survey.php file is missing a comma between the $answerRating and $comment variables.
To resolve the issues identified, the following changes should be made:

  1. Ensure that there is only one form element wrapping all input fields. Remove the nested form declaration.
  2. Move the retrieval of the comment variable to the beginning of the POST handling section.
  3. Add a comma in the bind_param method to separate the $answerRating and $comment variables.
  4. There is no need to close the connection using $conn->close(); PHP does it automatically.
When posting code, especially long bits, use the </> button in the control panel to embed the code. It makes it easier to read and understand.
 
Joined
Sep 4, 2022
Messages
158
Reaction score
16
How to make good SQL queries by Php :

  • build a 'db' class ( OOP is easy , using it is 'clean code' )
  • when you have lot of 'SELECT' queries , get all $results in top of your code page.
  • populate your HTML through all $result vars all along your code using 'global $result;' instructions.

'global $var' makes $var reachable within all your Php scopes .
you can use $vars everywhere you want without bugs, in every location of your current Php scripts.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,260
Messages
2,571,039
Members
48,768
Latest member
first4landlord

Latest Threads

Top