When form submitted action does not execute - php

I am making a basic registration form and my code is not working I tried problem-solving but I do not see any issues in my code. When the user submits the form the page does not go to register.php
Here is my connect.php code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "WifiP";
/* Attempt to connect to MySQL database */
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if($conn === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
Here is my header.php code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>WifiP | Home</title>
<link rel="stylesheet" type="text/css" href="main.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
</head>
<body>
<ul>
<li>Home</li>
<li>Wifi</li>
<li>Login</li>
</ul>
Here is my footer.php code:
</body>
</html>
Here is my register.php code:
<?php
require_once 'connect.php' ;
$sql = "INSERT INTO users (email, password)
VALUES ('".$_POST["email"]."','".$_POST["password"]."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Here is my register_page.php code:
<?php require_once 'header.php' ?>
<center>
<h1 class='pageTitle'>Register</h1>
<a href="register_page.php" class='registerLink'> Or Login</a><br>
<form action="register.php" method="post">
<input type="text" name="email" placeholder="Email"> <br>
<input type="password" name="password" placeholder="Password"><br>
<input type="password" name="rPassword" placeholder="Retype Password"><br>
<input type="button" value="Submit">
</form>
</center>
<?php require_once 'footer.php' ?>

The HTML element defines a form that is used to collect user input and after user insert that data need to submit the form to send that inserted data to action path.
To submitting a form there are some possible ways but according to your question you want to send data to 'register.php' by clicking the button you defined.
Form elements are different types of input elements, like text fields, checkboxes, radio buttons, submit buttons, and more.
In this case for submission the form you need a submit button that type should be "submit" not "button"
try change your register page like below
<input type="submit" value="Submit">
please according to the input type that it is "submit" not "button"
now by clicking the submit button your form data will send to action path.

Related

Inserting record into SQLite using PHP

For the past two hours, I have been trying to create a simple insertion form that connects to a SQLite. For some reason, the insertion of a new record won't work. I get no error message when I run my app using php -S localhost:1234. My form is just emptied out without any insertion after a click on the Submit button.
My database is named database.db, the table is named students_tb, and the columns in the table are id, sname and score.
Here is my code, which is based on https://www.youtube.com/watch?v=cyl0Oj3rmmg&list=PLU70qqWW4frENsWYAm-tAKp2ZJQ_dt3WR&index=8. I checked and rechecked the 3-minute-long tutorial, but wasn't successful at tracking down my bug. I guess this must be a silly mistake, but I really can't find it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Student</title>
<style>
label, input {
display: block;
}
</style>
</head>
<body>
<h1>Add student to database</h1>
<?php
// has the form been submitted?
// if not, show the HTML form
if (!isset($_POST['submit'])) {
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<label for="sname">Student's Name</label>
<input type="text" name="sname" required>
<label for="score">Score</label>
<input type="number" name="score" required>
<button type="submit">Submit</button>
</form>
<?php
} else {
try {
$db = new PDO("sqlite:database.db");
$sql = "INSERT INTO students_tb (sname, score) VALUES (:sname, :score)";
$stat = $db->prepare($sql);
// named params
$sname = filter_input(INPUT_POST, "sname");
$stat->bindValue(":sname", $sname, PDO::PARAM_STR);
$score = filter_input(INPUT_POST, "score");
$stat->bindValue(":score", $score, PDO::PARAM_INT);
$success = $stat->execute();
// does the value exist?
if ($success) {
echo "The student has been added to the database.";
} else {
echo "The student has NOT been added to the database.";
}
$db = null;
} catch (PDOException $e) {
// for development
print "We had an error: " . $e->getMessage() . "<br>";
die();
}
}
?>
</body>
</html>
It has been a while since I worked in PHP, but I think the problem might be in the HTML code of the form. You have:
<button type="submit">Submit</button>
And your PHP code is checking for a value of the variable named submit, but this field does not have a name, only a type. Should it be:
<button type="submit" name="submit">Submit</button>

Can not Insert data into MySQL from PHP form

After I fill up the PHP form, the data is not showing in mysql. What is wrong with my code and how can i fix it?
These are all my codes. Please help me I am still a beginner in php. I tried searching my error in other websites however it is not working.
This is the code for the form
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- C R E A T E D A T A -->
<form class="" action="createdatatry.php" method="post">
<h3>ENTER THE FOLLOWING SUPPLIER INFORMATION:</h3>
<input type="text" name="Supplier_Name" placeholder="Enter Supplier Name" required/>
<input type="text" name="Supplier_Contact" placeholder="Enter Contact No." required/>
<input type="text" name="Supplier_StreetNo" placeholder="Enter Street No." required/>
<input type="text" name="Supplier_Province" placeholder="Enter Province" required/>
<input type="text" name="Supplier_PostalCode" placeholder="Enter Postal Code" required/>
<input type="text" name="Supplier_Country" placeholder="Enter Country" required/>
<input type="submit" name="create" value="CREATE">
</form>
</body>
</html>
This is the code for the mysql connection
database.php
<?php
$host = 'localhost';
$user = 'root';
$password = '';
$database = 'sourcingdb';
$connection = mysqli_connect($host, $user, $password, $database);
if (mysqli_connect_error()) {
echo "Error Unable to connect to MySQL server <br>";
echo "Message: ".mysqli_connect_error()."<br>";
}
?>
This is the code in creating/ inserting data into mysql
createdatatry.php
<?php
require('./database.php');
if (isset($_POST['create'])) {
$Supplier_Name = $_POST['Supplier_Name'];
$Supplier_Contact = $_POST['Supplier_Contact'];
$Supplier_StreetNo = $_POST['Supplier_StreetNo'];
$Supplier_Prov = $_POST['Supplier_Prov'];
$Supplier_PostalCode = $_POST['Supplier_PostalCode'];
$Supplier_Country = $_POST['Supplier_Country'];
$queryCreate = "INSERT INTO supplierinfo (`Supplier_Name`, `Supplier_Contact`, `Supplier_StreetNo`, `Supplier_Province`, `Supplier_PostalCode`, `Supplier_Country`) VALUES ('$Supplier_name', '$Supplier_Contact', '$Supplier_StreetNo', '$Supplier_Prov', '$Supplier_PostalCode', '$Supplier_ountry')";
$sqlCreate = mysqli_query($connection, $queryCreate);
echo '<script>alert("Successfully created!")</script>';
//echo '<script>window.location.href = "/sourcing/index.php"</script>';
}
?>
Problem solved: Apparently, I did not check the structure of my table (ex. data types) that is why the data is not visible in mysql.
You have given wrong file name in forms action on index.php
You have to write action="createdata.php" in form on index.php
Form action should be like this :
form action = "createdata.php" method="POST"
Your query should be like this :
$queryCreate = "INSERT INTO supplierinfo (Supplier_Name, Supplier_Contact, Supplier_StreetNo, Supplier_Province, Supplier_PostalCode, Supplier_Country) VALUES ('$Supplier_name', '$Supplier_Contact', '$Supplier_StreetNo', '$Supplier_Prov', '$Supplier_PostalCode', '$Supplier_Country')";
For your query
$queryCreate = "INSERT INTO supplierinfo (`Supplier_Name`, `Supplier_Contact`, `Supplier_StreetNo`, `Supplier_Province`, `Supplier_PostalCode`, `Supplier_Country`) VALUES ('$Supplier_name', '$Supplier_Contact', '$Supplier_StreetNo', '$Supplier_Prov', '$Supplier_PostalCode', '$Supplier_ountry')";
$sqlCreate = mysqli_query($connection, $queryCreate);
You only assigned mysqli_query($connection, $queryCreate) to a PHP variable , but you didnt execute it.
Try this
if(mysqli_query($connection, $queryCreate)){
echo '<script>alert("Successfully created!")</script>';
}

PHP Form does not log in and move to next page

I ran into another problem with my website that I can't get around.
I'm trying to make it so when the admin logs in he will be taken to the admin page but for some reason when I enter the correct details into the log in and press the submit button it just brings me back to the admin log in page again.
Here is a Gyazo of my problem
https://gyazo.com/34f133fea4b20ec285ee7ff491053145
<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<meta charset="UTF-8">
<title>Login</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js" type="text/javascript"></script>
<link href='https://fonts.googleapis.com/css?family=Ubuntu:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/148866/reset.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<body>
<main id="cd-main-content">
<section id="cd-intro">
<h1>Admin Log In</h1>
<header class="cd-header">
<?php
require('db.php');
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
// removes backslashes
$adminusername = stripslashes($_REQUEST['adminusername']);
//escapes special characters in a string
$adminusername = mysqli_real_escape_string($con,$adminusername);
$adminpassword = stripslashes($_REQUEST['adminpassword']);
$adminpassword = mysqli_real_escape_string($con,$adminpassword);
//Checking is user existing in the database or not
$query = "SELECT * FROM `admin` WHERE username='$adminusername'
and password='".md5($adminpassword)."'";
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['username'] = $adminusername;
// Redirect user to admin page /////////////////////////////////////////////////////////////////////
header("Location: adminpage.php");
}else{
echo "<div class='form'>
<h3>Username/password is incorrect.</h3>
<br/>Click here to <a href='admin.php'>Login</a></div>";
}
}else{
?>
<div class="form">
<form action="" method="post" name="login">
<input type="text" name="adminusername" placeholder="Username" required />
<input type="password" name="adminpassword" placeholder="Password" required />
<input name="submit" type="submit" value="Login" />
</form>
</div>
<?php } ?>
<a class="cd-menu-trigger" href="#main-nav">Menu<span></span></a>
</header>
<div class="cd-blurred-bg"></div>
</section> <!-- cd-intro -->
</main>
<div class="cd-shadow-layer"></div>
<nav id="main-nav">
<ul>
<li><span>Login</span></li>
<li><span>What's On</span></li>
<li><span>Favourites</span></li>
<li><span>About</span></li>
<li><span>Admin</span></li>
</ul>
Close<span></span>
</nav>
</body>
<script src='js/jquery.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
You are doing:
if (isset($_POST['username'])) {
//...
}
Try this
if (isset($_POST['adminusername'])) {
//...
}
As a note, I suggest you to try use a framework, like laravel.
first I would debug by var_dump($_POST) and see what you get. I would bet that since you dont have an ID set for the input value name it is not working. If anything checking for ISSET($_POST['username']) would never work because you do not have a vairable set for that name.
var_dump($_POST) and see what you get. If not add an ID='username' to the input
try this :-
if (isset($_POST['submit'])){
// rest of code...
}

