loop issue in sql data verification - php

Hi this is my PHP code for attendance sign in, but it enters multiple entry when i remove the while loop.
Please help me to get which loop is better to this coding...
It is working fine when i remove the while loop. However it is possible to enter multiple entries in attendance.
<?php
$conn = mysqli_connect("localhost", "Vijay", "vijay123", "test");
if (mysqli_connect_errno())
{
echo "Unable to connect the Server" . mysqli_connect_error();
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// getting details from form
$EmployeeNoA = mysqli_real_escape_string($conn, $_POST['EmployeeNoA']);
$EmployeeNameA = mysqli_real_escape_string($conn, $_POST['EmployeeNameA']);
$Shift = mysqli_real_escape_string($conn, $_POST['Shift']);
$SignInDay = mysqli_real_escape_string($conn, $_POST['SignInDay']);
$SignInDate = mysqli_real_escape_string($conn, $_POST['SignInDate']);
$SignInTime = mysqli_real_escape_string($conn, $_POST['SignInTime']);
if ($Shift == "0")
{
echo "<script>alert('Please Select the Shift!');</script>";
}
else
{
// $rowcount = mysqli_query($conn, "SELECT * From attend");
// $rowCount = mysqli_num_rows($rowcount);
$ver = mysqli_query($conn, "SELECT * FROM attend WHERE EmployeeNoA='$EmployeeNoA' && SignInDate='$SignInDate'");
while ($view = mysqli_fetch_array($ver, MYSQL_ASSOC)) // **it is repeatedly running and store multiple data and error message.
{
if ($SignInDate != $view['SignInDate'])
{
$sql = "INSERT INTO attend (EmployeeNoA, EmployeeNameA, Shift, Day, SignInDate, SignInTime) VALUES ('$EmployeeNoA', '$EmployeeNameA', '$Shift', '$SignInDay', '$SignInDate', '$SignInTime')";
if (!mysqli_query($conn, $sql))
{
echo mysqli_error($conn);
}
else
{
echo "<script>alert ('You have Signed In!');</script>";
}
}
else
{
echo "<script>alert ('You have ALREADY Signed In!');</script>";
}
}
}
}
?>
Here Pls find my html
<h2 style="text-align:center;margin-bottom:1.5em;margin-top:1.5em;font-family:sans-serif">ATTENDANCE SIGN IN</h2>
<form action="<?php ($_SERVER['PHP_SELF']);?>" method="POST">
<div style="margin-top:20px;margin-left:20px;">
<table cellpadding="5">
<tr><td><label>Employee No:</label></td><td><input type="text" name="EmployeeNoA" value="<?php echo $EmployeeNo; ?>" readonly="readonly"></td></tr>
<tr><td><label>Employee Name:</label></td><td><input type="text" name="EmployeeNameA" value="<?php echo $EmployeeName; ?>" readonly="readonly"></td></tr>
<tr><td style="vertical-align:top;"><label>Shift:</label></td><td>
<select name="Shift" id="Shift">
<option value="0">-- Select --</option>
<option value="Shift1">I Shift</option>
<option value="Shift2">IA Shift</option>
<option value="Shift3">II Shift</option>
<option value="Shift4">General Shift</option>
<option value="Shift5">General A Shift</option>
</select>
<!--<tr><td style="vertical-align:top;"><label>Shift:</label></td><td style="line-height:1.6em; text-align:justify;font-weight:bold;"><input type="radio" name="shift" value="I"> I Shift <span style="font-weight:normal;font-size:small;color:grey;">6:00 - 3:00</span><br/><input type="radio" name="shift" value="IA"> IA Shift <span style="font-weight:normal;font-size:small;color:grey;">7:00 - 4:00</span><br/><input type="radio" name="shift" value="II"> II Shift<br/><input type="radio" name="shift" value="G"> Gen. Shift <span style="font-weight:normal;font-size:small;color:grey;">8:00 - 5:00</span><br/><input type="radio" name="shift" value="G1"> G I Shift <span style="font-weight:normal;font-size:small;color:grey;">10:00 - 7:00</span>--><td></tr>
<tr><td><label>Day:</label></td><td><input style="text-align:center;" type="text" name="SignInDay" value="<?php date_default_timezone_set('Asia/Kolkata'); echo date('l'); ?>" readonly="readonly"></td></tr>
<tr><td><label>SignIn Date:</label></td><td><input style="text-align:center;" type="text" name="SignInDate" value="<?php date_default_timezone_set('Asia/Kolkata'); echo date('Y-m-d'); ?>" readonly="readonly"></td></tr>
<tr><td><label>SignIn Time:</label></td><td><input style="text-align:center;color:blue;" type="text" name="SignInTime" value="<?php date_default_timezone_set('Asia/Kolkata'); echo date('H:i:s'); ?>" readonly="readonly"></td></tr>
<tr><td style="text-align:center;" colspan="2"><input style="margin-top:20px;" type="submit" name="signin" value="Sign In">         <button type="close" name="close" onclick="closeWin()">Exit</button></td></tr>
</table>
</div>
</form>

