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.
Related
I am trying to create a PHP validation FORM.
Validation errors are displaying correctly for me every time. My only problems is that I am not able to set the focus on the input with error if an error came.
For example, I am using $rut_error, $first_name_error, $last_name_error, $email_error, $address_error and I want to set focus on the corresponding input if any error came.
I tried using javascript but I am not cleared where should I put that code, Could anyone guide me how to solve it? Can I fix this only with PHP? Please help.
I tried entering here but no success:
//First name Validation
if (empty($_POST["first_name"]) and $rut_error == '')
{
$first_name_error = "First name is required";
echo "<script>document.registration.first_name.focus();</script>";
}
My code is below:
addStudent.php
<html>
<head>
<title>Add Client</title>
</head>
<body>
Show Client
<?php include('form_processStudent.php'); ?>
<div id="divAgenda">
<form id="contact" action="<?= htmlspecialchars($_SERVER["PHP_SELF"]) ?>" method="post" name = "registration">
<fieldset>
<span class="error"><?= $rut_error ?></span><br>
<input placeholder="Rut..." id="rut" type="text" name="rut" value="<?= $rut ?>" tabindex="1" size="8" maxlength="8"> - <input type="text" name="dv" value="<?= $dv ?>" size="1" tabindex="2" maxlength="1"> Ejemplo: 12345678-1<br>
</fieldset>
<fieldset>
<span class="error"><?= $first_name_error ?></span><br>
<input placeholder="Primer Nombre..." id="first_name" type="text" id="first_name" name="first_name" value="<?= $first_name ?>" maxlength="50" tabindex="3"><br>
</fieldset>
<fieldset>
<span class="error"><?= $last_name_error ?></span><br>
<input placeholder="Segundo Nombre..." id="last_name" type="text" id="last_name" name="last_name" value="<?= $last_name ?>" maxlength="50" tabindex="4"><br>
</fieldset>
<fieldset>
<span class="error"><?= $email_error ?></span><br>
<input placeholder="Correo Electrónico..." id="email" type="text" name="email" value="<?= $email ?>" maxlength="100" tabindex="5"><br>
</fieldset>
<fieldset>
<span class="error"><?= $address_error ?></span><br>
<input placeholder="Dirección..." id="address" type="text" name="address" value="<?= $address ?>" maxlength="200" tabindex="5"><br>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Enviar</button>
</fieldset>
</form>
</body>
</html>
form_processStudent.php
<?php
// define variables and set to empty values
echo"<script>
document.registration.last_name.focus();
return false;
</script>";
$rut_error = $first_name_error = $last_name_error = $email_error = $address_error = "";
$rut = $dv = $first_name = $last_name = $email = $address = "";
if(isset($_POST['submit']))
{
//RUT Validation
$rut = test_input($_POST["rut"]);
$dv = ($_POST["dv"]);
if ( empty($_POST["rut"]))
{
$rut_error = "RUT is required";
}
else if ( $dv=='' )
{
$rut_error = "Verification digit is required";
}
else if (!is_numeric($rut))
{
$rut_error = "Entered RUT is not numeric";
}
else if (!((strlen($rut) == 7) or (strlen($rut) == 8)))
{
$rut_error = "Number of digits of RUT not valid";
}
else
{
$x = 2; $s = 0; $dv2 = 0;
for($i = (strlen($rut) - 1); $i >= 0; $i--)
{
if($x > 7)
$x = 2;
$s += ($rut[$i] * $x);
$x++;
}
$dv2=11-($s % 11);
if($dv2 == 10)
$dv2 = 'K';
if($dv2 == 11)
$dv2 = '0';
if($dv2 == $dv)
{
//echo "<br>". "rut={" . $rut . "}";
//echo "<br>". "dv ={" . $dv . "}";
}
else
$rut_error = "invalid RUT";
}
//First name Validation
if (empty($_POST["first_name"]) and $rut_error == '')
{
$first_name_error = "First name is required";
echo "<script>document.registration.first_name.focus();</script>";
}
else
{
if ($rut_error == '')
{
$first_name = test_input($_POST["first_name"]);
//echo "<br>". "first_name={" . $first_name . "}";
}
}
//Last name Validation
if (empty($_POST["last_name"]) and $rut_error == '' and $first_name_error == '')
{
$last_name_error = "Second name is required";
echo "<script>function validateform()
{
document.registration.last_name.focus();
return false;
}
</script>";
}
else
{
if ($rut_error == '' and $first_name_error == '')
{
$last_name = test_input($_POST["last_name"]);
//echo "<br>". "last_name={" . $last_name . "}";
}
}
//Email Validation
if (empty($_POST["email"]) and $rut_error == '' and $first_name_error == '' and $last_name_error == '')
{
$email_error = "Email is required";
}
else
{
if ($rut_error == '' and $first_name_error == '' and $last_name_error == '')
{
$email = test_input($_POST["email"]);
//echo "<br>". "email={" . $email . "}";
// check if e-mail address is well-formed
if ((!filter_var($email, FILTER_VALIDATE_EMAIL)) and $rut_error == '' and $first_name_error == '' and $last_name_error == '')
{
$email_error = "Invalid email";
}
}
}
//Adress Validation
if (empty($_POST["address"]) and $rut_error == '' and $first_name_error == '' and $last_name_error == '' and $email_error == '')
{
$address_error = "Address is required";
}
else
{
if ($rut_error == '' and $first_name_error == '' and $last_name_error == '' and $email_error == '')
{
$address = test_input($_POST["address"]);
//echo "<br>". "address={" . $address . "}";
}
}
if ($rut_error == '' and $first_name_error == '' and $last_name_error == '' and $email_error == '' and $address_error == '')
{
//echo "<br>". "Dentro de IF";echo "<br>";
require_once('mysqli_connect.php');
$query = "INSERT INTO students (rut, dv, first_name, last_name, email, address) VALUES (?,?,?,?,?,?)";
$stmt = mysqli_prepare($dbc, $query);
mysqli_stmt_bind_param($stmt, "ssssss", $rut, $dv, $first_name, $last_name, $email, $address);
mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
echo 'affected_rows=<' . $affected_rows . '>';
if($affected_rows == 1)
{
$rut = $dv = $first_name = $last_name = $email = $address = '';
echo "<br>"."Client Entered";
mysqli_stmt_close($stmt);
mysqli_close($dbc);
}
else
{
echo 'Error Occurred<br />';
echo mysqli_error();
mysqli_stmt_close($stmt);
mysqli_close($dbc);
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
getStudentInfo.php
Add Client
<?php
// Get a connection for the database
require_once('mysqli_connect.php');
// Create a query for the database
$query = "SELECT serie, rut, dv, first_name, last_name, email, address FROM students ORDER BY serie desc";
// Get a response from the database by sending the connection
// and the query
$response = #mysqli_query($dbc, $query);
// If the query executed properly proceed
if($response)
{
echo '<table align="left" cellspacing="5" cellpadding="8">
<tr><td align="left"><b>Serie </b></td>
<td align="left"><b>Rut </b></td>
<td align="left"><b>Dígito Verificador </b></td>
<td align="left"><b>Primer Nombre </b></td>
<td align="left"><b>Segundo Nombre </b></td>
<td align="left"><b>Email </b></td>
<td align="left"><b>Dirección </b></td>
</tr>';
// mysqli_fetch_array will return a row of data from the query
// until no further data is available
while($row = mysqli_fetch_array($response))
{
echo '<tr><td align="left">' . $row['serie'] . '</td>
<td align="left">' . $row['rut'] . '</td>
<td align="left">' . $row['dv'] . '</dv>
<td align="left">' . $row['first_name'] . '</td>
<td align="left">' . $row['last_name'] . '</td>
<td align="left">' . $row['email'] . '</td>
<td align="left">' . $row['address'] . '</td>'
;
echo '</tr>';
}
echo '</table>';
}
else
{
echo "Couldn't issue database query<br />";
echo mysqli_error($dbc);
}
// Close connection to the database
mysqli_close($dbc);
?>
mysqli_connect.php
<?php
// Defined as constants so that they can't be changed
DEFINE ('DB_USER', 'studentweb');
DEFINE ('DB_PASSWORD', '123');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'dbTest');
// $dbc will contain a resource link to the database
// # keeps the error from showing in the browser
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die('Could not connect to MySQL: ' . mysqli_connect_error());
//echo "Connected...\n\n";
?>
You can do it via javascript.
You put a script that would work once the page is fully loaded.
The script will checkout the content of each <span class="error">. If some non empty one is found, it shall put the focus on it.
In your html:
<body>
...
<script type="text/javascript">
window.onload = function(){
var errors = document.querySelectorAll('.error');
for(var i = 0, l = errors.length; i < l; i++){
var error = errors[i],
shouldForcus = error.textContent.trim().length !== 0;
if(shouldFocus){
var input = error.parentNode.querySelector('input');
input.focus();
break;
}
}
}
</script>
</body>
I'm new to PHP and I'm trying some form validation. I have the following code:
I submit a form and submit the data to an SQL statement if it passes validation. If the form is valid, it redirects to an external success page.
What I can't do is get the original post variables onto the success page. How could I do this please? My code is below:
PHP:
<body>
<?php
$firstnameErr = $emailErr = $lastnameErr = $gradeErr = $roleErr = "";
$firstname = $email = $lastname = $grade = $role = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$firstnameErr = "First name is required";
} else {
$firstname = user_input($_POST["firstname"]);
}
if (empty($_POST["lastname"])) {
$lastnameErr = "Last mame is required";
} else {
$lastname = user_input($_POST["lastname"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = user_input($_POST["email"]);
}
if (empty($_POST["grade"])) {
$gradeErr = "Grade is required";
} else {
$grade = user_input($_POST["grade"]);
}
if (empty($_POST["role"])) {
$roleErr = "Role is required";
} else {
$role = user_input($_POST["role"]);
}
if($firstnameErr == '' && $emailErr == '' && $lastnameErr == '' && $gradeErr == '' && $roleErr == ''){
$stmt = $conn->prepare("INSERT INTO `Tom`.`staff_details` (`first_name`, `surname`, `role`, `grade`,`email`) VALUES ('$firstname', '$lastname','$role', '$grade','$email');");
$stmt->execute();
header('Location: staff_added.php');
exit();
};
}
function user_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
HTML:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<fieldset>
<p><span class="error">* required field</span></p>
<label>First name:</label><input type="text" name="firstname" />
<span class="error">* <?php echo $firstnameErr;?></span><br>
<label>Last name:</label><input type="text" name="lastname" />
<span class="error">* <?php echo $lastnameErr;?></span><br>
<label>Role:</label><input type="text" name="role" />
<span class="error">* <?php echo $roleErr;?></span><br>
<label>Grade:</label><input type="text" name="grade" />
<span class="error">* <?php echo $gradeErr;?></span><br>
<label>Email:</label><input type="text" name="email" />
<span class="error">* <?php echo $emailErr;?></span><br><br>
<input class="standard_submit" type="submit" value="Save" id="submit_search_button">
</fieldset>
</form>
I would like those variables to move across to the staff_added.php page so that I can print them back to the user. I've done some reading over this but as far, it's not making much sense.
Any help would be appreciated.
Thank you
You can store the variables in a SESSION object and then will be available from everywhere :
<?php
session_start();
//other code...
$_SESSION["role"] = $role;
//other code...
?>
Using prepared statements you should be looking at an approach like this perhaps rather than directly embedding variables in the sql.
<?php
function user_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$firstname = $email = $lastname = $grade = $role = false;
if( $_SERVER["REQUEST_METHOD"] == "POST" ) {
$errors=array();
if( empty($_POST["firstname"])) $errors[] = "First name is required";
else $firstname = user_input( $_POST["firstname"] );
if( empty($_POST["lastname"])) $errors[] = "Last mame is required";
else $lastname = user_input($_POST["lastname"]);
if( empty($_POST["email"])) $errors[] = "Email is required";
else $email = user_input($_POST["email"]);
if( empty($_POST["grade"]) ) $errors[] = "Grade is required";
else $grade = user_input($_POST["grade"]);
if( empty($_POST["role"])) $errors[] = "Role is required";
else $role = user_input( $_POST["role"] );
if( empty( $errors ) ){
$stmt = $conn->prepare("INSERT INTO `Tom`.`staff_details` (`first_name`, `surname`, `role`, `grade`,`email`) VALUES (?,?,?,?,?);");
if( $stmt ){
$stmt->bind_param('sssss',$firstname,$lastname,$role,$grade,$email);
$stmt->execute();
exit( header( 'Location: staff_added.php' ) );
} else { echo 'statement failed'; }
} else {
foreach( $errors as $error )echo $error . '<br />';
}
}
?>
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.
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>
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.