The following flags an error if a form field is empty and also flags an error if anything other than letters are entered in the form input.
if (empty($_POST["feedtitle"])) {
$has_errors = true;
$feedtitleErr = "Enter feed title";
} elseif (preg_match('/[^a-zA-Z]/i',$_POST["feedtitle"])) {
$has_errors = false;
$feedtitleErr = "Enter text only";
} else {
$feedtitle = validate_input($_POST["feedtitle"]);
}
When created the form this works fine. When editing the form data however is the input is left empty the empty field error "Enter feed title" does not fire and if I enter anything other than letters e.g. numbers no value is passed i.e. the variable $feedtitle is blank. If I enter text however it saves.
I don't think the query is the issue.
$Query = "UPDATE ccregisterfeed SET author='$author', category='$category',
copyright='$copyright', feeddescription='$feeddescription', feedtitle='$feedtitle',
websitelink='$websitelink', imagelink='$imagelink', imagetitle='$imagetitle',
subtitle='$subtitle' WHERE id='$feedid' AND username ='$user'";
FULL SCRIPT
<?php
include "connect.php";
require "authenticate.php";
error_reporting(E_ERROR);
$message = $_GET['message'];
$user = $_SESSION['UserName'];
//declare form field and form field error variables
$authorErr = $categoryErr = $copyrightErr = $feeddescriptionErr = $feedlinkErr = $feedtitleErr = $websitelinkErr = $imagelinkErr = $imagetitleErr = $subtitleErr = "";
$author = $category = $copyright = $feeddescription = $feedlink = $feedtitle = $websitelink = $imagelink = $imagetitle = $subtitle = "";
//form field validation
function validate_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST['Submit']))
{
$has_errors = false;
if (empty($_POST["author"])) {
$has_errors = true;
$authorErr = "Enter your name";
}else{
$author = validate_input($_POST["author"]);
}
if (empty($_POST["category"])) {
$has_errors = true;
$categoryErr = "Enter a category";
}else {
$category = validate_input($_POST["category"]);
}
if (empty($_POST["copyright"])) {
$has_errors = true;
$copyrightErr = "Enter copyright details";
} else {
$copyright = validate_input($_POST["copyright"]);
}
if (empty($_POST["feeddescription"])) {
$has_errors = true;
$feeddescriptionErr = "Enter feed description";
} else {
$feeddescription = validate_input($_POST["feeddescription"]);
}
if (empty($_POST["feedtitle"])) {
$has_errors = true;
$feedtitleErr = "Enter feed title";
} elseif (preg_match('/[^a-zA-Z]/i',$_POST["feedtitle"])) {
$has_errors = true;
$feedtitleErr = "Enter text only";
} else {
$feedtitle = validate_input($_POST["feedtitle"]);
}
if (empty($_POST["websitelink"])) {
$has_errors = true;
$websitelinkErr = "Enter link to website";
} else {
$websitelink = validate_input($_POST["websitelink"]);
}
if (empty($_POST["imagelink"])) {
$has_errors = true;
$imagelinkErr = "Enter link to image";
} else {
$imagelink = validate_input($_POST["imagelink"]);
}
if (empty($_POST["imagetitle"])) {
$has_errors = true;
$imagetitleErr = "Enter image name";
} else {
$imagetitle = validate_input($_POST["imagetitle"]);
}
if (empty($_POST["subtitle"])) {
$has_errors = true;
$subtitleErr = "Enter feed subtitle";
} else {
$subtitle = validate_input($_POST["subtitle"]);
}
// var_dump ($date);
// var_dump ($feedlink);
// var_dump ($feeddescription);
//write edited data into tables matching logged in user with their data
$feedid = mysql_real_escape_string($_POST['feedid']);
$date = date("Y-m-d H:i:s");
$feeddescription = str_replace("_", "", $feeddescription);
$feeddescription = str_replace("-", "", $feeddescription);
$feeddescription = str_replace("!", "", $feeddescription);
$feeddescription = str_replace("#", "", $feeddescription);
$feeddescription = str_replace("'", "", $feeddescription);
$Query = "UPDATE ccregisterfeed SET author='$author', category='$category', copyright='$copyright', feeddescription='$feeddescription', feedtitle='$feedtitle', websitelink='$websitelink', imagelink='$imagelink', imagetitle='$imagetitle', subtitle='$subtitle' WHERE id='$feedid' AND username ='$user'";
if($sql = mysql_query($Query)) {
header("location: rss.php");
// header("location: feededit.php");
} else {
die("Query was: $Query. Error: ".mysql_error());
}
}
//show logged in user their updated data
$user = $_SESSION['UserName'];
$result = mysql_query("SELECT * FROM ccregisterfeed WHERE username = '$user'") or die(mysql_error());
while($row = mysql_fetch_array($result)){
$id=$row['id'];
$author = $row['author'];
$category = $row['category'];
$copyright = $row['copyright'];
$feeddescription = $row['feeddescription'];
$feedtitle = $row['feedtitle'];
$websitelink = $row['websitelink'];
$imagelink = $row['imagelink'];
$imagetitle = $row['imagetitle'];
$subtitle = $row['subtitle'];
}
//delete form and image data when users clicks delete button
if (isset($_POST['Delete'])){
$deleteuser = $_POST['Delete'];
mysql_query("DELETE FROM ccregisterfeed WHERE id = '$deleteuser'");
mysql_query("ALTER TABLE ccregisterfeed AUTO_INCREMENT = 1");
$message = 'Feed Deleted';
header("Location: feededit.php?&message=".urlencode($message));
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<form action="feededit.php" method="post" enctype="multipart/form-data" name="edit" id="editfeed">
<fieldset>
<div class="legendcreate">Feed Edit</div>
<div class="feedcontainer">
<div class="feedcontainerinner">
<div><label class="labelshow">Author</label><input id="author" class="insetfeed" name="author" type="text" placeholder="Author" value="<?PHP print $author ; ?>"/><p class="errorinput"><?php echo $authorErr;?></p></div>
<?php if(isset($_GET['message']) && !empty($message)): ?>
<div class="messagebox">
<?php echo $message ?>
</div>
<?php endif; ?>
<div><label class="labelshow">Category</label><input id="category" class="insetfeed" name="category" type="text" placeholder="Category" value="<?PHP print $category; ?>"/><p class="errorinput"><?php echo $categoryErr;?></p></div>
<div><label class="labelshow">Copyright</label><input id="copyright" class="insetfeed" name="copyright" type="text" placeholder="Copyright" value="<?PHP print $copyright; ?>"/><p class="errorinput"><?php echo $copyrightErr;?></p></div>
<div><label class="labelshow">Feed Title</label><input id="feedtitle" class="insetfeed" name="feedtitle" type="text" placeholder="Feed Title" value="<?PHP print $feedtitle; ?>"/><p class="errorinput"><?php echo $feedtitleErr;?></p></div>
<div><label class="labelshow">Website Link</label><input id="websitelink" class="insetfeed" name="websitelink" type="text" placeholder="Website Link" value="<?PHP print $websitelink; ?>"/><p class="errorinput"><?php echo $websitelinkErr;?></p></div>
<div><label class="labelshow">Image Link</label><input id="imagelink" class="insetfeed" name="imagelink" type="text" placeholder="Image Link" value="<?PHP print $imagelink; ?>"/><p class="errorinput"><?php echo $imagelinkErr;?></p></div>
<div><label class="labelshow">Image Title</label><input id="imagetitle" class="insetfeed" name="imagetitle" type="text" placeholder="Image Title" value="<?PHP print $imagetitle; ?>"/><p class="errorinput"><?php echo $imagetitleErr;?></p></div>
<div><label class="labelshow">Subtitle</label><input id="subtitle" class="insetfeed" name="subtitle" type="text" placeholder="Subtitle" value="<?PHP print $subtitle; ?>"/><p class="errorinput"><?php echo $subtitleErr;?></p></div>
<div><textarea id="description" name="feeddescription" class="textareadescription" placeholder="Enter feed description"><?php
$out = htmlspecialchars_decode($feeddescription);
$out = str_replace( '\n', '<br />', $out );
echo $out;
?></textarea>
<div class="submit"><input name="Submit" type="submit" class="submitbtn" value="Save"/></div>
<div class="delete"><input name="deletebtn" type="submit" class="resetbtn" value="Delete"/></div>
<input type="hidden" name="feedid" value="<?phpecho $id;?>"/>
</div>
</div>
</div>
</form>
</fieldset>
Related
I'm trying to add form data into my database table on Xampp ,but while My echo displays everything properly ,it doesn't input anything into the database table and I wonder if I'm missing something here.I made sure to spell everything the same ,so I doubt it's a spelling error atleast....Any help,suggestions and or corrections are greatly appreciated !
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$VarErr = $PavErr = $AdErr = $PkErr = $KiekErr = "";
$Vardas = $Pavarde = $Adresas = $Pk = $Kiekis = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Vardas"])) {
$VarErr = "Įveskite vardą";
} else {
$Vardas= test_input($_POST["Vardas"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$Vardas)) {
$VarErr = "Galima vesti tik su raidėmis";
}
}
if (empty($_POST["Pavarde"])) {
$PavErr = "Įveskite pavardę";
} else {
$Pavarde = test_input($_POST["Pavarde"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$Pavarde)) {
$PavErr = "Galima vesti tik su raidėmis";
}
}
if (empty($_POST["Adresas"])) {
$AdErr = "Įveskite adresą";
} else {
$Adresas= test_input($_POST["Adresas"]);
}
if (empty($_POST["Pk"])) {
$Pk = "Įveskite prekės kodą";
} else {
$Pk = test_input($_POST["Pk"]);
}
if (empty($_POST["Kiekis"])) {
$KiekErr = "Įveskite kiekį";
} else {
$Kiekis = test_input($_POST["Kiekis"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Vardas: <input type="text" name="Vardas" value="<?php echo $Vardas;?>">
<span class="error">* <?php echo $VarErr;?></span>
<br><br>
Pavarde: <input type="text" name="Pavarde" value="<?php echo $Pavarde;?>">
<span class="error">* <?php echo $PavErr;?></span>
<br><br>
Adresas: <input type="text" name="Adresas" value="<?php echo $Adresas;?>">
<span class="error"><?php echo $AdErr;?></span>
<br><br>
Pk: <input type="number" name="Pk" value="<?php echo $Pk;?>">
<span class="error"><?php echo $PkErr;?></span>
<br><br>
Kiekis:<input type="number" name="Kiekis" value="<?php echo $Kiekis;?>">
<span class="error"><?php echo $KiekErr;?></span>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $Vardas;
echo "<br>";
echo $Pavarde;
echo "<br>";
echo $Adresas;
echo "<br>";
echo $Pk;
echo "<br>";
echo $Kiekis;
$host = "localhost";
$user = "root";
$password ="";
$database = "uzsakymas";
try{
$connect = mysqli_connect($host,$user,$password,$database);
}
catch(mysqli_sql_exception $ex){
echo 'database connection error';
}
if(isset($_POST['insert'])) {
$Vardas = $_POST['Vardas'];
$Pavarde = $_POST['Pavarde'];
$Adresas = $_POST['Adresas'];
$Pk = $_POST['Pk'];
$Kiekis = $_POST['Kiekis'];
$insert_query = "INSERT INTO uzsakymai (Vardas,Pavarde,Adresas,Pk,Kiekis)VALUES('$Vardas','$Pavarde','$Adresas','$Pk','$Kiekis')";
try {
$insert_result = mysqli_query($connect,$insert_query);
if($insert_result){
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Inserted';
}else{
echo'Data not Inserted';
}
}
} catch(Exception $ex) {
echo 'Error Insert'.$ex->getMessmessage();
}
}
?>
</body>
</html>
hi your are checking value in insert isset($_POST['insert']) but insert name not assign in any control so assign insert name to your submit control check below :
<input type="submit" value="Submit" name="insert">
I'm kinda confused with your code but I think the wrong part is in here:
<input type="submit" name="submit" value="Submit">
You have this submit but look at this:
if(isset($_POST['insert']))
You are trying to check if POST is set to insert instead of submit.
In my code below i have two form section first one is to fetch information from database and second one is verify a record in the database my problem is how do verify a record and redirect to error page or if the input form do not march any record redirect to index page this my code;
<?php
include_once 'init.php';
$error = false;
//check if form is submitted
if (isset($_POST['book'])) {
$book = mysqli_real_escape_string($conn, $_POST['book']);
$action = mysqli_real_escape_string($conn, $_POST['action']);
if (strlen($book) < 6) {
$error = true;
$book_error = "booking code must be alist 6 in digit";
}
if (!is_numeric($book)) {
$error = true;
$book_error = "Incorrect booking code";
}
if (empty($_POST["action"])) {
$error = true;
$action_error = "pick your action and try again";
}
if (!$error) {
if(preg_match('/(check)/i', $action)) {
echo "6mameja";
}
if (preg_match('/(comfirm)/i', $action)) {
if(isset($_SESSION["user_name"]) && (trim($_SESSION["user_name"]) != "")) {
$username=$_SESSION["user_name"];
$result=mysqli_query($conn,"select * from users where username='$username'");
}
if ($row = mysqli_fetch_array($result)) {
$id = $row["id"];
$username=$row["username"];
$idd = $row["id"];
$username = $row["username"];
$ip = $row["ip"];
$ban = $row["validated"];
$balance = $row["balance"];
$sql = "SELECT `item_name` , `quantity` FROM `books` WHERE `book`='$book'";
$query = mysqli_query($conn, $sql);
while ($rows = mysqli_fetch_assoc($query)) {
$da = $rows["item_name"]; $qty = $rows["quantity"];
$sqll = mysqli_query($conn, "SELECT * FROM promo WHERE code='$da' LIMIT 1");
while ($prow = mysqli_fetch_array($sqll)) {
$pid = $prow["id"];
$price = $prow["price"];
$count = 0;
$count = $qty * $price;
$show = $count + $show;
}
}
echo "$show";
echo "$balance";
if ($show<$balance) {
if (isset($_POST["verify"])) {
$pass = mysqli_real_escape_string($conn, $_POST["pass"]);
if ($pass != "$username") {
header("location: index.php");
}
elseif ($pass = "$username") {
header("location: ../error.php");
}
}
echo '<form action="#" method="post" name="verify"><input class="text" name="pass" type="password" size="25" /><input class="text" type="submit" name="verify" value="view"></form>';
echo "you cant buy here";
exit();
}
} else {
$errormsg = "Error in registering...Please try again later!";
}
}
}
}
?>
<form role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="booking">
<fieldset>
<legend>Check Booking</legend>
<div class="form-group">
<label for="name">Username</label>
<input type="text" name="book" placeholder="Enter Username" required value="<?php if($error) echo $book; ?>" class="form-control" />
<span class="text-danger"><?php if (isset($book_error)) echo $book_error; ?></span>
</div>
<input type="submit" name="booking" value="Sign Up" class="btn btn-primary" />
<table>
<input type="radio" name="action" value="comfirm" <?php if(isset($_POST['action']) && $_POST['action']=="comfirm") { ?>checked<?php } ?>>
<input type="radio" name="action" value="check" <?php if(isset($_POST['action']) && $_POST['action']=="check") { ?>checked<?php } ?>> Check booking <span class="text-danger"><?php if (isset($action_error)) echo $action_error; ?></span>
</div>
</table>
</fieldset>
</form>
in achievement am expected to redirect to error or index page but my code above refress back to first form what are my doing wrong. Big thanks in advance
So I have the following code:
<body>
<?php
$firstname = $lastname = $phone = $phone = $email = $date = $code = "";
$firstnameerr = $lastnameerr = $phoneerr = $emailerr = $dateerr = $codeerr = "";
$check = 0;
$str = "abcdefghijklmnopqrstuvwxyz";
$rand1 = $str[rand(0, strlen($str) - 1)];
$rand2 = $str[rand(0, strlen($str) - 1)];
$rand3 = $str[rand(0, strlen($str) - 1)];
$rand4 = $str[rand(0, strlen($str) - 1)];
$rand5 = $str[rand(0, strlen($str) - 1)];
$final = $rand1 . $rand2 . $rand3 . $rand4 . $rand5;
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (empty($_POST["ffirstname"])){
$firstnameerr = "First Name is empty!";
$check = 1;
} else {
$firstname = testInput($_POST['ffirstname']);
$check = 0;
if (!preg_match("/^[a-zA-Z]*$/",$firstname)){
$firstnameerr = "This is not a valid name!";
$check = 1;
}
}
if (empty($_POST["flastname"])){
$lastnameerr = "Last Name is empty!";
$check = 1;
} else {
$lastname = testInput($_POST['flastname']);
$cheek = 0;
if (!preg_match("/^[a-zA-Z ]*$/",$lastname)){
$lastnameerr = "This is not a valid name";
$check = 1;
}
}
if (empty($_POST["fphone"])){
$phoneerr = "Phone field is empty!";
$check = 1;
}else {
$phone = testInput($_POST['fphone']);
if(!is_numeric($phone)){
$phoneerr = "Phone number is not a number";
$check = 1;
}
}
if (empty($_POST["femail"])){
$emailerr = "E-mail field is empty!";
} else {
$email = testInput($_POST['femail']);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailerr = "E-mail is not valid";
$check = 1;
}
}
if (empty($_POST["fdate"])){
$dateerr = "No date selected!";
$check = 1;
} else {
$date = testInput($_POST['fdate']);
}
if (empty($_POST["fcode"])){
$codeerr = "There is no code!";
$check = 1;
} else {
$code = $_POST["fcode"];
if ($code !== $final){
$codeerr = "The code is wrong";
$check = 1;
}
}
if ($check == 0) {
$host = "localhost";
$user = "root";
$pass = "";
$db = "myfirstdb";
$connect = new mysqli($host,$user,$pass,$db);
if ($connect->connect_error){
die("Connection failed: " . $connect->connect_error);
} else {
echo "Connected successfully!";
}
$sql = "INSERT INTO table1 (firstname , lastname , phone , email , date) VALUES ('$firstname', '$lastname', '$phone', '$email', '$date')";
if ($connect->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
$connect->close();
}
}
function testInput($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="header">
<img src="http://stupidname.org/files/gfx/design/random%20logos/RandomLogo1.png" alt="logo" height="250px" width="250px">
<div id="top"><h1 id="first">Welcome to my website</h1></div>
</div>
<div id="section">
<div id="nav">
<ul>
<li>Home</li>
<li>About</li>
<li>Project</li>
<li>Contact</li>
</ul>
</div>
<div id="article">
<h3 style="text-align: center"><b>Please confirm the form below:</b></h3>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p class="namer">First Name</p><br>
<input type="text" name="ffirstname" id="ffirstnameid"><span class="error"><?php echo $firstnameerr; ?></span><br>
<p class="namer">Last Name</p><br>
<input type="text" name="flastname" id="flastnameid"><span class="error"><?php echo $lastnameerr; ?></span><br>
<p class="namer">Phone Number</p><br>
<input type="text" name="fphone" id="fphoneid"><span class="error"><?php echo $phoneerr; ?></span><br>
<p class="namer">E-mail</p><br>
<input type="text" name="femail" id="femailid"><span class="error"><?php echo $emailerr; ?></span><br>
<p class="namer">Date</p><br>
<input type="text" name="fdate" id="fdateid"><span class="error"><?php echo $dateerr; ?></span><br>
<p class="namer">Enter the Captcha code!</p><br>
<h1><?php echo $final?></h1><br>
<input type="text" name="fcode" id="fcodeid"><span class="error"><?php echo $codeerr; ?></span><br>
<input type="submit" name="fsubmit" value="Submit">
</form>
</div>
</div>
My problem is with the code a.k.a in the if that uses $code and $final to check wheather it's a human or not. Now whenever i write the exact same thing as in the $final variable the program thinks it's not the same so i get the $codeerr. Can someone please help me fix it?
Ok, I added little changes to your code, and I think it should work now.
<?php
session_start();
?>
<body>
<?php
function generateCode() {
$str = "abcdefghijklmnopqrstuvwxyz";
$rand1 = $str[rand(0, strlen($str) - 1)];
$rand2 = $str[rand(0, strlen($str) - 1)];
$rand3 = $str[rand(0, strlen($str) - 1)];
$rand4 = $str[rand(0, strlen($str) - 1)];
$rand5 = $str[rand(0, strlen($str) - 1)];
return $rand1 . $rand2 . $rand3 . $rand4 . $rand5;
}
$firstname = $lastname = $phone = $phone = $email = $date = $code = "";
$firstnameerr = $lastnameerr = $phoneerr = $emailerr = $dateerr = $codeerr = "";
$check = 0;
if(!isset($_SESSION['final'])) {
$_SESSION['final'] = generateCode();
}
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (empty($_POST["ffirstname"])){
$firstnameerr = "First Name is empty!";
$check = 1;
} else {
$firstname = testInput($_POST['ffirstname']);
$check = 0;
if (!preg_match("/^[a-zA-Z]*$/",$firstname)){
$firstnameerr = "This is not a valid name!";
$check = 1;
}
}
if (empty($_POST["flastname"])){
$lastnameerr = "Last Name is empty!";
$check = 1;
} else {
$lastname = testInput($_POST['flastname']);
$cheek = 0;
if (!preg_match("/^[a-zA-Z ]*$/",$lastname)){
$lastnameerr = "This is not a valid name";
$check = 1;
}
}
if (empty($_POST["fphone"])){
$phoneerr = "Phone field is empty!";
$check = 1;
}else {
$phone = testInput($_POST['fphone']);
if(!is_numeric($phone)){
$phoneerr = "Phone number is not a number";
$check = 1;
}
}
if (empty($_POST["femail"])){
$emailerr = "E-mail field is empty!";
} else {
$email = testInput($_POST['femail']);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailerr = "E-mail is not valid";
$check = 1;
}
}
if (empty($_POST["fdate"])){
$dateerr = "No date selected!";
$check = 1;
} else {
$date = testInput($_POST['fdate']);
}
if (empty($_POST["fcode"])){
$codeerr = "There is no code!";
$check = 1;
} else {
$code = $_POST["fcode"];
if ($code !== $_SESSION['final']){
$codeerr = "The code is wrong";
$check = 1;
}
}
if ($check == 0) {
$host = "localhost";
$user = "root";
$pass = "";
$db = "myfirstdb";
$connect = new mysqli($host,$user,$pass,$db);
if ($connect->connect_error){
die("Connection failed: " . $connect->connect_error);
} else {
echo "Connected successfully!";
}
$sql = "INSERT INTO table1 (firstname , lastname , phone , email , date) VALUES ('$firstname', '$lastname', '$phone', '$email', '$date')";
if ($connect->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
$connect->close();
}
}
if($check == 1) {
$_SESSION['final'] = generateCode();
}
function testInput($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="header">
<img src="http://stupidname.org/files/gfx/design/random%20logos/RandomLogo1.png" alt="logo" height="250px" width="250px">
<div id="top"><h1 id="first">Welcome to my website</h1></div>
</div>
<div id="section">
<div id="nav">
<ul>
<li>Home</li>
<li>About</li>
<li>Project</li>
<li>Contact</li>
</ul>
</div>
<div id="article">
<h3 style="text-align: center"><b>Please confirm the form below:</b></h3>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p class="namer">First Name</p><br>
<input type="text" name="ffirstname" id="ffirstnameid"><span class="error"><?php echo $firstnameerr; ?></span><br>
<p class="namer">Last Name</p><br>
<input type="text" name="flastname" id="flastnameid"><span class="error"><?php echo $lastnameerr; ?></span><br>
<p class="namer">Phone Number</p><br>
<input type="text" name="fphone" id="fphoneid"><span class="error"><?php echo $phoneerr; ?></span><br>
<p class="namer">E-mail</p><br>
<input type="text" name="femail" id="femailid"><span class="error"><?php echo $emailerr; ?></span><br>
<p class="namer">Date</p><br>
<input type="text" name="fdate" id="fdateid"><span class="error"><?php echo $dateerr; ?></span><br>
<p class="namer">Enter the Captcha code!</p><br>
<h1><?php echo $_SESSION['final']?></h1><br>
<input type="text" name="fcode" id="fcodeid"><span class="error"><?php echo $codeerr; ?></span><br>
<input type="submit" name="fsubmit" value="Submit">
</form>
</div>
</div>
You must save $final code in $_SESSION for example, because after submit of the form the code for generating $final will get executed and $final will get new value different from the rendered code before submit.
I am working on a project for school and I can't seem to figure out what is wrong with my html/php page.
For the record, I am making an html page with php and it is connected to an Oracle database.
I am trying to add a Person to the Person table but when I type in the information and click submit the form (the entire body of the page) completely disappears and the record is not added to the table. I have been looking online all day for an answer and it still does not work.
My code:
<DOCTYPE HTML>
<html>
<head>
<font size="6">Schedules</font> <font size="6">Passengers</font> <font size="6">Add Passenger</font> <font size="6">Remove Passenger</font><br>
______________________________________________________________________________________________________________________________________________
<h1>Add Passenger</h1>
</head>
<body>
<br><br>
<?php
$passengerID = $passengerFName = $passengerLName = $carNo = $seatNo = $trainID = $tName = "";
$passengerIDErr = $passengerFNameErr = $passengerLNameErr = $carNoErr = $seatNoErr = $trainIDErr = $tNameErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["passengerFName"])) {
$passengerFNameErr = "First Name is required";
} else {
$passengerFName = test_inpit($_POST["passengerFName"]);
if (!preg_match("/^[a-zA-Z ]*$/",$passengerFName)) {
$passengerFNameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["passengerLName"])) {
$passengerLNameErr = "Last Name is required";
} else {
$passengerLName = test_inpit($_POST["passengerLName"]);
if (!preg_match("/^[a-zA-Z ]*$/",$passengerLName)) {
$passengerLNameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["carNo"])) {
$carNoErr = "Car Number is required";
} else {
$carNo = test_inpit($_POST["carNo"]);
if (!is_numeric($carNo)) {
$carNoErr = "Only numbers allowed";
}
}
if (empty($_POST["seatNo"])) {
$seatNoErr = "Seat Number is required";
} else {
$seatNo = test_inpit($_POST["seatNo"]);
if (!is_numeric($seatNo)) {
$seatNoErr = "Only numbers allowed";
}
}
if (empty($_POST["tName"])) {
$tNameErr = "Train Name is required";
} else {
$tName = test_inpit($_POST["tName"]);
if (!preg_match("/^[a-zA-Z ]*$/",$tName)) {
$tNameErr = "Only letters and white space allowed";
}
}
$passengerID = test_input($_POST["passengerID"]);
if (!is_numeric($passengerID)) {
$passengerIDErr = "Only letters and white space allowed";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Enter all information for the passenger<br>
<b>First Name:</b> <input type="text" name="passengerFName" value="<?php echo $passengerFName;?>">
<span class="error">* <?php echo $passengerFNameErr;?></span>
<br><br>
<b>Last Name:</b> <input type="text" name="passengerLName" value="<?php echo $passengerLName;?>">
<span class="error">* <?php echo $passengerLNameErr;?></span>
<br><br>
<b>Car Number:</b> <input type="text" name="carNo" value="<?php echo $carNo;?>">
<span class="error">* <?php echo $carNoErr;?></span>
<br><br>
<b>Seat Number:</b> <input type="text" name="seatNo" value="<?php echo $seatNo"?>">
<span class="error">* <?php echo $seatNoErr;?></span>
<br><br>
<b>Train Name:</b> <input type="text" name="tName" value="<?php echo $tName"?>">
<span class="error">* <?php echo $tNameErr;?></span>
<br><br>
<input type="submit">
<br><br><br>
<?php
$conn = oci_connect('username', 'password', '(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(Host=db1.chpc.ndsu.nodak.edu)(Port=1521)))(CONNECT_DATA=(SID=cs)))');
$query = 'SELECT MAX(personID)
FROM Person';
$stid = oci_parse($conn,$query);
oci_execute($stid,OCI_DEFAULT);
//iterate through each row
while ($row = oci_fetch_array($stid,OCI_ASSOC))
{
//iterate through each item in the row and echo it
foreach ($row as $item)
{
$passengerID = $item + 1;
}
}
oci_free_statement($stid);
oci_close($conn);
?>
<?php
$conn = oci_connect('username', 'password', '(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(Host=db1.chpc.ndsu.nodak.edu)(Port=1521)))(CONNECT_DATA=(SID=cs)))');
$query = 'SELECT trainID
FROM Train
WHERE tName = \''. $tName. '\'';
$stid = oci_parse($conn,$query);
$c1 = oci_execute($stid,OCI_DEFAULT);
if ($c1 === FALSE) {
Echo "Error! Train name does not exist";
}
//iterate through each row
while ($row = oci_fetch_array($stid,OCI_ASSOC))
{
//iterate through each item in the row and echo it
foreach ($row as $item)
{
$trainID = $item;
}
}
oci_free_statement($stid);
oci_close($conn);
?>
<?php
$conn = oci_connect('username', 'password', '(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(Host=db1.chpc.ndsu.nodak.edu)(Port=1521)))(CONNECT_DATA=(SID=cs)))');
$query = 'INSERT INTO Person (personID, fname, lname, carNo, seatNo, trainID)
VALUES (\''. $passengerID. '\', \''. $passengerFName. '\', \''. $passengerLName. '\', \''. $carNo. '\', \''. $seatNo. '\', \''. $trainID. '\')';
$stid = oci_parse($conn,$query);
$c2 = oci_execute($stid,OCI_COMMIT_ON_SUCCESS);
if ($c2 === FALSE) {
Echo "Error! Record was not added. Please check the information and try again";
}
elseif ($c2 === TRUE) {
Echo "Success! Passenger was added to the system";
}
oci_free_statement($stid);
oci_close($conn);
?>
</form>
</body>
</html>
Any help would be great. Thanks.
My problem is, I can't insert the variables $skyr,$eftir,$notandi,$pass and $mel in the code below into my Mysql database when I submit the form. The Insert statement is correct and mysqli_connect() in the $conn variable is correct, I tested it with other variables in other file. So, what is the problem in my code? What I'am doing wrong?
Here is my code:
<!DOCTYPE>
<html>
<head>
<title>Skráðu þig!</title>
<link rel="stylesheet" type "text/css" href="stylesheet.css">
<link rel='stylesheet' type "text/css" href="style_val.css"/>
</head>
<body>
<div class="container">
<banner><div class="bordi"><img src="./myndir/Banner.jpg"/></div></banner>
<div class="front-box"></div>
<div class="skraning">
<?php
//RECAPTCHA - SERVER SIDE
require_once('recaptchalib.php');
$privatekey = "privatekey";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
$invalid = "Vinsamlegast ritaðu aftur inn stafina fyrir ofan.";
}
else{
$invalid = "";
}
//Tekið af:https://developers.google.com/recaptcha/docs/php
error_reporting(1); error_reporting(E_ALL); ini_set('display_errors', 1);//Við viljum ekki sjá villurnar, heldur viljum við hafa hlutina á mannamáli. Við búum síðan til aðgerðir(functions) til að höndla þær villur sem kunna að koma upp.
?>
<?php
$mysql_host = "some host";
$mysql_database = "some database";
$mysql_user = "some user";
$mysql_password = "some password";
$dbname = 'some database name';
$conn = mysqli_connect($mysql_host,$mysql_user,$mysql_password,$dbname);
if(!$conn){
echo "Get ekki tengst gagnagrunni. Vefstjóra gert viðvart";
villupost();
}
function villupost(){
$to = 'arnarfreyr#hive.is';
$subject = 'MYSQL VILLA!';
$message = mysqli_error();
$headers = 'sjálfvirkur tölvupóstur';
mail($to,$subject,$message,$headers);
}
function sanityCheck($string, $type, $length){
// assign the type
$type = 'is_'.$type;
if(!$type($string))
{
return FALSE;
}
// now we see if there is anything in the string
elseif(empty($string))
{
return FALSE;
}
// then we check how long the string is
elseif(strlen($string) > $length)
{
return FALSE;
}
else
{
// if all is well, we return TRUE
return TRUE;
}
}
//Tekið og breytt af: http://www.phpro.org/tutorials/Validating-User-Input.html
// define variables and initialize with empty values
$skyrErr = $eftirErr = $notandiErr = $passErr = $melErr = $c_passErr = $melErr_s ="";
$skyr = $eftir = $notandi = $pass = $mel = $c_pass = $mel_s = "";
$fylla_ut = "Þennan reit verður að fylla út.";
$fylla_rett = "Vinsamlegast fylltu út rétt netfang.";
if (isset($_POST['sub'])) {
if (empty($_POST["skyr"])==FALSE && sanityCheck($_POST["skyr"],'string',60)!=FALSE) {
$skyr = mysqli_real_escape_string($conn,$_POST["skyr"]);
}
else {
$skyrErr = '<span class="red">'.$fylla_ut.'</span>';
$pass = "";
$c_pass = "";
}
if (empty($_POST["eftir"])==FALSE && sanityCheck($_POST["eftir"],'string',60)!=FALSE) {
$eftir = mysqli_real_escape_string($conn,$_POST["eftir"]);
}
else {
$eftirErr = '<span class="red">'.$fylla_ut.'</span>';
$pass = "";
$c_pass = "";
}
if (empty($_POST["notandi"])==FALSE && sanityCheck($_POST["notandi"],'string',15)!=FALSE){
$notandi = mysqli_real_escape_string($conn,$_POST["notandi"]);
}
else {
$notandiErr = '<span class="red">'.$fylla_ut.'</span>';
$pass = "";
$c_pass = "";
}
if (empty($_POST["pass"])==FALSE) {
if (!preg_match('/^(?=.*\d)(?=.*\W)(?=.*[a-z])(?=.*[A-Z]).{6,15}$/', $_POST["pass"])){
$passErr = "Lykilorðið verður að innihalda lágstafi, hástafi, tölustafi og sérstafi t.d. !\"#$%&/";
$pass = "";
$c_pass = "";
}
else{
$pass = $_POST["pass"];
$salted = mcrypt_create_iv(64);
$pass = mysqli_real_escape_string($conn,hash('sha512',$_POST["pass"].$salted));
}
}
else{
$passErr = '<span class="red">'.$fylla_ut.'</span>';
}
if (empty($_POST["mel"])==FALSE && sanityCheck($_POST["mel"],'string',60)!=FALSE){
if (!filter_var($_POST["mel"], FILTER_VALIDATE_EMAIL)){
$melErr = '<span class="red">'.$fylla_rett.'</span>';
$pass = "";
$c_pass = "";
}
else{
$mel = mysqli_real_escape_string($conn,$_POST["mel"]);
}}
else{
$melErr = '<span class="red">'.$fylla_ut.'</span>';
$pass = "";
$c_pass = "";
}
if (empty($_POST["mel_s"])==FALSE && sanityCheck($_POST["mel_s"],'string',60)!=FALSE){
if (!filter_var($_POST["mel_s"], FILTER_VALIDATE_EMAIL)){
$melErr_s = '<span class="red">'.$fylla_rett.'</span>';
$pass = "";
$c_pass = "";
}
if ($_POST["mel"]!=$_POST["mel_s"]){
$melErr_s = '<span class="red">Netföng stemma ekki.</span>';
$pass = "";
$c_pass = "";}
else{
$mel_s = $_POST["mel_s"];
}
}
else {
$melErr_s = '<span class="red">'.$fylla_ut.'</span>';
$pass = "";
$c_pass = "";
}
if (empty($_POST["c_pass"])==FALSE){
if($_POST["pass"]!=$_POST["c_pass"]){
$c_passErr = '<span class="red">Lykilorð stemma ekki. Reyndu aftur.</span>';
$pass = "";
$c_pass = "";
}
else{
$c_pass = $_POST["c_pass"];
}
}
else{
$c_passErr = '<span class="red">'.$fylla_ut.'</span>';
$pass = "";
$c_pass = "";
}
if ($skyr!=null&&$eftir!=null&&$notandi!=null&&$pass!=null&&$mel!=null/*&&$_POST["recaptcha_challenge_field"]!=null&&$_POST["recaptcha_response_field"]!=null*/){
$data = "INSERT INTO Login(Skírnarnafn,Eftirnafn,Notandanafn,Lykilorð,Tölvupóstur)
VALUES ('$skyr', '$eftir', '$notandi', '$pass', '$mel')";
mysqli_query($conn,$data);
mysqli_close($conn);
}
}
?>
<div class="formtext"></br>Hér getur þú skráð þig. Fylltu út formið hér að neðan.
Athugaðu að lykilorðið má ekki vera minna en 6 stafir
og ekki meira en 15 stafir.
Reit með stjörnu verður að fylla út.</div>
<script>
var RecaptchaOptions = {
theme : 'custom',
custom_theme_widget: 'recaptcha_widget'
};
</script>
<form class="formpos" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label>Skírnarnafn:<span class="red"> *</span></label>
<input class="skrainnp" type="text" name="skyr" value="<?php echo htmlspecialchars($skyr);?>" maxlength="60"/>
<span class="form_err"><?php echo $skyrErr;?></span>
</br>
</br>
<label>Eftirnafn:<span class="red"> *</span></label>
<input class="skrainnp" type="text" name="eftir" class="eftirnafn" value="<?php echo htmlspecialchars($eftir);?>" maxlength="60"/>
<span class="form_err"><?php echo $eftirErr;?></span></label>
</br>
</br>
<label>Notandanafn:<span class="red"> *</span></label>
<input class="skrainnp" type="text" name="notandi" class="notandanafn" value="<?php echo htmlspecialchars($notandi);?>" maxlength="15"/>
<span class="form_err"><?php echo $notandiErr;?></span>
<br/>
<br/>
<label>Lykilorð:<span class="red"> *</span><input class="skrainnp" type="password" name="pass" class="lykilorð" value="<?php echo htmlspecialchars($pass);?>" maxlength="15"/>
<span class="form_err"><?php echo $passErr;?></span>
</br>
</br>
<label>Staðfesta lykilorð:<span class="red"> *</span></label><input class="skrainnp" type="password" name="c_pass" class="s_lykilorð" value="<?php echo htmlspecialchars($c_pass);?>" maxlength="15"/>
<span class="form_err"><?php echo $c_passErr;?></span>
</br>
</br>
<label>Netfang:<span class= "red"> *<span></label>
<input class="skrainnp" type="text" name="mel" class="postur" value="<?php echo htmlspecialchars($mel)?>" maxlength="60"></input>
<span class="form_err"><?php echo $melErr;?></span>
</br>
</br>
<label>Netfang aftur:<span class= "red"> *<span></label>
<input class="skrainnp" type="text" name="mel_s" class="postur_s" value="<?php echo htmlspecialchars($mel_s)?>" maxlength="60"/>
<span class="form_err"><?php echo $melErr_s;?></span>
</br>
</br>
<!--RECAPTCHA-HTML BYRJAR-->
<div>
<div id="recaptcha_widget" style="display:none">
<div id="recaptcha_image"></div>
<div class="recaptcha_only_if_incorrect_sol" style="color:red"></div>
<span class="recaptcha_only_if_image">Ritaðu stafina fyrir ofan:</span>
<span class="recaptcha_only_if_audio">Ritaðu tölustafina sem þú heyrir:</span>
<input type="text" id="recaptcha_response_field" name="recaptcha_response_field" />
<div class="recaptcha_nytt">Fá nýtt</div>
<div class="recaptcha_lesa">Lesa upp</div>
<div class="recaptcha_mynd">Fá mynd</div>
<div class="recaptcha_hjalp">Hjálp</div>
<script type="text/javascript"
src="http://www.google.com/recaptcha/api/challenge?k=6LeHcvcSAAAAABMGhQ7ZqaWpJs0L0b93VKguMQwN">
</script>
<noscript>
<iframe src="http://www.google.com/recaptcha/api/noscript?k=6LeHcvcSAAAAABMGhQ7ZqaWpJs0L0b93VKguMQwN"
height="300" width="500" frameborder="0"></iframe><br>
<textarea name="recaptcha_challenge_field" rows="3" cols="40">
</textarea>
<input type="hidden" name="recaptcha_response_field"
value="manual_challenge">
</noscript>-->
<!--RECAPTCHA-HTML ENDAR-->
<?php //RECAPTCHA
require_once('recaptchalib.php');
$publickey = "6LeHcvcSAAAAABMGhQ7ZqaWpJs0L0b93VKguMQwN"; // you got this from the signup page
echo recaptcha_get_html($publickey);
echo "<span class='recaptcha_err'>".$invalid."</span>";
?>
</br>
</br>
<input type="submit" name="sub" class="senda" value="Áfram"/>
</form>
</div>
</div>
</body>
</html>
UPTADE:
I found out that the insert statement is not working.
I know for sure that the connection is working, it's used in other file and was used when this worked correctly. Then something went wrong. I don't know why.
So, what's wrong with this code below?
$skyr = "Arnar";
$eftir = "Kristinsson";
$notandi = "afk0901";
$pass = "afk0901";
$mel = "arnarfreyr#hive.is";
$data = "INSERT INTO Login(Skírnarnafn,Eftirnafn,Notandanafn,Lykilorð,Tölvupóstur)
VALUES ('$skyr', '$eftir', '$notandi', '$pass', '$mel')";
mysqli_query($conn,$data);
mysqli_close($conn);
It looks like I've found what was wrong...it was not my code. It was the database. I used wrong Indexes. I changed Index types from unique to Index. Problem solved. Thank you who tried to answer :) I really found this out after 5 days...I don't know why I did not fell this in mind before.