It looks like you just want to test whether the first query returns any rows. Use:
$ver = mysqli_query($conn, "SELECT COUNT(*) AS count FROM attend WHERE EmployeeNoA='$EmployeeNoA' && SignInDate='$SignInDate'");
$row = mysqli_fetch_assoc($ver);
if ($row['count'] == 0) {
sql = "INSERT INTO attend (EmployeeNoA, EmployeeNameA, Shift, Day, SignInDate, SignInTime) VALUES ('$EmployeeNoA', '$EmployeeNameA', '$Shift', '$SignInDay', '$SignInDate', '$SignInTime')";
if (!mysqli_query($conn, $sql)) {
echo mysqli_error($conn);
} else {
echo "<script>alert ('You have Signed In!');</script>";
}
} else {
echo "<script>alert ('You have ALREADY Signed In!');</script>";
}

Related

Updating a specific row in an SQL table selected by a drop-down list in PHP

I've been making a Car Parking System for a school project, and I've been stuck on this problem for a while now. The goal of the project is to have a maximum of 10 parking slots, where the user is able to select which slot they want to be in from a drop-down box. So far, I've managed to get the drop-down box to show along with the 10 parking slots, but I could never get it to update on the row selected on the drop-down box. Here are my codes so far:
<?php
$CustomerName = $PlateNumber = $CarName = $CarColor = $Slot = "";
$CustomerNameErr = $PlateNumberErr = $CarNameErr = $CarColorErr = "";
if($_SERVER["REQUEST_METHOD"] == "POST")
{
if(empty($_POST["CustomerName"]))
{
$CustomerNameErr = "Please fill out this field";
}
else
{
$CustomerName = $_POST["CustomerName"];
}
if(empty($_POST["PlateNumber"]))
{
$PlateNumberErr = "Please fill out this field";
}
else
{
$PlateNumber = $_POST["PlateNumber"];
}
if(empty($_POST["CarName"]))
{
$CarNameErr = "Please fill out this field";
}
else
{
$CarName = $_POST["CarName"];
}
if(empty($_POST["CarColor"]))
{
$CarColorErr = "Please fill out this field";
}
else
{
$CarColor = $_POST["CarColor"];
}
}
?>
<form class="logintext" method="POST" action="<?php htmlspecialchars("PHP_SELF");?>">
<br><b>Register Parking</b><br><br>
<!-- Slot select-->
Select Slot: <select name="slots">
<?php
$mysqli = NEW mysqli('localhost','root','','sad');
$slot_query = $mysqli->query("SELECT slot FROM parkingrecords");
while ($rows = $slot_query->fetch_assoc())
{
$SlotVal = $rows['Slot'];
echo "<option value='".$rows['Slot']."'>".$rows['Slot']."</option>";
}
?>
</select><br><br>
<!-- fill-up form; this is the data that replaces the "empty" slots on the table-->
Customer Name: <input type="text" name="CustomerName" value="<?php echo $CustomerName ?>"><br>
<span class="error"><?php echo $CustomerNameErr; ?></span><br>
Plate Number: <input type="text" name="PlateNumber" value="<?php echo $PlateNumber ?>"><br>
<span class="error"><?php echo $PlateNumberErr; ?></span><br>
Car Name: <input type="text" name="CarName" value="<?php echo $CarName ?>"><br>
<span class="error"><?php echo $CarNameErr; ?></span><br>
Car Color: <input type="text" name="CarColor" value="<?php echo $CarColor ?>"><br>
<span class="error"><?php echo $CarColorErr; ?></span><br>
<input type="submit" value="Register">
</form>
<?php
include("carpark_connections.php");
if($Slot && $CustomerName && $PlateNumber && $CarName && $CarColor)
{
$query = mysqli_query($connections, "UPDATE parkingrecords SET CustomerName = '$CustomerName', PlateNumber = '$PlateNumber', CarName = '$CarName', CarColor = '$CarColor' WHERE Slot = '$SlotVal' ");
echo "<script language = 'javascript'>alert('You have been registered!')</script>";
echo "<script>window.location.href='ParkNow.php';</script>";
} ...
Nothing happens when I try to submit the update form. The data I type in doesn't seem to go anywhere at all, but it still executes the query since the javascript alert is working. I don't know what I'm missing here. Any help would be appreciated!
EDIT: I fixed a little bit of the code and now instead of nothing happening, it just keeps on updating the 10th slot no matter which slot i select on the dropdown.
Below is an updated code please replace it with this updated code.
<?php
$CustomerName = $PlateNumber = $CarName = $CarColor = $Slot = "";
$CustomerNameErr = $PlateNumberErr = $CarNameErr = $CarColorErr = "";
if($_SERVER["REQUEST_METHOD"] == "POST")
{
if(empty($_POST["CustomerName"])){
$CustomerNameErr = "Please fill out this field";
}else{
$CustomerName = $_POST["CustomerName"];
}
if(empty($_POST["PlateNumber"])){
$PlateNumberErr = "Please fill out this field";
}else{
$PlateNumber = $_POST["PlateNumber"];
}
if(empty($_POST["CarName"])){
$CarNameErr = "Please fill out this field";
}else{
$CarName = $_POST["CarName"];
}
if(empty($_POST["CarColor"])){
$CarColorErr = "Please fill out this field";
}else{
$CarColor = $_POST["CarColor"];
}
if(empty($_POST["slots"])){
$SlotErr = "Please fill out this field";
}else{
$Slot = $_POST["slots"];
}
}
?>
<form class="logintext" method="POST" action="<?php htmlspecialchars("PHP_SELF");?>">
<br><b>Register Parking</b><br><br>
<!-- Slot select-->
Select Slot: <select name="slots">
<?php
$mysqli = NEW mysqli('localhost','root','','sad');
$slot_query = $mysqli->query("SELECT slot FROM parkingrecords");
while ($rows = $slot_query->fetch_assoc())
{
$SlotVal = $rows['Slot'];
echo "<option value='$SlotVal'>$SlotVal</option>";
}
?>
</select><br><br>
<!-- fill-up form; this is the data that replaces the "empty" slots on the table-->
Customer Name: <input type="text" name="CustomerName" value="<?php echo $CustomerName ?>"><br>
<span class="error"><?php echo $CustomerNameErr; ?></span><br>
Plate Number: <input type="text" name="PlateNumber" value="<?php echo $PlateNumber ?>"><br>
<span class="error"><?php echo $PlateNumberErr; ?></span><br>
Car Name: <input type="text" name="CarName" value="<?php echo $CarName ?>"><br>
<span class="error"><?php echo $CarNameErr; ?></span><br>
Car Color: <input type="text" name="CarColor" value="<?php echo $CarColor ?>"><br>
<span class="error"><?php echo $CarColorErr; ?></span><br>
<input type="submit" value="Register">
</form>
<?php
include("carpark_connections.php");
if($Slot && $CustomerName && $PlateNumber && $CarName && $CarColor)
{
$query = mysqli_query($connections, "UPDATE parkingrecords SET CustomerName = '$CustomerName', PlateNumber = '$PlateNumber', CarName = '$CarName', CarColor = '$CarColor' WHERE Slot = '$Slot' ");
echo "<script language = 'javascript'>alert('You have been registered!')</script>";
echo "<script>window.location.href='ParkNow.php';</script>";
}
You are missing a part where should you accept the $_POST['slots']
if(empty($_POST["slots"]))
{
$slotErr = "Please select value for this field";
}
else
{
$slot = $_POST["slots"];
}

