Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
The code below should get the input by the user and insert it into the customer table. However, i get the error :Problem with queryIncorrect integer value: 'customerid' for column 'customerID' at row 1. Can anyone help with this? Thanks
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Prac 2 Task 12</title>
</head>
<body>
<?php
$conn = mysql_connect("localhost", "user", "password");
mysql_select_db("factory291", $conn)
or die ('Database not found ' . mysql_error() );
$sql = "SELECT * FROM customer";
$rs = mysql_query($sql, $conn)
or die ('Problem with query' . mysql_error());
$ename = $elname = $ecus = $epcode = "";
$fnamecus = $lnamecus = $idcus = $pcde = "";
$error_report = false;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["customerid"])) {
$ecus = "Customer ID is required";
$error_report = true;
} else {
$idcus = input_t($_POST["customerid"]);
// check if numeric
if (preg_match("/[^0-9]/",$idcus)) {
$ecus = "Only numbers allowed";
$error_report = true;
}
if(strlen($idcus) != 6 && ($idcus) != null)
{
$ecus = "Customer ID must be 6 digits";
$error_report = true;
}
}
if (empty($_POST["customerfname"])) {
$ename = "First name is required";
$error_report = true;
} else {
$fnamecus= input_t($_POST["customerfname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-]*$/",$fnamecus)) {
$ename = "Only alphabetic letters and hyphen";
$error_report = true;
}
if(strlen($fnamecus) > 20 && ($fnamecus) != null)
{
$ename = "First name can't be more that 20 characters long";
$error_report = true;
}
}
if (empty($_POST["customerlname"])) {
$elname = "Last name is required";
$error_report = true;
} else {
$lnamecus = input_t($_POST["customerlname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-]*$/",$lnamecus)) {
$elname = "Only alphabetic letters and hyphen";
$error_report = true;
}
if(strlen($lnamecus) > 20 && ($lnamecus) != null)
{
$elname = "Last name can't be more that 20 characters long";
$error_report = true;
}
}
if (!is_null($_POST["postcode"])) {
$pcde = input_t($_POST["postcode"]);
// check if name only contains letters and whitespace
if (preg_match("/[^0-9]/",$pcde)) {
$epcode = "Only numbers allowed";
$error_report = true;
}
if(strlen($pcde) != 4 && ($pcde) != null)
{
$epcode = "Post code must be 4 digits";
$error_report = true;
}
}
}
if($error_report != true) {
$query="INSERT INTO customer (customerID, firstName, lastName, Address, suburb, state, postcode)
VALUES ('".$_POST['customerid']."', '".$_POST['customerfname']."', '".$_POST['customerlname']."',
'".$_POST['customeraddress']."', '".$_POST['suburb']."',
'".$_POST['state']."', '".$_POST['postcode']."')";
echo "correct";
}
function input_t($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h1>Customer Information Collection <br /></h1>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" id="custinfo" >
<table>
<tr>
<td><label for="customerid">Customer ID (integer value): </label></td>
<td><input type="text" id="customerid" name="customerid" size=11 value="<?php
echo $idcus;?>"/><span class="error">* <?php echo $ecus;?></span></td>
</tr>
<tr>
<td><label for="customerfname">Customer Frist Name: </label></td>
<td><input type="text" id="customerfname" name="customerfname" size=50 value="<?php
echo $fnamecus;?>"/><span class="error">* <?php echo $ename;?></span></td>
</tr>
<tr>
<td><label for="customerlname">Customer Last Name: </label></td>
<td><input type="text" id="customerlname" name="customerlname" size=50 value="<?php
echo $lnamecus;?>"/><span class="error">* <?php echo $elname;?></span></td>
</tr>
<tr>
<td><label for="customeraddress">Customer Address: </label></td>
<td><input type="text" id="customeraddress" name="customeraddress" size=65/></td>
<td><label for="suburb"> Suburb: </label></td>
<td><input type="text" id="suburb" name="suburb"/></td>
</tr>
<tr>
<td>
State:<select name="state" id="state">
<option value="select">--</option>
<option value="ACT">ACT</option>
<option value="NSW">NSW</option>
<option value="NT">NT</option>
<option value="QLD">QLD</option>
<option value="SA">SA</option>
<option value="TAS">TAS</option>
<option value="VIC">VIC</option>
<option value="WA">WA</option>
</select>
</td>
<td><label for="postcode"> Post Code: </label><input type="text" id="postcode"
name="postcode" size=4 value="<?php
echo $pcde;?>"/><span class="error"><?php echo $epcode;?></span></td>
</tr>
</table>
<p><input type="submit" value="Save Data"/> <input type="reset" value="Clear Form" />
</tr>
</form>
</body>
</html>
Your problem is incorrect use of quotes:
$query="INSERT INTO customer (customerID, firstName, lastName, Address, suburb, state, postcode)
VALUES ('customerid', 'customerfname', ‘customerlname', 'customeraddress', 'suburb',
'state', 'postcode')";
You are submitting the literal string values, 'customerid', etc.
From your code, it looks like you want to use the $_POST values, like this:
$query="INSERT INTO customer (customerID, firstName, lastName, Address, suburb, state, postcode)
VALUES ('".$_POST['customerid']."', '".$_POST['customerfname']."', '".$_POST['customerlname']."', '".$_POST['customeraddress']."', '".$_POST['suburb']."',
'".$_POST['state']."', '".$_POST['postcode']."')";
Also:
Please do not use the mysql_* functions. They are deprecated. Use MySQLi or PDO.
You are wide open to SQL injection. You need to escape your data or, even better, use prepared statements.
Related
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!
This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 6 years ago.
Tried searching the other threads but found nothing that helps:
The code below is part of a form, this passes the data from the form to the DB, the connection has been tested and works.
When the submit button is pressed, nothing happens, no echo for success or failure, and no new record in the database. I can't seem to find what the issue is:
<?php
if(isset($_POST['submit'])){
require '/connectDB.php';
try {
$stmt = $db->prepare("INSERT INTO tbl_matchOfficials
(MO_FN, MO_LN, MO_Gender, MO_DOB, MO_DOD,
Nationality, twitterHandle, Active, TMO)
VALUES ('$_POST[MO_FN]', '$_POST[MO_LN]',
'$_POST[MO_Gender]', '$_POST[MO_DOB]',
'$_POST[MO_DOD]', '$_POST[Nationality]',
'$_POST[twitterHandle]', '$_POST[Active]',
'$_POST[TMO]')");
$stmt->bindParam('MO_FN', $MO_FN);
$stmt->bindParam('MO_LN', $MO_LN);
$stmt->bindParam('MO_Gender', $MO_Gender);
$stmt->bindParam('MO_DOB', $MO_DOB);
$stmt->bindParam('MO_DOD', $MO_DOD);
$stmt->bindParam('Nationality', $Nationality);
$stmt->bindParam('twitterHandle', $twitterHandle);
$stmt->bindParam('Active', $TMO);
$stmt->bindParam('TMO', $TMO);
$stmt->execute();
echo "New record created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$db = null;
}
?>
Appreciate your help.
EDIT:
It's clear from the awesome assistance below that there is something else wrong, here is the whole code for the form. The form displays and holds the data as it should, it just won't insert and echo back (good or bad).
<!DOCTYPE HTML>
<html>
<head>
<title>New Match Official</title>
<style>
.error {color: #FF0000;}
</style>
<!-- Load jQuery from Google's CDN -->
<!-- Load jQuery UI CSS -->
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<!-- Load jQuery JS -->
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<!-- Load jQuery UI Main JS -->
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<!-- Load SCRIPT.JS which will create datepicker for input field -->
<script src="script.js"></script>
<script src="script1.js"></script>
<link rel="stylesheet" href="runnable.css" />
</head>
<h1>
New Match Official
</h1>
<body>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['submit'])){
require '/connectDB.php';
try {
$stmt = $db->prepare("INSERT INTO tbl_matchOfficials
(MO_FN, MO_LN, MO_Gender, MO_DOB, MO_DOD,
Nationality, twitterHandle, Active, TMO)
VALUES (:MOFN, :MOLN,
:MOGender, :MODOB,
:MODOD, :Nationality,
:twitterHandle, :Active,
:TMO)");
$stmt->bindParam(':MOFN', $_POST['MO_FN']);
$stmt->bindParam(':MOLN', $_POST['MO_LN']);
$stmt->bindParam(':MOGender', $_POST['MO_Gender']);
$stmt->bindParam(':MODOB', $_POST['MO_DOB']);
$stmt->bindParam(':MODOD', $_POST['MO_DOD']);
$stmt->bindParam(':Nationality', $_POST['Nationality']);
$stmt->bindParam(':twitterHandle', $_POST['twitterHandle']);
$stmt->bindParam(':Active', $_POST['Active']);
$stmt->bindParam(':TMO', $_POST['TMO']);
$stmt->execute();
echo "New record created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$db = null;
}
?>
<?php
// define variables and set to empty values
$MO_FN = $MO_LN = $MO_Gender = $MO_DOB = $MO_DOD = $Nationality = $twitterHandle = $Active = $TMO = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$MO_FN = test_input($_POST["MO_FN"]);
$MO_LN = test_input($_POST["MO_LN"]);
$MO_Gender = test_input($_POST["MO_Gender"]);
$MO_DOB = test_input($_POST["MO_DOB"]);
$MO_DOD = test_input($_POST["MO_DOD"]);
$Nationality = test_input($_POST["Nationality"]);
$twitterHandle = test_input($_POST["twitterHandle"]);
$Active = test_input($_POST["Active"]);
$TMO = test_input($_POST["TMO"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$FNErr = $LNErr = $GenderErr = $NationalityErr = $ActiveErr = $TMOErr = "";
$MO_FN = $MO_LN = $MO_Gender = $Nationality = $Active = $TMO = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["MO_FN"])) {
$FNErr = "First Name is required";
} else {
$MO_FN = test_input($_POST["MO_FN"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$MO_FN)) {
$FNErr = "Only letters and white space allowed";
}
}
if (empty($_POST["MO_LN"])) {
$LNErr = "Last Name is required";
} else {
$MO_LN = test_input($_POST["MO_LN"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$MO_LN)) {
$LNErr = "Only letters and white space allowed";
}
}
if (empty($_POST["MO_Gender"])) {
$GenderErr = "Gender is required";
} else {
$MO_Gender = test_input($_POST["MO_Gender"]);
}
if (empty($_POST["Nationality"])) {
$NationalityErr = "Nationality is Required (i.e. AUS for Australia)";
} else {
$Nationality = test_input($_POST["Nationality"]);
}
if (empty($_POST["Active"])) {
$ActiveErr = "Please state if Match Official is still active";
} else {
$Active = test_input($_POST["Active"]);
}
if (empty($_POST["TMO"])) {
$TMOErr = "Please state if Match Official performs the role of a TMO";
} else {
$TMO = test_input($_POST["TMO"]);
}
}
?>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td>First Name:</td>
<td><input type="text" name="MO_FN" value="<?php echo $MO_FN;?>"><span class="error">* <?php echo $FNErr;?></span></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" name="MO_LN" value="<?php echo $MO_LN;?>"><span class="error">* <?php echo $LNErr;?></span></td>
</tr>
<tr>
<td>Gender:</td>
<td><input type="radio" name="MO_Gender" <?php if (isset($MO_Gender) && $MO_Gender=="Male") echo "checked";?> value="Male">Male
<input type="radio" name="MO_Gender" <?php if (isset($MO_Gender) && $MO_Gender=="Female") echo "checked";?> value="Female">Female
<span class="error">* <?php echo $GenderErr;?></span></td>
</tr>
<tr>
<td>Date of Birth:</td>
<td><input type="text" id="datepicker" name="MO_DOB" value="<?php echo $MO_DOB;?>"></td>
</tr>
<tr>
<td>Date of Death:</td>
<td><input type="text" id="datepicker1" name="MO_DOD" value="<?php echo $MO_DOD;?>"></td>
</tr>
<tr>
<td>Nationality (TLA):</td>
<td><input type="text" maxlength="3" name="Nationality" value="<?php echo $Nationality;?>"><span class="error">* <?php echo $NationalityErr;?></span></td>
</tr>
<tr>
<td>Twitter Handle:</td>
<td><input type="text" name="twitterHandle" value="<?php echo $twitterHandle;?>"></td>
</tr>
<tr>
<td>Active Referee:</td>
<td><input type="radio" name="Active" <?php if (isset($Active) && $Active=="Yes") echo "checked";?> value="Yes">Yes
<input type="radio" name="Active" <?php if (isset($Active) && $Active=="No") echo "checked";?> value="No">No
<span class="error">* <?php echo $ActiveErr;?></span></td>
</tr>
<tr>
<td>TMO:</td>
<td><input type="radio" name="TMO" <?php if (isset($TMO) && $TMO=="Yes") echo "checked";?> value="Yes">Yes
<input type="radio" name="TMO" <?php if (isset($TMO) && $TMO=="No") echo "checked";?> value="No">No
<span class="error">* <?php echo $TMOErr;?></span></td>
</tr>
<tr>
<td><br><br><input type="submit"></td>
</tr>
</table>
</form>
<?php
echo "<h2>Your Input:</h2>";
echo "<table>";
echo "<tr><td>First Name: </td><td>$MO_FN</td></tr>";
echo "<tr><td>Last Name: </td><td>$MO_LN</td></tr>";
echo "<tr><td>Gender: </td><td>$MO_Gender</td></tr>";
echo "<tr><td>Date of Birth: </td><td>$MO_DOB</td></tr>";
echo "<tr><td>Date of Death: </td><td>$MO_DOD</td></tr>";
echo "<tr><td>Nationality: </td><td>$Nationality</td></tr>";
echo "<tr><td>Twitter Handle: </td><td>$twitterHandle</td></tr>";
echo "<tr><td>Active: </td><td>$Active</td></tr>";
echo "<tr><td>TMO: </td><td>$TMO</td></tr>";
echo "</table>"
?>
</body>
</html>
PDO uses Named Placeholders for the variables inside the query. More information about that can be found here: Prepared statements and stored procedures
That said, try this instead. Unless something else is going on, it should solve your problem:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['submit'])){
require '/connectDB.php';
try {
$stmt = $db->prepare("INSERT INTO tbl_matchOfficials
(MO_FN, MO_LN, MO_Gender, MO_DOB, MO_DOD,
Nationality, twitterHandle, Active, TMO)
VALUES (:MOFN, :MOLN,
:MOGender, :MODOB,
:MODOD, :Nationality,
:twitterHandle, :Active,
:TMO)");
$stmt->bindParam(':MOFN', $_POST['MO_FN']);
$stmt->bindParam(':MOLN', $_POST['MO_LN']);
$stmt->bindParam(':MOGender', $_POST['MO_Gender']);
$stmt->bindParam(':MODOB', $_POST['MO_DOB']);
$stmt->bindParam(':MODOD', $_POST['MO_DOD']);
$stmt->bindParam(':Nationality', $_POST['Nationality']);
$stmt->bindParam(':twitterHandle', $_POST['twitterHandle']);
$stmt->bindParam(':Active', $_POST['Active']);
$stmt->bindParam(':TMO', $_POST['TMO']);
$stmt->execute();
echo "New record created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$db = null;
}
?>
For those who follow this in future, answer was to add a name="submit" to the submit button code!
After that also came a connection error, but that was because my connectDB.php file is in the root (I am on MAMP) and so needed the initial / removed.
Thanks to everyone for the quick and awesome assistance.
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>";
}
This php file is using server side validation via post method as the user enters data into the input devices. The only problem I'm having is inserting the data into the customers table as it doesn't work. I know this because i have created test php file that displays all the customer tables content and the data the user enters is not there. Where have i gone wrong?
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Prac 2 Task 12</title>
</head>
<body>
<?php
$conn = mysql_connect("localhost", "twa291", "......");
mysql_select_db("factory291", $conn)
or die ('Database not found ' . mysql_error() );
$sql = "SELECT * FROM customer";
$rs = mysql_query($sql, $conn)
or die ('Problem with query' . mysql_error());
$ename = $elname = $ecus = $epcode = "";
$fnamecus = $lnamecus = $idcus = $pcde = "";
$error_report = false;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["customerid"])) {
$ecus = "Customer ID is required";
$error_report = true;
} else {
$idcus = input_t($_POST["customerid"]);
// check if numeric
if (preg_match("/[^0-9]/",$idcus)) {
$ecus = "Only numbers allowed";
$error_report = true;
}
if(strlen($idcus) != 6 && ($idcus) != null)
{
$ecus = "Customer ID must be 6 digits";
$error_report = true;
}
}
if (empty($_POST["customerfname"])) {
$ename = "First name is required";
$error_report = true;
} else {
$fnamecus= input_t($_POST["customerfname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-]*$/",$fnamecus)) {
$ename = "Only alphabetic letters and hyphen";
$error_report = true;
}
if(strlen($fnamecus) > 20 && ($fnamecus) != null)
{
$ename = "First name can't be more that 20 characters long";
$error_report = true;
}
}
if (empty($_POST["customerlname"])) {
$elname = "Last name is required";
$error_report = true;
} else {
$lnamecus = input_t($_POST["customerlname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-]*$/",$lnamecus)) {
$elname = "Only alphabetic letters and hyphen";
$error_report = true;
}
if(strlen($lnamecus) > 20 && ($lnamecus) != null)
{
$elname = "Last name can't be more that 20 characters long";
$error_report = true;
}
}
if (!is_null($_POST["postcode"])) {
$pcde = input_t($_POST["postcode"]);
// check if name only contains letters and whitespace
if (preg_match("/[^0-9]/",$pcde)) {
$epcode = "Only numbers allowed";
$error_report = true;
}
if(strlen($pcde) != 4 && ($pcde) != null)
{
$epcode = "Post code must be 4 digits";
$error_report = true;
}
}
}
if($error_report != true) {
$query="INSERT INTO customer (customerID, firstName, lastName, Address, suburb, state, postcode)
VALUES ('customerid', 'customerfname', ‘customerlname', 'customeraddress', 'suburb',
'state', 'postcode')";
$queryResult = mysql_query($query, $conn)
or die ('Problem with query' . mysql_error());
echo "correct";
}
function input_t($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h1>Customer Information Collection <br /></h1>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" id="custinfo" >
<table>
<tr>
<td><label for="customerid">Customer ID (integer value): </label></td>
<td><input type="text" id="customerid" name="customerid" size=11 value="<?php
echo $idcus;?>"/><span class="error">* <?php echo $ecus;?></span></td>
</tr>
<tr>
<td><label for="customerfname">Customer Frist Name: </label></td>
<td><input type="text" id="customerfname" name="customerfname" size=50 value="<?php
echo $fnamecus;?>"/><span class="error">* <?php echo $ename;?></span></td>
</tr>
<tr>
<td><label for="customerlname">Customer Last Name: </label></td>
<td><input type="text" id="customerlname" name="customerlname" size=50 value="<?php
echo $lnamecus;?>"/><span class="error">* <?php echo $elname;?></span></td>
</tr>
<tr>
<td><label for="customeraddress">Customer Address: </label></td>
<td><input type="text" id="customeraddress" name="customeraddress" size=65/></td>
<td><label for="suburb"> Suburb: </label></td>
<td><input type="text" id="suburb" name="suburb"/></td>
</tr>
<tr>
<td>
State:<select name="state" id="state">
<option value="select">--</option>
<option value="ACT">ACT</option>
<option value="NSW">NSW</option>
<option value="NT">NT</option>
<option value="QLD">QLD</option>
<option value="SA">SA</option>
<option value="TAS">TAS</option>
<option value="VIC">VIC</option>
<option value="WA">WA</option>
</select>
</td>
<td><label for="postcode"> Post Code: </label><input type="text" id="postcode"
name="postcode" size=4 value="<?php
echo $pcde;?>"/><span class="error"><?php echo $epcode;?></span></td>
</tr>
</table>
<p><input type="submit" value="Save Data"/> <input type="reset" value="Clear Form" />
</tr>
</form>
</body>
</html>
You need to call mysql_query on your $query -- right now you're just defining the $query object and then ignoring it for the rest of the page.
Add something like the following on the line before echo "correct";
$queryResult = mysql_query($query, $conn)
or die ('Problem with query' . mysql_error());
n.b. I'll echo #Ozmah's comment about looking into PDO or mysqli functions - learning the deprecated plain mysql functions will be of dubious value.
Well, I just bought a sms api which is created by php. They provide me this 2 lines:
http://fahimit.com/smsapi.php?
user=username&pass=pass&phone=mobile_numer&senderid=sender_name&message=my_message
\well now i'm using a html form to send sms. But after message send it's not showing full sender name and message.
For example if i use "Test Sender" as sender_name and "Test message test message" as my_message then it's only showing First word like: Test as sender_name and Test as my_message. I don't understand why it's not showing full message and sender name
PHP code:
<?php
if(isset($_POST['Submit']) && $_POST['Submit'] == "Send SMS")
{
$write_numer = $_POST['write_number'];
$sender = inputvalid($_POST['sender']);
$type = inputvalid($_POST['type']);
$select_msg = inputvalid($_POST['select_msg']);
$msg = $_POST['txt'];
$length = strlen($msg);
$err = array();
$ip = $_SERVER['REMOTE_ADDR'];
if(isset($write_numer) && isset($sender) && isset($type) && isset($select_msg) && isset($msg))
{
if(empty($write_numer) && empty($sender) && empty($type) && empty($select_msg) && empty($msg))
$err[] = "All field require";
else
{
if(empty($write_numer))
$err[] = "Write your mobile number";
elseif(strlen($write_numer) > 13 || strlen($write_numer) < 13)
$err[] = "Your mobile number format is not correct";
elseif(!is_numeric($write_numer))
$err[] = "Your mobile number format is not correct";
elseif (!preg_match("/^8801(6|5|7|8|9|1)\d{8}/", $write_numer))
$err[] = "Invalid mobile number";
if(empty($sender))
$err[] = "Select sender name";
if(empty($type))
$err[] = "Select your message type";
if(empty($select_msg) && empty($msg))
$err[] = "Select your message";
}
}
//error count
if(!empty($err))
{
echo "<div class='error'>";
foreach($err as $er)
{
echo "<font color=red>$er.</font><br/>";
}
echo "</div>";
echo "<br/>";
}
else
{
$sms = "http://fahimit.com/smsapi.php?user=MYUSERNAME&pass=MYPASS&phone=".$write_numer."&senderid=".$sender."&message=".$msg."";
$sms = file_get_contents($sms);
if($sms)
{
echo "<div class='success'>Successfully sent your message to $write_numer. Thank You.</div>";
$sql = mysql_query("INSERT INTO e_sent_sms VALUES('', '', '', '$write_numer', '$msg', '', '', '$length', '$type', '$sender', '$current_date', '$ip' )");
}
else
{
mysql_error();
}
}
}
?>
HTML CODE:
<form name="frm" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>">
<table width="800" border="0" cellspacing="10" cellpadding="0" style="float:left; position:relative;">
<tr>
<td>Write Number</td>
<td><input type="text" name="write_number" placeholder="Write your mobile number" class="td3" value="<?php if(isset($_POST['write_number'])) echo $_POST['write_number']; ?>" /><span style="color:#033;">* Mobile number must start with 8801XXXXXXXXX</span></td>
</tr>
<tr>
<td>Sender</td>
<td><input type="text" name="sender" placeholder="Sender name" class="td3" value="<?php if(isset($_POST['sender'])) echo $_POST['sender']; ?>" /></td>
</tr>
<tr>
<td>Message type</td>
<td>
<select name="type" class="select">
<option value="">--Select--</option>
<option value="5" <?php if(isset($_POST['type']) && $_POST['type'] == "5") echo 'selected = "selected"'; ?>>Text</option>
<option value="1" <?php if(isset($_POST['type']) && $_POST['type'] == "1") echo 'selected = "selected"'; ?>>Flash</option>
<option value="3" <?php if(isset($_POST['type']) && $_POST['type'] == "3") echo 'selected = "selected"'; ?>>Arabic</option>
<option value="2" <?php if(isset($_POST['type']) && $_POST['type'] == "2") echo 'selected = "selected"'; ?>>Unicode</option>
<option value="6" <?php if(isset($_POST['type']) && $_POST['type'] == "6") echo 'selected = "selected"'; ?>>Unicode Flash</option>
<option value="4" <?php if(isset($_POST['type']) && $_POST['type'] == "4") echo 'selected = "selected"'; ?>>Wap Push</option>
</select>
</td>
</tr>
<tr>
<td>Select message</td>
<td>
<select name="select_msg" class="select" id="carDealer">
<option value="">--Select Message--</option>
<?php
$sql = mysql_query("SELECT DISTINCT msg FROM e_sms_draft");
while($res = mysql_fetch_array($sql))
{
$draft = inputvalid($res['msg']);
$draft = stripslashes($draft);
if(isset($_POST['select_msg']) && $_POST['select_msg'] == "$draft")
$sel = 'selected = "selecteds"';
else
$sel = "";
echo "<option value='$draft' $sel>$draft</option>";
}
?>
</select>
</td>
</tr>
<td valign="top">Message</td>
<td><textarea class="textarea2" id="carPark" placeholder="Your message" name="txt" onkeyup="counter(this);"><?php if(isset($_POST['txt'])) echo $_POST['txt']; ?></textarea>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function putIt(e) {
$("#carPark").val(e.target.value);
}
$("#carDealer").on("change", putIt);
</script>
<br/><input type="" name="lbl" style="border:none;"><br/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Save SMS" class="view"/>
<input type="submit" name="Submit" value="Send SMS" class="submit"/></td>
</tr>
</table>
</form>
Can you tell me what's wrong in my code ?
You need to urlencode your text before passing it to the URL. Do like this
$sender = urlencode($sender);
$msg = urlencode($msg);
$sms = "http://fahimit.com/smsapi.php?user=MYUSERNAME&pass=MYPASS&phone=".$write_numer."&senderid=".$sender."&message=".$msg."";
Do this for all the variables that you are going to send it to the URL.