a comment in case of field empty php?

I have 3 PHP files , the first one contain fields to compile which mean in html a form. the second , the code that took the fields from the first file and register them inside a folder .txt with a title=the date and time , the third file confirm the registration: i did the 3 files they work : but i would like to reload the fields page, in case where I click on the button and one or more of the fields is empty, with a comment near the field empty :
the first file form.php is:
I put the code only with one field to don't disturb more :`
<!doctype html>
<html lang="it">
<head>
<meta charset="utf-8">
<title>Titre de la page</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
}
<form action="POST.PHP" method="POST">
<input type="text" name="name" placeholder="name" value="name">
<button type="button">Click Me!</button>
</form>
</body>
</html>
the second file POST.php contain :
<?php
$nameErr= "";
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Missing";
} else {
$name = $_POST["name"];
$filename="file/". date("Y-m-d_H_m_s") . "_" . uniqid() . ".txt" ;
$fp = fopen( $filename, "w" );
fwrite($fp, $name);
fclose($fp);
include 'registred.php';
}
}
?>
and the third file registred.php contain :
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Titre de la page</title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<h2>completed registration</h2>
<h3>wish to see you soon !!</h3>
<ul>
<li >name:<?=htmlspecialchars($name)?></li>
</ul>
</body>
</html>
This is not the best way to do that but its good enough to give you a idea about how u r gonna manage this.
<?php session_start();?>
<form action="post.php" method="post">
<input type="text" name="txtName">
<?php
if(isset($_SESSION['mising_data'])){
echo $_SESSION['mising_data'];
}
?>
<input type="submit" name="btnSubmit">
</form>
now in post.php file
<?php
session_start();
if (isset($_POST['btnSubmit'])) {
if (empty($_POST['txtName'])) {
$_SESSION['mising_data'] = 'missing Data';
header('Location: form.php');
}
}
?>
to handle this professionally u should use jquery ajax() method

