Validating using JQuery and processing by PHP - php

I want to validate my form using JQuery and use php to send it to my database.
This is what I've tried:
<body>
<form id="first_form" method="post" action="">
<div>
<label for="first_name">First Name:</label>
<input type="text" id="first_name" name="first_name"></input>
</div>
<div>
<label for="last_name">Last Name:</label>
<input type="text" id="last_name" name="last_name"></input>
</div>
<div>
<label for="handphone">Handphone:</label>
<input type="text" id="handphone" name="handphone"></input>
</div>
<div>
<input type="submit" value="Submit" />
</div>
</form>
<script>
$(document).ready(function() {
$('#first_form').submit(function(e) {
e.preventDefault();
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var handphone = $('#handphone').val();
$(".error").remove();
if (first_name.length < 1) {
$('#first_name').after('<span class="error">This field is required</span>');
return false;
}
if (last_name.length < 1) {
$('#last_name').after('<span class="error">This field is required</span>');
return false;
}
if (handphone.length < 1) {
$('#handphone').after('<span class="error">This field is required</span>');
return false;
}
});
});
</script>
<?php
$first_name = "<script>var first_name = $('#first_name').val();</script>";
$last_name = "<script>var first_name = $('#last_name').val();</script>";
$handphone = "<script>var first_name = $('#handphone').val();</script>";
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO vali (first_name, last_name, handphone)
VALUES (first_name, last_name, handphone)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
</body>
So as you can see, the first part is just the html and form.
The second part is where I used Jquery to validate (which works).
Now the issue is at the php part, where it sends the data to my database as empty.
The logic behind my php code is that, I take the values of the variables I set in Jquery and just update it to the database. But its updating empty values.
I tried to return false in Jquery, but its not working for me. May I know what am I doing wrong here?

Firsty, you have to understand JavaScript in this case is a client-scripting language and PHP is a server-scripting language. Variables can't be pass from JavaScript to PHP is the <script> tag.
Secondly, we have different types of requests; GET, POST, PUT, DELETE and so on. This we can check via PHP. A form can only send two types of request as at the time of me typing this answer, GET and POST request, this is the method value you set in your form. Every value set in a form can be accessed in the request global array and the name of the value being the key/indetifier. $_GET[] if you sent a get request and $_POST[] if you sent a post request.
In your form above, your method is set to POST, meaning all the values would be available in the global $_POST[].
When ever a page loads, the server script gets loaded first before the Client Side / HTML / CSS and other resources used by your document.
PHP has a function called isset() which is used to check if a variable available regardless it's value which is very useful for form validation.
If you ever have PHP codes in file performing logic/operations, it is advisable you placed them topmost of you file since it isn't used in rendering your document/view.
From your code, you should edit as
<?php
if(isset($_POST['submit'])){
// This block will only be executed when a submit button is triggered
//Make your connection here, it is not a must but good practice to always make connection first in order to make it available everywhere. Ensure to check if connection was successful or not.
$first_name = $_POST['first_name']; // this gives you the exact value you passed in the form.
...
// All you variables should be assigned using the above method
//in the above assignation of variables, we didn't sanitize. mysqli has a method real_escape_string() which does that for us. Ensure to always sanitize and properly validate inputs you send to your DB
//Sanitizing inputs
$first_name = $con ->real_escape_string($first_name);
// Do the above for other inputs, then you are good to perform an insert.
$result = $conn->query($sql);
if($result){
//Record has been inserted, you can choose to redirect or do some other logic
}else{
//Record was not successfully inserted. Print your error if in development to get an insight to what went wrong
}
}
$conn->close()
?>

Related

PHP variable wont show in form input field

