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!
Related
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"];
}
I have a edit form that has some checkboxes on it and I am having trouble getting the new checkbox values posted back to the db after it has been changed. So far the form will load in the current values in the db but after you click different check boxes it wont update the change in the db. Any help would be appreciated.
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($id, $firstname, $contactname, $phone, $type, $sex, $markers, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Record</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>First Name: *</strong> <input type="text" name="firstname" value="<?php echo $firstname; ?>"/><br/>
<strong>Contact Name: *</strong> <input type="text" name="contactname" value="<?php echo $contactname; ?>"/><br/>
<strong>Phone Number: *</strong> <input type="text" name="phone" value="<?php echo $phone; ?>"/><br/>
<strong>Type: *</strong>
<select name="type">
<option value="">Select...</option>
<option value="Inpatient Hospital" <?php if($type=="Inpatient Hospital")echo "selected=\"selected\""; ?>>Inpatient Hospital</option>
<option value="Residential Facility"<?php if($type=="Residential Facility")echo "selected=\"selected\""; ?>>Residential Facility</option>
<option value="Behavioral Treatment Facility"<?php if($type=="Behavioral Treatment Facility")echo "selected=\"selected\""; ?>>Behavioral Treatment Facility</option>
<option value="Therapeutic Group Home"<?php if($type=="Therapeutic Group Home")echo "selected=\"selected\""; ?>>Therapeutic Group Home</option>
<option value="Drug or Addictions Rehab"<?php if($type=="Drug or Addictions Rehab")echo "selected=\"selected\""; ?>>Drug or Addictions Rehab</option>
</select><br/>
<input type="radio" name="sex" value="Male" <?php echo ($sex=="Male")?'checked="checked"':'' ?>size="17">Male
<input type="radio" name="sex" value="Female" <?php echo ($sex=="Female")?'checked="checked"':'' ?> size="17">Female
<input type="radio" name="sex" value="Both" <?php echo ($sex=="Both")?'checked="checked"':'' ?> size="17">Both<br/>
<strong>Markers: *</strong> <input type="text" name="markers" value="<?php echo $markers; ?>"/><br/>
<?php
// Create connection
$con=mysqli_connect("localhost","un","pw","childcare");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT FMarkers FROM faci WHERE ID='$id'");
while($row = mysqli_fetch_array($result))
{
$focus=explode(",",$row['FMarkers']);
?>
Autism<input type="checkbox" name="FMarkers[]" value="Autism" <?php if(in_array("Autism",$focus)) { ?> checked="checked" <?php } ?> >
Attachement Disorder<input type="checkbox" name="FMarkers[]" value="Attachement Disorder" <?php if(in_array("Attachement Disorder",$focus)) { ?> checked="checked" <?php } ?> >
Dissociative Disorder<input type="checkbox" name="FMarkers[]" value="Dissociative Disorder" <?php if(in_array("Dissociative Disorder",$focus)) { ?> checked="checked" <?php } ?> >
ODD<input type="checkbox" name="FMarkers[]" value="ODD" <?php if(in_array("ODD",$focus)) { ?> checked="checked" <?php } ?> >
ADHD<input type="checkbox" name="FMarkers[]" value="ADHD" <?php if(in_array("ADHD",$focus)) { ?> checked="checked" <?php } ?> >
<?php
//print_r(array_values($focus));
//echo("<pre>\n");
//print_r($_POST);
//echo("</pre>\n");
//var_dump($dog);
//these below are different ways I have tried to get it to work
//$markers = implode(',', $_POST['dog']);
//$markers=$_POST['focus'];
//$markers = implode(",",$markers);
//$markers = implode(",",$_POST['focus']);
//$check = isset($_POST['focus']) ? $_POST['focus'] : '';
//$markers = is_array($check) ? implode(", ", $check) : '';
//echo $markers;
?>
<?php
}
?>
<p>* Required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$firstname = mysql_real_escape_string(htmlspecialchars($_POST['firstname']));
$contactname = mysql_real_escape_string(htmlspecialchars($_POST['contactname']));
$phone = mysql_real_escape_string(htmlspecialchars($_POST['phone']));
$type = mysql_real_escape_string(htmlspecialchars($_POST['type']));
$sex = mysql_real_escape_string(htmlspecialchars($_POST['sex']));
$markers = mysql_real_escape_string(htmlspecialchars($_POST['markers']));
// check that firstname/lastname fields are both filled in
if ($firstname == '' || $contactname == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $firstname, $contactname, $phone, $type, $sex, $markers, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE faci SET FName='$firstname', FContact='$contactname', FPhone='$phone', FType='$type', FSex='$sex', FMarkers='$markers' WHERE ID='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: facility-view.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM faci WHERE ID=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$firstname = $row['FName'];
$contactname = $row['FContact'];
$phone = $row['FPhone'];
$type = $row['FType'];
$sex = $row['FSex'];
$markers = $row['FMarkers'];
// show form
renderForm($id, $firstname, $contactname, $phone, $type, $sex, $markers, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
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>";
}
I had the following form working properly and populating MySQL DB. I had since added on a new field 'type' to my database and also added it to the form. However now when I try to add a new entry it says "Invalid column name 'type'". Any help would be greatly appreciated.
<script>
$(document).ready(function() {
$("#datepicker").datepicker();
});
</script>
<script>
$(document).ready(function() {
$("#datepicker2").datepicker();
});
</script>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<div>
<label for="Posted"><strong>Posted: </strong> </label>
<input id="datepicker" name="posted" value="<?php echo $Posted; ?>" /><br/><br/>
<label for="Ends"><strong>Ends: </strong> </label>
<input id="datepicker2" name="ends" value="<?php echo $Ends; ?>" /><br/><br/>
<label for="Position"><strong>Position: </strong></label>
<input type="text" name="position" value="<?php echo $Position; ?>" /><br/><br/>
<label for="Location"><strong>Location: </strong> </label>
<select name="location">
<option value=" ">Select...<?php echo $Location; ?></option>
<option value="Fargo">Fargo</option>
<option value="Grand Forks">Grand Forks</option>
</select><br/><br/>
<label for="Application Type"><strong>Application Type: </strong> </label>
<select name="type">
<option value=" ">Select...<?php echo $Type; ?></option>
<option value="Driver">Driver</option>
<option value="Employee">Employee</option>
</select><br/><br/>
<label for="Hours"><strong>Hours: </strong> </label>
<input type="text" name="hours" value="<?php echo $Hours; ?>" /><br/><br/>
<label for="Pay"><strong>Pay: </strong> </label>
<input type="text" name="pay" value="<?php echo $Pay; ?>" /><br/><br/>
<label for="Benefits"><strong>Benefits: </strong> </label>
<textarea cols="60" rows="2" name="benefits" value="<?php echo $Benefits; ?>" ><?php echo $Benefits; ?></textarea><br/><br/>
<label for="Description"><strong>Description: </strong> </label>
<textarea cols="60" rows="3" name="description" value="<?php echo $Description; ?>" ><?php echo $Description; ?></textarea><br/><br/>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
function ms_escape_string($data) {
if ( !isset($data) or empty($data) ) return '';
if ( is_numeric($data) ) return $data;
$non_displayables = array(
'/%0[0-8bcef]/', // url encoded 00-08, 11, 12, 14, 15
'/%1[0-9a-f]/', // url encoded 16-31
'/[\x00-\x08]/', // 00-08
'/\x0b/', // 11
'/\x0c/', // 12
'/[\x0e-\x1f]/' // 14-31
);
foreach ( $non_displayables as $regex )
$data = preg_replace( $regex, '', $data );
$data = str_replace("'", "''", $data );
return $data;
}
ms_escape_string($_POST);
$posted=$_POST['posted'];
$ends=$_POST['ends'];
$type=$_POST['type'];
$position=$_POST['position'];
$location=$_POST['location'];
$hours=$_POST['hours'];
$pay=$_POST['pay'];
$benefits=$_POST['benefits'];
$description=$_POST['description'];
// check to make sure all fields are entered
if ($posted == '' || $ends == '' || $type == '' || $position == '' || $location == '' || $hours == '' || $pay == '' || $benefits == '' || $description == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if any fields are blank, display the form again
renderForm($posted, $ends, $type, $position, $location, $hours, $pay, $benefits, $description, $error);
}
else
{
// save the data to the database
$SQL = "INSERT INTO JobPosting (posted, ends, type, position, location, hours, pay, benefits, description) VALUES ('$posted', '$ends', '$type', '$position', '$location', '$hours', '$pay', '$benefits', '$description')";
$result = mssql_query($SQL)
or die (mssql_get_last_message());
// once saved, redirect back to the view page
header("Location: view.php");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','','','','','','','','');
}
You will need to escape the column name type in the query ie type since type is a reserved work in MySQL sytax.
How the hell do you escape ` marks anyway?
type is a reserved word in MS SQL. This means that it is used in other MS SQL operations. Similarly, you would run into trouble if you had a column named select or group
You can escape reserved words by using brackets: []
$SQL = "INSERT INTO JobPosting (posted, ends, [type], position, location, hours, pay, benefits, description) VALUES ('$posted', '$ends', '$type', '$position', '$location', '$hours', '$pay', '$benefits', '$description')";
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.