Not Able to save data to Mysql database

I am developing a simple attendance system in which the attendance is taken by the a teacher and then saved to the database. However, I am having a problem with saving the data to the database. when i click on "submit attendance" the data won't be submitted to the database. i use register.php to register students but take the attendance in different file.
Below is the code i use to submit. Can someone help me? Thanks.
sorry the file i shared was supposed to save data to mysql database. Below is the file which takes the data and am still having the problem for saving it.
this is the teacher file to take the attendance
teacher.php
<?php
$pageTitle = 'Take Attendance';
include('header.php');
require("db-connect.php");
if(!(isset($_COOKIE['teacher']) && $_COOKIE['teacher']==1)){
echo 'Only teachers can create new teachers and students.';
$conn->close();
include('footer.php');
exit;
}
//get session count
$query = "SELECT * FROM attendance";
$result = $conn->query($query);
$sessionCount=0;
setcookie('sessionCount', ++$sessionCount);
if(mysqli_num_rows($result)>0){
while($row = $result->fetch_assoc()){
$sessionCount = $row['session'];
setcookie('sessionCount', ++$sessionCount);
}
}
if(isset($_GET['class']) && !empty($_GET['class'])){
$whichClass = $_GET['class'];
$whichClassSQL = "AND class='" . $_GET['class'] . "'";
} else {
$whichClass = '';
$whichClassSQL = 'ORDER BY class';
}
echo '
<div class="row">
<div class="col-md-4">
<div class="input-group">
<input type="number" id="session" name="sessionVal" class="form-control" placeholder="Session Value i.e 1" required>
<span class="input-group-btn">
<input id="submitAttendance" type="button" class="btn btn-success" value="Submit Attendance" name="submitAttendance">
</span>
</div>
</div>
<div class="col-md-8">
<form method="get" action="' . $_SERVER['PHP_SELF'] . '" class="col-md-4">
<select name="class" id="class" class="form-control" onchange="if (this.value) window.location.href=this.value">
';
// Generate list of classes.
$query = "SELECT DISTINCT class FROM user ORDER BY class;";
$classes = $classes = mysqli_query($conn, $query);
if($classes && mysqli_num_rows($classes)){
// Get list of available classes.
echo ' <option value="">Filter: Select a class</option>';
echo ' <option value="?class=">All classes</option>';
while($class = $classes->fetch_assoc()){
echo ' <option value="?class=' . $class['class'] . '">' . $class['class'] . '</option>';
}
} else {
echo ' <option value="?class=" disabled>No classes defined.</option>';
}
echo '
</select>
</form>
</div>
</div>
';
$query = "SELECT * FROM user WHERE role='student' $whichClassSQL;";
$result = $conn->query($query);
?>
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Class</th>
<th>Present</th>
<th>Absent</th>
</tr>
</thead>
<tbody>
<form method="post" action="save-attendance.php" id="attendanceForm">
<?php
if(mysqli_num_rows($result) > 0){
$i=0;
while($row = $result->fetch_assoc()){
?>
<tr>
<td><input type="hidden" value="<?php echo($row['id']);?>" form="attendanceForm"><input type="text" readonly="readonly" name="name[<?php echo $i; ?>]" value="<?php echo $row['fullname'];?>" form="attendanceForm"></td>
<td><input type="text" readonly="readonly" name="email[<?php echo $i; ?>]" value="<?php echo $row['email'];?>" form="attendanceForm"></td>
<td><input type="text" readonly="readonly" name="class[<?php echo $i; ?>]" value="<?php echo $row['class'];?>" form="attendanceForm"></td>
<td><input type="radio" value="present" name="present[<?php echo $i; ?>]" checked form="attendanceForm"></td>
<td><input type="radio" value="absent" name="present[<?php echo $i; ?>]" form="attendanceForm"></td>
</tr>
<?php $i++;
}
}
?>
</form>
</tbody>
</table>
<script>
$("#submitAttendance").click(function(){
if($("#session").val().length==0){
alert("session is required");
} else {
$.cookie("sessionVal", $("#session").val());
var data = $('form#attendanceForm').serialize();
$.ajax({
url: 'save-attendance.php',
method: 'post',
data: {formData: data},
success: function (data) {
console.log(data);
if (data != null && data.success) {
alert('Success');
} else {
alert(data.status);
}
},
error: function () {
alert('Error');
}
});
}
});
</script>
<?php
$conn->close();
include('footer.php');
save-attendance.
<?php
//include ("nav.php");
require("db-connect.php");
$query = "SELECT * FROM user WHERE role='student'";
$result = $conn->query($query);
$nameArray = Array();
$count = mysqli_num_rows($result);
if(isset($_COOKIE['sessionCount'])){
$sessionCount = $_COOKIE['sessionCount'];
}
//save record to db
if(isset($_POST['formData'])) {
//increment the session count
if(isset($_COOKIE['sessionCount'])){
$sessionCount = $_COOKIE['sessionCount'];
setcookie('sessionCount', ++$sessionCount);
}
parse_str($_POST['formData'], $searcharray);
//print_r($searcharray);die;
//print_r($_POST);
for ($i = 0 ; $i < sizeof($searcharray) ; $i++){
// setcookie("checkloop", $i);;
$name = $searcharray['name'][$i];
$email= $searcharray['email'][$i];
$class = $searcharray['class'][$i];
$present= $searcharray['present'][$i];
if(isset($_COOKIE['sessionVal'])){
$sessionVal = $_COOKIE['sessionVal'];
}
//get class id
$class_query = "SELECT * FROM class WHERE name='".$class."'";
$class_id = mysqli_query($conn, $class_query);
if($class_id){
echo "I am here";
while($class_id1 = $class_id->fetch_assoc()){
$class_id_fin = $class_id1['id'];
echo $class_id['id'];
}
}
else{
echo "Error: " . $class_query . "<br>" . mysqli_error($conn);
}
//get student id
$student_query = "SELECT * FROM user WHERE email='".$email."'";
$student_id = $conn->query($student_query);
if($student_id) {
while ($student_id1 = $student_id->fetch_assoc()) {
$student_id_fin = $student_id1['id'];
}
}
//insert or update the record
$query = "INSERT INTO attendance VALUES ( '".$class_id_fin."', '".$student_id_fin."' , '".$present."','".$sessionVal."','comment')
ON DUPLICATE KEY UPDATE isPresent='".$present."'";
print_r($query);
if(mysqli_query($conn, $query)){
echo json_encode(array('status' => 'success', 'message' => 'Attendance added!'));
} else{
echo json_encode(array('status' => 'error', 'message' => 'Error: ' . $query . '<br>' . mysqli_error($conn)));
}
}
$conn->close();
}
You did not provide a lot of information, but I understand from the comments that the error is $sessionVal is undefined.
if $_COOKIE['sessionVal'] is not set, try:
1- print_r($_COOKIE) and check if [sessionVal] is set;
2- Try to add a fallback to:
if(isset($_COOKIE['sessionVal'])){
$sessionVal = $_COOKIE['sessionVal'];
}
else {
$sessionVal = 0;
}
or
$sessionVal = (isset($_COOKIE['sessionVal'])) ? $_COOKIE['sessionVal'] : 0;
Bottom line, there is not point to check if a variable is set and not having a fallback in case it is not set.