I'm trying to select a PHP variable from a database insert it into an html form input. I guess my question is how do you store the query into a variable and then call that variable in an html form? Also, the form is located on a separate page from the form action file. Why is it undefined if it's defined in the PHP file? The desired output is when I load the html page the value from the database for nickname auto-fills that field of the form.
error:
Notice: Undefined variable: Nickname in C:\xampp\htdocs\Client-Projects\Crossfire\templates\CoinSubmission.html on line 45
CoinSubmission.html
<form autocomplete="off" action="AdminCoinSub_Code.php" method="POST">
<p>
<input type="text" name="Nickname" id="Nickname" value="<?php echo htmlspecialchars($Nickname); ?>" />
</p>
</form>
AdminCoinSub_Code.php
<?php {
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "administrator_logins";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO coin (ProfileID, Store, Position,
Nickname, ContactNumber, MachineCount, CutOffDate, Coins, location, LastSubmission, Rank)
VALUES (:ProfileID, :Store,:Position, :Nickname,:ContactNumber,:MachineCount,:CutOffDate, :Coins,:location,:LastSubmission,:Rank)");
$stmt->bindParam(':ProfileID', $_POST['ProfileID']);
$stmt->bindParam(':Store', $_POST['Store']);
$stmt->bindParam(':Position', $_POST['Position']);
$stmt->bindParam(':Nickname', $_POST['Nickname']);
$stmt->bindParam(':ContactNumber', $_POST['ContactNumber']);
$stmt->bindParam(':MachineCount', $_POST['MachineCount']);
$stmt->bindParam(':CutOffDate', $_POST['CutOffDate']);
$stmt->bindParam(':Coins', $_POST['Coins']);
$stmt->bindParam(':location', $_POST['location']);
$stmt->bindParam(':LastSubmission', $_POST['LastSubmission']);
$stmt->bindParam(':Rank', $_POST['Rank']);
$stmt->execute();
echo "Success";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
}
$conn=mysqli_connect($servername,$username,$password,$dbname);
if (mysqli_connect_errno($conn))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT `Nickname` FROM `adminlogin` WHERE `ProfileID` = ':ProfileID'";
$Nickname = $conn->query($query); // This is where the query is executed
$fetcher = $Nickname->fetch_assoc();
while($row = mysqli_fetch_array($Nickname))
if (mysqli_num_rows($Nickname) > 0) {
echo 'User name exists in the table.';
} else {
echo 'User name does not exist in the table.';
}
?>
First of all, your html page should have the extension .php and not .html, that way it can interpret your php code inside the html file, don't worry this wont break the html.
why is it undefined if it's defined in the php file.
It's because each php script run separately unless you hook them together.
I would recommend yo read a bit more about how php works.
For this example to work i would do it it this way.
CoinSubmission.php
<?php //This goes at the top of the file
include_once('AdminCoinSub_Code.php') //If they are in the same dir else you will need to set the path properly.
?>
<form autocomplete="off" action="AdminCoinSub_Code.php" method="POST">
<p>
<input type="text" name="Nickname" id="Nickname" value="<?php echo
htmlspecialchars($Nickname); ?>">
</p>
</form>
The include at the top will "paste" your code of AdminCoinSub_Code in the CoinSubmission file and treat it as one file. So the variable will be accesible for it.
Note: My explanation is oversimplified, it ain't exactily how it works, but should get the gist of it.
Alaa Morad answer if also valid, but remember to change the .html to .php
Happy Coding :)
That's because $Nickname will not be set if Register Globals is off witch is a normal thing !
Register Globals has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0
so use $_POST
<input type="text" name="Nickname" id="Nickname" value="<?php echo htmlspecialchars($_POST['Nickname']); ?>">