I cannot submit a form in php and redirect

I have a page (index.php) is a login page so I need to validate a user and redirect to other page but header(Location:"welcome.php"); is not working, the sql query is ok but I only get the message "Login Successful" and the page doest redirect to the other called welcome.php
I'm newbie in PHP so any help is great!
<!DOCTYPE html>
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="favicon.ico">
<title>Login</title>
<link href="bootstrap.min.css" rel="stylesheet">
<link href="signin.css" rel="stylesheet">
</head>
<body>
<div class="container">
<form class="form-signin" role="form" action="<?=$_SERVER['PHP_SELF']?>" method="POST">
<h2 class="form-signin-heading"><center>Bienvenido!</center></h2>
<input type="text" name="username" class="form-control" placeholder="Username" required="" autofocus="">
<input type="password" name="password" class="form-control" placeholder="Password" required="">
<div class="checkbox">
<label><input type="checkbox" value="remember-me"> Remember me </label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
</form>
</div>
<?php
$link = mysqli_connect("localhost","root","root","testdb") or die ("error".mysqli_error($link));
$username = $_POST['username'];
$password= $_POST['password'];
if (isset($_POST['username'])) {
$sql = "SELECT * FROM testdb.user WHERE username='$username' and password='$password'";
$result = mysqli_query($link,$sql);
if ($result);
{
$num=mysqli_num_rows($resultado);
}
if($num==1)
{
header("Location: welcome.php");
exit();
}else{
header("Location:wrong.php");
}
mysqli_free_result($result);
mysqli_close();
}
?>
It is because you are sending output before issuing the redirect. You can't change the HTTP headers once you have started printing the body of the HTTP message.
// echo "Login Successful"; // remove this line and all other HTML
header("Location: welcome.php");
exit();
Basically you have to restructure the program so that when the form is submitted you are not sending output to the browser.
Example pseudo code:
if user has submitted the form then
authenticate user
if authentication is successful then
redirect user to welcome.php
else
show login page and error message
else
show login page
thought this might help on top of the real answer that robbmj provided
Create 3 folders...
Views
Models
Controllers
In the Views folder, create a php file called "Login.php"
Inside that php page paste your html form:
<!DOCTYPE html>
<head>
</head>
<body>
<div class="container">
<form class="form-signin" role="form" action="<?=$_SERVER['PHP_SELF']?>/Controllers/Login.php" method="POST">
<h2 class="form-signin-heading"><center>Bienvenido!</center></h2>
<input type="text" name="username" class="form-control" placeholder="Username" required="" autofocus="">
<input type="password" name="password" class="form-control" placeholder="Password" required="">
<div class="checkbox">
<label><input type="checkbox" value="remember-me"> Remember me </label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
</form>
</div>
</body>
</html>
Inside your Models folder, create a file called SQLDbContext.php
Inside that file place the code like so:
class SQLDbContext
{
public $link;
public function Connect()
{
$this->link = mysqli_connect( "localhost", "root", "root", "testdb")
or die ( "error" . mysqli_error( $enlace ) );
}
public function __Destruct()
{
mysql_free_result($result);
mysql_close();
}
}
Inside your Models folder, create a file called AuthenticationRepository.php
Inside that file, place the code like so:
require_once( "SqlDbContext.php" );
class AuthenticationRepository extends SQLDbContext
{
public function __Construct()
{
$this->Connect();
}
public function GetUsersByUsernameAndPassword( $username, $password )
{
$sql = "SELECT * FROM testdb.user WHERE username='$username' and password='$password'";
$result = mysqli_query( $this->link, $sql );
return $result;
}
}
Create a Login.php file inside Controllers (You'll notice I changed your action to /Controllers/Login.php in your Login view
Inside that php file, place your logic to login:
require_once( "../Models/AuthenticationRepository.php" );
$authenticationRepository = new AuthenticationRepository();
$username = $_POST[ "username" ];
$password = $_POST[ "password" ];
$usersInDb = $authenticationRepository->GetUsersByUsernameAndPassword( $username, $password );
$num = mysqli_num_rows( $usersInDb );
if( $num == 1 )
{
header("Location: Views/Welcome.php");
}
else
{
// Set a $_SESSION here and in the Views/Login.php check for that $_SESSION being set
header("Location: Views/Login.php");
}
NOTES:
- You will notice that nothing has been echo'd to the screen before a header(...) has been issued.
- You will notice that all logic has been divided up (wrongly but itll get you started).
- YOU STILL NEED TO DO SQL injection checks and validation etc, but i'll leave that for you to do buddy
By doing all of this, you avoid alot of the problems you have at the moment... There is so much you can do here to improve this code, In fact, the above code really isn't too hot either, but it's a step in the right direction... Seperate all of your stuff out... Check out http://www.laravel.com which is an MVC framework made to help you not screw things up too much :)

Categories