PHP error submitting to SQL database

Looking for help please. I'm new to php and my course needs me to save form data to an sql database. I have the below code which creates my error message "Something went wrong". I'm studying online and my lecturer is less than useless at helping. Can anyone tell me where I am going wrong please?
My database reads and writes ok elsewhere..
<?php
$page_title = "Login Page";
session_start();
include('header.php');
require_once("validation_functions.php");
require_once('functions.php');
require_once('connection.php');
// Check if form was submitted
if (isset($_POST['submit'])) {
// Remove whitespace from beginning and end of values
$title = trim($_POST["Title"]);
$director = trim($_POST["Director"]);
$producer = trim($_POST["Producer"]);
$running_time = trim($_POST["Running"]);
$starring = trim($_POST["Starring"]);
$distributor = trim($_POST["Distributor"]);
// Escape strings and filter input to prevent SQL injection
$title = mysqli_real_escape_string($connection, $title);
$director = mysqli_real_escape_string($connection, $director);
$producer = mysqli_real_escape_string($connection, $producer);
$starring = mysqli_real_escape_string($connection, $starring);
$distributor = mysqli_real_escape_string($connection, $distributor);
$running_time = intval($running_time);
if (isset($_POST["Rel"])) { $release = $_POST["Rel"]; }
if (isset($_POST["Genre"])) { $genre = $_POST["Genre"]; }
if (isset($_POST["Rating"])) { $rating = $_POST["Rating"]; }
$form_errors = false;
// Check if fields are blank
if (is_blank($title) || is_blank($director) || is_blank($producer) || is_blank($release) || is_blank($running_time) || is_blank($starring) || is_blank($distributor)) {
$blank_message = "<p class='error-msg'>All fields are required.</p>";
$form_errors = true;
}
// Check if running time is a valid number
if (isset($running_time) && !filter_var($running_time, FILTER_VALIDATE_INT)) {
$number_message = "<p class='error-msg'>Running time is not a valid number.</p>";
$form_errors = true;
}
// Check if movie already exists
if (record_exists("SELECT * FROM Movie WHERE Movie.Title = '{$title}'")) {
$exists_message = "<p class='error-msg'>This movie already exists in the database.</p>";
$form_errors = true;
}
if ($form_errors == false) {
$insert_movie = "INSERT INTO Movie (Title, Director, Producer, Rel, Running, GenreID, Starring, Distributor, Rating) VALUES ('{$title}', '{$director}', '{$producer}', '{$release}', '{$running_time}'', '{$genre}', '{$starring}', '{$distributor}', '{$rating}')";
if (mysqli_query($connection, $insert_movie)) {
$movie_id = mysqli_insert_id($connection);
$success_message = "<p class='success-msg'>The movie has been successfully added to the database.</p>";
}
else {
$error_message = "<p class='error-msg'>Something went wrong. Please try again.</p>";
}
}
}
//php code ends here
?>
<!-- // PUT ERRORS HERE-->
<?php if (isset($blank_message)) { echo $blank_message; } ?>
<?php if (isset($number_message)) { echo $number_message; } ?>
<?php if (isset($date_message)) { echo $date_message; } ?>
<?php if (isset($exists_message)) { echo $exists_message; } ?>
<?php if (isset($success_message)) { echo $success_message; } ?>
<?php if (isset($error_message)) { echo $error_message; } ?>
<form action="<?php htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" enctype="multipart/form-data" id="movieinput">
Title:<br>
<input type="text" name="Title" placeholder="e.g. Aliens" data-validation="required" value="<?php if (isset($title)) { echo $title; } ?>"><br>
Director:<br>
<input type="text" name="Director" placeholder="e.g. Ridley Scott" data-validation="required" value="<?php if (isset($director)) { echo $director; } ?>"><br>
Producer:<br>
<input type="text" name="Producer" placeholder="e.g. Gale Ann Hurd" data-validation="required" value="<?php if (isset($producer)) { echo $producer; } ?>"><br>
Release Date:<br>
<input type="date" name="Rel" format="yyyy/mm/dd" value="<?php if (isset($date)) { echo $date; } ?>"><br>
Running Time (mins):<br>
<input type="number" pattern=".{1,3}" name="Running" placeholder="e.g. 137" data-validation="required" value="<?php if (isset($running)) { echo $running; } ?>"><br>
Genre:<br><select name="Genre" value="<?php if (isset($genre)) { echo $genre; } ?>"><br>>
<option value="drama" name="drama">Drama</option>
<option value="documentary" name ="documentary">Documentary</option>
<option value="scifi" name="scifi" selected>Sci-Fi</option>
<option value="comedy" name="comedy">Comedy</option>
<option value="biopic" name ="biopic">Biopic</option>
<option value="horror" name="horror">Horror</option>
</select><br>
Starring:<br>
<input type="text" name="Starring" placeholder="e.g. Sigourney Weaver, Michael Biehn, William Hope" value="<?php if (isset($starring)) { echo $starring; } ?>"><br>
Distributor:<br>
<input type="text" name="Distributor" placeholder="e.g. 20th Century Fox" data-validation="required" value="<?php if (isset($distributor)) { echo $distributor; } ?>"><br>
Rating:<br><select name="Rating" value="<?php if (isset($rating)) { echo $rating; } ?>"><br>>>
<option
value="one">1
</option>
<option
value="two">2
</option>
<option
value="three">3
</option>
<option
value="four">4
</option>
<option
value="five">5
</option>
</select><br>
<br>
<input type="submit" name="submit" value="Submit"/>
</form>
<script> </script>
You are using SQL database from php and using mysqli_query() function to insert which would definitely not work. You have to use PDO. to access SQL database.
Connect to SQL Server through PDO using SQL Server Driver
https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&cad=rja&uact=8&ved=0ahUKEwjk4MS-w-HRAhUPR48KHbLaAIMQFggdMAE&url=http%3A%2F%2Fphp.net%2Fmanual%2Fen%2Fref.pdo-dblib.php&usg=AFQjCNGG9EMmNv41NHQfjhpapjqhugBYQA
> $insert_movie = "INSERT INTO Movie (Title, Director, Producer, Rel,
> Running, GenreID, Starring, Distributor, Rating) VALUES ('{$title}',
> '{$director}', '{$producer}', '{$release}', '{$running_time}'',
> '{$genre}', '{$starring}', '{$distributor}', '{$rating}')";
use this instead of
> $insert_movie = "INSERT INTO Movie (Title, Director, Producer, Rel,
> Running, GenreID, Starring, Distributor, Rating) VALUES ('$title',
> '$director', '$producer', '$release', '$running_time', '$genre',
> '$starring', '$distributor', '$rating')";
In this case, some of the below possibility will cause this issue.
Input type is mismatch with column data type in database table.
Required parameter to be used to insert into the table.
One suggestion to ensure that there is no issue in INSERT query. Just print the insert statement in browser and execute that manually in DB.
$insert_movie = "INSERT INTO Movie (Title, Director, Producer, Rel, Running, GenreID, Starring, Distributor, Rating) VALUES ('{$title}', '{$director}', '{$producer}', '{$release}', '{$running_time}'', '{$genre}', '{$starring}', '{$distributor}', '{$rating}')";
echo $insert_movie; exit;
Try this and will continue the debugging if there is no issue in insert statement.
Cheers!