User not being deleted on link click [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I have a users table and I want to be able to delete a user when a link is clicked. $user_name is set in a session. Here is the link:
<?php echo "Delete Account" ?>
Here is the code on delete_user.php:
<?php
session_start();
session_destroy();
require "connection.php";
?>
<?php
if($_GET['id'] != ""){
$user_name = $_GET['id'];
$sql = "DELETE FROM users WHERE user_name='{$user_name}'";
$result = mysqli_query($connection, $sql);
header('Location: register.php');
}
?>
<?php include "footer.php";?>
I don't understand why it's not deleting the user from the database when this code is executed?
There's no clear reason as to why your code is not working. However, you mentioned being new to PHP, so picking up good practices with your code could (1) help solve the issue at hand, (2) make your code more efficient, and easier to debug.
I recommend you use mysqli in the object-oriented manner, it requires less code, and usually easier to follow.
Making the connection is simple:
<?php
$host = 'localhost';
$user = 'USERNAME';
$pass = 'PASS';
$data = 'DATABASE';
$mysqli = new mysqli($host, $user, $pass, $data);
// catch errors for help in troubleshooting
if ($mysqli->errno)
{
echo 'Error: ' . $mysqli->connect_error;
exit;
}
?>
Creating a safe environment for your server keep in mind these things:
Do not trust user input (ever!)
Do not perform direct queries into your database.
When developing, break your code into steps so you can easily troubleshoot each part.
With those three simple things in mind, create a delete file.
<?php
if (isset($_GET['id'])
{
// never trust any user input
$id = urlencode($_GET['id']);
$table = 'users';
// set a LIMIT of 1 record for the query
$sql = "DELETE FROM " . $table . " WHERE user_name = ? LIMIT 1";
// to run your code create a prepared statement
if ($stmt = $mysqli->prepare( $sql ))
{
// create the bind param
$stmt->bind_param('s', $id);
$stmt->execute();
$message = array(
'is_error' => 'success',
'message' => 'Success: ' . $stmt->affected_rows . ' were updated.'
);
$stmt->close();
}
else
{
$message = array(
'is_error' => 'danger',
'message' => 'Error: There was a problem with your query'
);
}
}
else
{
echo 'No user id is set...';
}
The code will help you set the query, and delete the user based on their user_name... Which I am not sure that is the best solution, unless user_name is set to be an unique field on your MySQL database.
Firstly this is a horrible way to do this, you are prone to SQL Injections and also using GET literally just tags the query to the end of the URL which is easily obtainable by a potential hacker or ANY user as a matter of fact. Use POST instead with a bit of jQuery magic, I would also recommend using Ajax so that you don't get redirected to php file and it will just run. As it is not anyone can access that URL and delete users so I recommend using PHP SESSIONS so that only people from your site can delete users. Also simply passing the id to the PHP file is very insecure as ANYONE could simply create a link to your php file on their site and delete users.
Therefore try this to fix your code (with added security):
PLEASE NOTE: I am aware that this may not be the best way nor the worst but it is a fairly secure method that works well.
Your main page, index.php:
<?php
session_start();
// Create a new random CSRF token.
if (! isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = base64_encode(openssl_random_pseudo_bytes(32));
}
// Check a POST is valid.
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
// POST data is valid.
}
?>
...
<form id="delete_user_form" action="delete_user.php" method="post">
<input type="hidden" name="user_id" value="<?php echo $user_name; ?>" />
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>" />
<input type="submit" value="Delete User" />
</form>
In your .js file (make sure you have jQuery linked):
window.csrf = { csrf_token: $("input[name= csrf_token]").val() };
$.ajaxSetup({
data: window.csrf
});
$("#delete_user_form").submit(function(event) {
event.preventDefault(); //Stops the form from submitting
// CSRF token is now automatically merged in AJAX request data.
$.post('delete_user.php', { user_id: $("input[name=user_id]").val() }, function(data) {
//When it it's complete this is run
console.log(data); //With this you can create a success or error message element
});
});
Now for your delete_user.php file, this should fix the errors:
<?php
session_start();
require "connection.php";
// Checks if csrf_token is valid
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
if(isset($_POST['user_id']) && $_POST['user_id'] != ""){
$user_name = $_POST['user_id'];
$sql = "DELETE FROM users WHERE user_name = '$user_name' LIMIT 1"; //LIMIT 1 only allows 1 record to be deleted
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully"; //You get this in your javascript output data variable
} else {
echo "Error deleting record: " . $conn->error; //You get this in your javascript output data variable
}
$conn->close();
}
}
?>
I don't know what your connection.php contains so this is what I'd put in it:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

PHP Login code doesn't work, user stays stuck on the login page

I am new to PHP and can't find answers as to why the following code doesn't work. This should be easy, but I can't figure this out. This code produces no errors, and the SQL statement is correct in the phpAdmin SQL console. I've searched web & StackOverflow, but can't find a good answer. What's wrong?
ALL users (whether in the db or not) get ignored and stuck on login page.
<?php
session_start();
//create function to check login form for admin or other type of user.
//Redirect the admin user to the welcome page.
function login()
{
//strip login and password using in-build htmlspecialchars function
$value1 = htmlspecialchars($_POST['login']);
$value2 = htmlspecialchars($_POST['password']);
//set variables for the db connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
$loggedin = '';
//Create new connection to db
$conn = new mysqli($servername, $username, $password, $dbname);
//Check connection and handle any error
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
header('Locatin: login.php');
}
else {
//check if super admin user exists in db
$sql = "SELECT count(*) FROM admins WHERE AdminLevel = 1";
$result = mysqli_query($conn,$sql);
//check to see if query returns any rows
if(mysql_num_rows(($result) > 0) {
include 'welcome.php';
}
//check if the password and username match
if(($username === $value1) && ($password === $value2)) {
$_SESSION['loggedin'] = TRUE;
echo "Hello ".$value1.", you are logged in!<br>";
}
//send user error message if login/username and password wrong
else {
echo "Incorrect username or password<br>";
include 'login.php';
}
//close the db connection
$conn->close();
}
?>
Login Form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Admin Login</title>
<script>
//function to check the form
function chkForm()
{
//determine the number of elements in the user login form
var intFormLen = document.forms[0].elements.length;
//loop through the form fields to see that a value has been input
for (var i = 0; i < intFormLen; i++) {
if (document.forms[0].elements[i].value == "") {
//send user an error message if login field empty
document.getElementById(document.forms[0].elements[i].name).innerHTML="Required Field";
document.forms[0].elements[i].focus();
return false;
}
}
//clear the form fields
function clearWarn(fieldName)
{
document.getElementById(fieldName).innerHTML = "";
return true;
}
return;
}
</script>
</head>
<body>
<h2>Admin Login</h2>
<div class="phpEcho">
<div class="formLayout">
<form action="#" method="post" onsubmit="return chkForm();">
<label for="login">Login:</label>
<input type="text"name="login" onchange="return clearWarn('fieldName')">
<div id="login" style="color:red"></div><br>
<label for="password">Password:</label>
<input type="password" name="password" onchange="return clearWarn('fieldName')">
<div id="password" style="color:red"></div><br><br>
<input type="submit" name="cmdSubmit" value="Log in">
</form>
</div>
</div>
</body>
</html>
You set your form action="#" and don't submit it in JavaScript.
As noted by Jason, chkForm() will never return true, which would also prevent the form from submitting.
This script has a lot of issues that should be addressed. I will go over a couple things that may help you:
1) I would suggest using some kind of config / bootstrap file to include in your documents that contains reusable elements and start session. Require/include only once.
/config.php
define("_DS_",DIRECTORY_SEPARATOR);
define("DBUSER",'root');
define("DBPASS",'');
define("DBHOST",'localhost');
define("DBDATABASE",'mydb');
// Start session
session_start();
2) You will want to separate out your functions, importantly your database connection, whether by class or by function. You want to keep tasks separate so it's easy to reuse.
Here is an example (I am going to use PDO because I am more familiar with it but principle is the same):
/functions/connection.php
function connection()
{
// This is just a really basic connection, one could expand on this
return new PDO('mysql:host='.DBHOST.';dbname='.DBDATABASE, DBUSER, DBPASS);
}
/functions/login.php
/*
** #param $username [string] by making this a param, you can manually log in users outside of POST
** #param $password [string] same as username
** #param $conn [resource] You will want to inject your connection into this
** in order to use it. Don't make the connection
** inside. May as well reuse resources already active
** #return [bool] If you return TRUE or FALSE, that will tell your script
** whether the login succeeded or failed for notification
*/
function login($username,$password,$conn)
{
// Don't worry about stripping down the username/pass, just bind
// the username and match the password
// You need to select from your user table (or whatever table
// you are storing your usernames for your site)
$query = $conn->prepare("select * from `users` where `username` = :0");
$query->execute(array(':0'=>$username));
$result = $query->fetch(PDO::FETCH_ASSOC);
if(empty($result))
return false;
// You will want to use password_hash to save passwords
if(!password_verify($password,$result['password']))
return false;
// I use htmlspecialchars here so I don't forget when echoing to page
// but you can do it at the time you echo to browser
$_SESSION['first_name'] = htmlspecialchars($result['first_name']);
//etc....
return true;
}
To use:
/index.php
// Include our soon-to-be-used files
require_once(__DIR__._DS_.'config.php');
require_once(__DIR__._DS_.'functions'. _DS_.'connection.php');
require_once(__DIR__._DS_.'functions'. _DS_.'login.php');
// Set connection
$con = connection();
// See if a post has been made
if(isset($_POST['login'])) {
$loggedin = login($_POST['login'],$_POST['password'],$con);
}
// If the login attempt made
if(isset($loggedin)) {
// If successful
if($loggedin) {
header('Location: welcome.php');
exit;
}
else
// If failed, you can note in a variable an echo in the html section
$error = 'Login failed';
}
For the client-side validation, I would suggest jQuery Validate, it's easy and works very well.