update query not working php

I'm working on a project and I'm suppose to update the another user's details using the $_GET method. My problem is that when user clicks on the id, it does go to edit page but when i change something and press the update button, it does not update. I'm not sure what am i doing wrong here.. I would really appreciate f someone can help me.
//Edit
My code is working now guys, I just changed the $_POST to $_REQUEST now and my form is updated.. Thank you all for helping me.. Thank you.. Here is my edited code.. I've taken out the oassword field, but i have a doubt.. Is using request safe?
<?php
include '../../connection.php';
$sid = $_REQUEST['sid'];
$query = "SELECT * FROM STUDENT WHERE STU_ID='$sid'";
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)){
$unm = $row["STU_UNAME"];
$fnm = $row["STU_FNAME"];
$lnm = $row["STU_LNAME"];
$dob = $row["STU_DOB"];
$add = $row["STU_ADD"];
$tlp = $row["STU_PHONE"];
$sem = $row["STU_SEM"];
$img = $row["STU_IMG"];
$sts = $row["STU_STATUS"];
$cid = $row["CRS_ID"];
}
}
else{
$no = "0 result!";
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
//insert details in data
$sid = $_POST["sid"]; $snm = $_POST["snm"]; $fst = $_POST["fnm"]; $lst = $_POST["lnm"]; $sdb = $_POST["dob"];
$sad = $_POST["add"]; $shp = $_POST["tlp"]; $stt = $_POST["sts"]; $sem = $_POST["sem"]; $cid = $_POST["cid"];
$sql = "UPDATE STUDENT SET
STU_ID='$sid', STU_UNAME='$snm', STU_FNAME= '$fst', STU_LNAME='$lst', STU_DOB='$sdb', STU_ADD='$sad', STU_PHONE='$shp',
STU_STATUS='$stt', STU_SEM='$sem', CRS_ID = '$cid' WHERE STU_ID='$sid'";
//check if data is updated
if (mysqli_query($connection, $sql)) {
header("Location: searchStudent.php");
}
else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
}
?>
Here's my form code:
<form class="contact_form" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<ul>
<li>
<h2>Edit Students Details</h2>
<span class="required_notification">* Denotes Required Field</span>
</li>
<li>
<label for="id">Student ID: </label>
<input type="text" name="sid" value="<?php echo $sid;?>"/>
</li>
<li>
<label for="name">Username: </label>
<input type="text" name="snm" value="<?php echo $unm;?>"/>
</li>
<li>
<label for="name">First Name: </label>
<input type="text" name="fnm" value="<?php echo $fnm;?>"/>
</li>
<li>
<label for="name">Last Name: </label>
<input type="text" name="lnm" value="<?php echo $lnm;?>"/>
</li>
<li>
<label for="dob">Date of Birth: </label>
<input type="date" name="dob" value="<?php echo $dob;?>"/>
</li>
<li>
<label for="add">Address: </label>
<textarea name="add" rows="4" cols="50"><?php echo $add;?></textarea>
</li>
<li>
<label for="tlp">Phone: </label>
<input type="text" name="tlp" value="<?php echo $tlp;?>"/>
</li>
<li>
<label for="sts">Status: </label>
<select name="sts">
<option selected><?php echo $sts;?></option>
<option value="FULLTIME">FULL TIME</option>
<option value="PARTTIME">PART TIME</option>
</select>
</li>
<li>
<label for="sem">Semester: </label>
<select name="sem">
<option selected><?php echo $sem;?></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>
</select>
</li>
<li>
<label for="crs">Course: </label>
<select name="cid">
<option selected><?php echo $cid;?></option>
<option value="AL">AL</option>
<option value="DBM">DBM</option>
<option value="DIT">DIT</option>
<option value="DTM">DTM</option>
<option value="FIS">FIS</option>
</select>
</li>
<li>
<button class="submit" type="submit" name="update">Update</button>
</li>
Make sure your form method is POST
Try this code:
<?php
include '../../connection.php';
//
$id = $_POST['id'];
$query = "SELECT * FROM STUDENT WHERE STU_ID='$id'";
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)){
$unm = $row["STU_UNAME"];
$fnm = $row["STU_FNAME"];
$lnm = $row["STU_LNAME"];
$pwd = $row["STU_PWD"];
$dob = $row["STU_DOB"];
$add = $row["STU_ADD"];
$tlp = $row["STU_PHONE"];
$sem = $row["STU_SEM"];
$img = $row["STU_IMG"];
$sts = $row["STU_STATUS"];
$cid = $row["CRS_ID"];
}
}
else{
$no = "0 result!";
}
$pwdErr = $cpwdErr= "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if($_POST["pwd"] == $_POST["cpwd"]){
if(strlen($_POST["pwd"])>8){
//insert details in data
$sid = $_POST["sid"]; $pwd = $_POST["pwd"]; $snm = $_POST["snm"]; $fst = $_POST["fnm"]; $lst = $_POST["lnm"];
$sdb = $_POST["dob"]; $sad = $_POST["add"]; $shp = $_POST["tlp"]; $stt = $_POST["sts"]; $sem = $_POST["sem"];
$cid = $_POST["cid"];
$sql = "UPDATE STUDENT SET
STU_ID='$sid', STU_PWD='$pwd', STU_UNAME='$snm', STU_FNAME= '$fst', STU_LNAME='$lst', STU_DOB='$sdb', STU_ADD='$sad', STU_PHONE='$shp',
STU_STATUS='$stt', STU_SEM='$sem', CRS_ID = '$cid' WHERE STU_ID='$id'";
//check if data is updated
if (mysqli_query($connection, $sql)) {
header("Location: searchStudent.php");
}
else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
}
else{
$pwdErr = "Invalid/Password must be more than 8 characters!";
}
}
else{
$cpwdErr = "Password not same!";
}
}
?>
Get ride for how to use prepare statement with example here.
Hope this help you well!
Your error is your are using POST in your form but getting its value with get change $_get with $_POST
$id = $_POST['id'];
well problem is that id you are posting is "sid" but you are using just "id" like $_POST['id'] instead of $_POST['sid']. so use this -
$id = $_POST['sid'];
instead of -
$id = $_POST['id']

change dropdown from array to check box

I would like a change from the drop down to the checkbox, I want to change it because I want firstly select the list in the array can be selected before store to database via the checkbox, so the dropdown script was as follows
<?php
session_start();
define('DEFAULT_SOURCE','Site_A');
define('DEFAULT_VALUE',100);
define('DEFAULT_STC','BGS');
include('class/stockconvert_class.php');
$st = new st_exchange_conv(DEFAULT_SOURCE);
if(isset($_GET['reset'])) {
unset($_SESSION['selected']);
header("Location: ".basename($_SERVER['PHP_SELF']));
exit();
}
?>
<form action="do.php" method="post">
<label for="amount">Amount:</label>
<input type="input" name="amount" id="amount" value="1">
<select name="from">
<?php
$stocks = $st->stocks();
asort($stocks);
foreach($stocks as $key=>$stock)
{
if((isset($_SESSION['selected']) && strcmp($_SESSION['selected'],$key) == 0) || (!isset($_SESSION['selected']) && strcmp(DEFAULT_STC,$key) == 0))
{
?>
<option value="<?php echo $key; ?>" selected="selected"><?php echo $stock; ?></option>
<?php
}
else
{
?>
<option value="<?php echo $key; ?>"><?php echo $stock; ?></option>
<?php
}
}
?>
</select>
<input type="submit" name="submit" value="Convert">
</form>
and i Changed it to the checkbox as follows
<?php
session_start();
define('DEFAULT_SOURCE','Site_A');
define('DEFAULT_VALUE',100);
define('DEFAULT_STC','BGS');
include('class/stockconvert_class.php');
$st = new st_exchange_conv(DEFAULT_SOURCE);
if(isset($_GET['reset'])) {
unset($_SESSION['selected']);
header("Location: ".basename($_SERVER['PHP_SELF']));
exit();
}
?>
<form action="do.php" method="post">
<label for="amount">Amount:</label>
<input type="input" name="amount" id="amount" value="1"><input type="submit" name="submit" value="Convert">
<?php
$stocks = $st->stocks();
asort($stocks);
foreach($stocks as $key=>$stock)
{
if((isset($_SESSION['selected']) && strcmp($_SESSION['selected'],$key) == 0) || (!isset($_SESSION['selected']) && strcmp(DEFAULT_STC,$key) == 0))
{
?>
<br><input type="checkbox" id="scb1" name="from[]" value="<?php echo $key; ?>" checked="checked"><?php echo $stock; ?>
<?php
}
else
{
?>
<br><input type="checkbox" id="scb1" name="from[]" value="<?php echo $key; ?>"><?php echo $stock; ?>
<?php
}
}
?>
</form>
but does not work, am I need to display Other codes related?
Thanks if some one help, and appreciated it
UPDATED:
ok post the first apparently less obvious, so I will add the problem of error
the error is
Fatal error: Call to undefined method st_exchange_conv::convert() in C:\xampp\htdocs\test\do.php on line 21
line 21 is $st->convert($from,$key,$date);
session_start();
if(isset($_POST['submit']))
{
include('class/stockconvert_class.php');
$st = new st_exchange_conv(DEFAULT_SOURCE);
$from = mysql_real_escape_string(stripslashes($_POST['from']));
$value = floatval($_POST['amount']);
$date = date('Y-m-d H:i:s');
$_SESSION['selected'] = $from;
$stocks = $st->stocks();
asort($stocks);
foreach($stocks as $key=>$stock)
{
$st->convert($from,$key,$date);
$stc_price = $st->price($value);
$stock = mysql_real_escape_string(stripslashes($stock));
$count = "SELECT * FROM oc_stock WHERE stock = '$key'";
$result = mysql_query($count) or die(mysql_error());
$sql = '';
if(mysql_num_rows($result) == 1)
{
$sql = "UPDATE oc_stock SET stock_title = '$stock', stc_val = '$stc_price', date_updated = '$date' WHERE stock = '$key'";
}
else
{
$sql = "INSERT INTO oc_stock(stock_id,stock_title,stock,decimal_place,stc_val,date_updated) VALUES ('','$stock','$key','2',$stc_price,'$date')";
}
$result = mysql_query($sql) or die(mysql_error().'<br />'.$sql);
}
header("Location: index.php");
exit();
}
Why I want to change it from dropdown to checkbox?
because with via checkbox list I will be able to choose which ones I checked it was the entrance to the database, then it seem not simple to me, I looking for some help< thanks So much For You mate.
You have not removed the opening <select> tag.
But you removed the <submit> button.
You changed the name from "from" to "from[]".
EDIT: After your additions:
Using the dropdown list you were only able to select one value for from. Now you changed it to checkboxes and thus are able to select multiple entries. This results in receiving an array from[] in your script in do.php. Your functions there are not able to handle arrays or multiple selections in any way.
You have to re-design do.php, change your form back to a dropdown list or use ratio buttons instead.

Categories