Login with PHP doesn´t show any html code

I´ve a problem a login, the page doesn´t show anything. This is the code:
PHP:
<?php
require 'connect_db.php';
/* start the session */
session_start();
conectar();
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "SELECT * FROM teachers WHERE email='$email' and password='$password'";
$result = mysql_query($sql);
// counting table row
$count = mysql_num_rows($result);
if($count == 1)
{
$_SESSION['loggedin'] = true;
$_SESSION['email'] = $email;
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + (10 * 60) ;
echo "<body><p>Welcome! </p></body>";
}
else
{
echo "Mail or password not correct.";
echo "<a href='teacher.html'>Try again</a>";
}
//$conexion->close();
?>
The HTML calling this code is:
<form action= "php/login_profesores.php" method="POST" onsubmit="return validacion()">
<label>Mail</label>
<input type="text" class="" id="inputMail"></input></br></br>
<label>DNI</label>
<input type="password" id="inputDNI"></input></br>
<input name="Enviar" type="submit" class="submit" value="Send" /></input></br>
</form>
validación() is the javascript code what works, but the problem is that php doesn´t show any page when the user logins in the system. The DB is well-configured and teacher´s table exists.
connect_db
<?php
function conectar()
{
define('DB_SERVER','http://**/');
define('DB_NAME','**');
define('DB_USER','**');
define('DB_PASS','**');
$conexion=new mysqli();
$conexion->connect('DB_SERVER','DB_USER','DB_PASS', 'DB_NAME');
$error=$conexion->connect_error; //Tambien vale connect_error
echo $error;
}
?>
You must have name attribute in your input fields if you want to pass the value using POST, GET or any other method.
<input type="text" class="" name="email" id="inputMail"></input></br></br>
<label>DNI</label>
<input type="password" name="password" id="inputDNI"></input></br>
In the form you are specifing input types but you are not specifying names for that.
You are using MySQL_ procedural in your PHP page but you're using MySQLi_ Object Orientated in your connection page.
Update everything to MySQLi (object orientated). MySQL_ is now deprecated and no longer supported and should not be used.
You should also check with your SQL that it allows access from the IP address your page is trying to access it from. If they are on the same server then you should replace your SQL database connection address with localhost .
Thanks, it works! I had to write the name of server without http:// and I had another problem mixing mysql and mysqli because it is not correct.

problem with form to send entry to mysql database in php

I have three files working on an login app to learn PHP.
This is the connection with DB
<?php
# Connecting database below
$connection = mysqli_connect('localhost','root','','loginapp');
if ($connection) {
# code...
echo "connected";
}
else{
echo "Errorr";
die("Database");
}?>
and here is the html code for the web view
<html>
<head>
<title>Form</title>
</head>
<body>
<h1>Welcome to My Form</h1>
<form class="" action="login_create.php" method="post">
<input type="text" name="name" placeholder="Enter your name here"><br>
<input type="password" name="password" placeholder="Enter Password" value=""><br>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
and here is the file where things are going wrong, its not checking the conditions of entries and not putting the data into database what's wrong going there? help please
sometimes it gives
error that "unknown 'sbumit' in the $_POST" and sometimes it don't
doesn't even show any error
but doesn't even do anything
<?php
include "db.php";
if (isset($_POST['submit'])) {
$username = $_POST['name'];
$password = $_POST['password'];
if (isset($username) && isset($password)) {
if (strlen($username) > 10 && strlen($username) < 3) {
echo "Must enter username & pass between 3 & 10";
echo "So that we can forward your request";
}
else {
$query = "INSERT INTO users (username,password) VALUES ('$username','$password')";
$result = mysqli_query($connection,$query);
if(!$result)
{
die('Sorry Query faild'.mysqli_error());
}
}
}
else
{
echo "You haven't wrote anything, write it first";
}
}?>
Habib,
Some guidance for PHP :
$button = isset($_POST["submit"])?$_POST["submit"]:"";
What this line does is apply a value to the $button variable, the first check is that IF isset($var) THEN (indicated with the ? ) apply the value of $var to the $button variable.
The colon : then sets that if the boolean query (true/false) of the IF returns false, then apply the second value instead, in this case an empty string of "".
This is code minimalisation and you should be aware of it but there is little need to use it, especially while learning.
Feedback on your code:
mysqli_error($connection); Your error feedback for MySQLi should include the connection details, as shown here.
replace the $username = $_POST['name'];
$password = $_POST['password'];
if (isset($username) && isset($password)) {
because you want to check not if they're set but if they're not empty, currently they will be set as they're set to the values of $_POST even if they are null (potentially), so replace with:
if(!empty($username) && !empty($password)){
Also note that ! is the negative operator. so above is IF NOT EMPTY.
if (strlen($username) > 10 && strlen($username) < 3) { this is impossible to reach because you're setting if string is longer then 10 AND string is shorter than 3, this is clearly impossible. replace the && with || which is OR rather than AND .
Personally I think that isset($_POST['submit']) is not the best way, instead checking that if($_POST['submit'] == 'submit') confirms the submission of this form from this submit button (the value is the value set in your HTML form).
$query = "INSERT INTO users (username,password) VALUES ('$username','$password')"; This works fine, BUT you really, really need to do some research into SQL injection attacks and SQL security. read How can I prevent SQL injection in PHP? as a start. This is very important to learn at the start of your PHP MySQL learning.
Also research into PDO database connectivity.
Also be aware that your script will not output anything when you have a successful saving of username/password to the database.
As a closer:
Fnally, set up error logging on your page, to give you useful feedback on errors and problems: error_reporting(E_ALL);
ini_set('display_errors', 1); at the very top of your page. Also see How do I get PHP errors to display?
Change your code as follow.
<?php
include "db.php";
$button = isset($_POST["submit"])?$_POST["submit"]:"";
$username = isset($_POST["name"])?$_POST["name"]:"";
$password = isset($_POST["password "])?$_POST["password "]:"";
/*Commetents*/
$button =isset($_POST["submit"])?$_POST["submit"]:"";
is similar to following code:
if(isset($_POST["submit"]))
{
$button = $_POST["submit"];
}
else
{
$button = $_POST["submit"];
}
You know in Php 5.4 , it will present error,if you do not set any value to variable . that is why we used it. If it doesn't get any value it will set it value "".
if($button == "submit") means when someone will press the button submit then $_POST['submit'] value will be submit which you define in the submit button value.
if($button == "submit")
{
if($username=="" or $password=="")
{
$error ="Username & Password can't be blank";
}
elseif(strlen($username)<3 or strlen($username) > 10 )
{
$error ="Must enter username & pass between 3 & 10";
}
else
{
$query = "INSERT INTO users (username,password) VALUES('$username','$password')";
mysqli_query($connection,$query) or die(mysqli_error());
}
}
echo $error;
Hope it will help you .

Categories