So I'm trying to input some session variables into the database, and I'm successfuly inserting all rows, except the $_SESSION['organisationId']. Some context: A user lands on a url as the one given in the snippit below, I get the organisationId, then want that user to be assigned that organisationId when they create the account - working as a sort of 'invite-system' of sorts.
// This is the URL I am using: http://thisapp.com/login.php?competitionId=51da7ed4d686a&organisationId=51d81cab92709
<?php
session_start();
ob_start();
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
include('db.php');
$_SESSION['competitionId'] = $_GET['competitionId'];
$_SESSION['organisationId'] = $_GET['organisationId'];
<h4>Create your Account</h4>
<form action="login.php" method="post" name="acceptinvite">
name: <input type="text" name="createname"><br>
email: <input type="text" name="createemail"><br>
password: <input type="password" name="createpassword"><br>
<input type="submit" value="Create Account">
</form>
<?php
if (isset($_POST["createname"]) && !empty($_POST["createname"])) {
//define variables
$name = mysql_real_escape_string($_POST['createname']);
$email = mysql_real_escape_string($_POST['createemail']);
$password = mysql_real_escape_string($_POST['createpassword']);
$teamLeader = 0;
$organisationId = mysql_real_escape_string($_SESSION['organisationId']);
$orgName = mysql_real_escape_string($_SESSION['orgName']);
//finish registering the user
$acceptInviteTeam = ("INSERT INTO `users` (`organisationId`, `name`, `email`, `password`, `isTeamLeader`) VALUES ('$organisationId', '$name', '$email', '$password', '$teamLeader')");
$result = mysql_query($acceptInviteTeam) or die (mysql_error());
}
else {
echo "Fill out the form and use the correct credentials";
}
?>
Here's what the problem is.
When you enter the link http://thisapp.com/login.php?competitionId=51da7ed4d686a&organisationId=51d81cab92709 you have organisationId and you save it in the session. But the target of the form is simply login.php. when you submit the form, there is no organisationId in the url, so the session variable gets overwritten by null.
This is the fix:
$_SESSION['competitionId'] = isset($_GET['competitionId']) ? $_GET['competitionId'] : $_SESSION['competitionId'];
$_SESSION['organisationId'] = isset($_GET['organisationId']) ? $_GET['organisationId'] : $_SESSION['organisationId'];
Alternatively you can use an if statement.
Related
Newcomer to php here! I have two HTML forms that looks like this:
<form action="../includes/signup.php" method="post" enctype="multipart/form-data">
<!--inputs + submit button-->
</form>
<form action="../includes/login.php" method="post">
<!--inputs + submit button-->
</form>
I am certain that the form action is correct as well as the content inside the PHP files themselves. However, whenever the inputs are submitted, the user is redirected to the PHP files themselves instead of the appropriate header(Location: "url"). So essentially, instead of going to the welcome.php page on a successful registration, the user is instead redirected to signup.php.
Basically, how can I make it so that the code inside the PHP file is executed and that user isn't redirected to the PHP files themselves?
Below is my PHP code:
<?php
session_start();
$_SESSION['message'] = '';
$mysqli = new mysqli('localhost', 'root', 'root', 'personalproject');
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
//if email is taken
if (mysql_num_rows($query) == 0){
//password confirmation
if($_POST['password'] == $_POST['confirmpassword']) {
$name = $mysqli->real_escape_string($_POST['name']);
$email = $mysqli->real_escape_string($_POST['email']);
$class = $mysqli->real_escape_string($_POST['class']);
$password = $_POST['password'];
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
$query = mysql_query("SELECT email FROM users WHERE email=$email", $mysqli);
$sql ="INSERT INTO users (name, email, class, password)"
."VALUES ('$name', '$email', '$class', '$hashedPwd')";
//redirect if successful
if ($mysqli->query($sql) === true){
$_SESSION['message'] = "You are in, $name!";
header("Location: welcome.php");
}else{
$_SESSION['message'] = "Whoops. An error occurred, you could not be added to the database. Try again.";
}
}else{
$_SESSION['message'] = "Your passwords do not match!";
}
}else{
$_SESSION['message'] = "An account has already been made with that email!";
}
}
?>
Here is a very simple form validation structure you will have to apply this to your code.
PHP should check for the submit process, then validate form, then set a header to redirect.
<?php
if(isset($_POST['submit'])){//if submit is clicked.
if ($_POST['inputA'] == ''){echo "Cannot be Empty";}//the input to check is empty.
else{header("Location: anotherPage.php");} //redirect to your page.
}
?>
Your form should be like this.
<form method="post">
<input type="text" name="inputA">
<input type="submit" name="submit">
</form>
I am using this script for my login system in php, while am handling the session values it is not working
Case is when am not validating the session values in the test page which are passed from index page the login is valid and goes to the test page after successful login but when am using the session values to validate in the test page the login is not successful, after entering the credentials the page does not goes to test.php it stays only on index.php
Can i know what is the mistake i have done ? Thanks in advance
Login Page
<?php
require 'connection.php';
error_reporting(0);
$employee_id = $connection->real_escape_string($_POST['EMPLOYEE_ID']);
$password = $connection->real_escape_string($_POST['PASSWORD']);
$sql = "SELECT EMPLOYEE_ID,EMP_NAME,DESG FROM EMPLOYEELOGIN WHERE EMPLOYEE_ID='" . $employee_id . "' AND PASSWORD='" . $password . "'";
$result = $connection->query($sql);
session_start();
if ($result->num_rows == 1) {
$row = $result->fetch_row();
// print_r($row);
$_SESSION['EMPLOYEE_ID'] = $row[0];
$_SESSION['EMPNAME'] = $row[1];
$_SESSION['DESG'] = $row[2];
header('Location: test.php');
}
?>
// The form used
<form role="form" method="post" action='index.php' class="m-t-20">
<input class="form-control" type="text" name="EMPLOYEE_ID" required="" placeholder="Username">
<input class="form-control" type="password" name="PASSWORD" required="" placeholder="Password">
<input type="submit" class="btn btn-primary" name="submit" value="Login">
</form>
Test Page
<?php
session_start();
// error_reporting(0);
if (isset($_SESSION['EMPLOYEE_ID'])) {
if ($_SESSION['EMP_NAME'] != 1) {
header("Location: index.php");
} else {
require 'connection.php';
}
} else {
header("Location: index.php");
}
?>
connection.php
<?php
$connection = new mysqli("localhost","root","123","testdatabase");
if($connection->connect_error){
die("Connection Failed<br>".$connection->connect_error);
}
?>
Updated Answer based on new connection.php code::
You do not appear to have a mysqli class included in the code anywhere so your attempt to instantiate will fail, you should be getting a white page or an error of some sort depending on your php.ini configurations. In any of the code I assume you do not have that class. If thats the case you need to convert your code over to use mysqli_ functions directly or create/install a mysqli class. Direct functions you would use like this:
$conn = mysqli_connect // etc...
-------------- Previous Answer --------------
PASSWORD is a reserved word in mysql
PASSWORD=
Should be (note the backticks)
`PASSWORD`=
Or better yet, change the name of the column to something like user_password, pass or anything you want.
I believe that will solve the problem.
There is a full list of reserved words for mysql available here:
Mysql Keywords/Reserved Words List
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.
So I'm attempting to create an html form that posts data to a database full of customers in MySQL using PHP, but am very new to PHP.
Currently, I'm getting a 404 whenever I try to submit everything with the submit button "The requested URL /bankyprinting/post was not found on this server." The data is also not injected into the MySQL database, but I'm not getting any other errors indicating that the connection to the database wasn't made.
The applications I'm attempting to write/use are:
customers.html
<html>
<head>
</head>
<body>
<form method = "post" action = "customers.php" id="customers">
First Name:
<input type = "text" name = "FirstName"/><br>
LastName:
<input type = "text" name = "LastName"/><br>
Company:
<input type = "text" name = "Company"/><br>
Position:
<input type = "text" name = "Position"/><br>
Address:
<input type = "text" name = "Address"/><br>
Phone Number:
<input type = "text" name = "PhoneNumber"/><br>
Cell Number:
<input type = "text" name = "CellNumber"/><br>
Alternate Number:
<input type = "text" name = "AlternateNumber"/><br>
E-Mail:
<input type = "text" name = "EMail"/><br>
<input type = "submit" name="submit" value = "submit"/><br>
</form>
</body>
<footer>
</footer>
</html>
index.html
</html>
<head>
</head>
<body>
New Customer
</body>
<footer>
</footer>
</html>
connect.php
<?php
$host="localhost";
$port=3306;
$socket="/tmp/mysql.sock";
$user="root";
$password="";
$dbname="bankyprinting";
$con = mysqli_connect($host, $user, $password, $dbname, $port, $socket)
or die ('Could not connect to the database server' . mysqli_connect_error());
//$con->close();
?>
and
customers.php
<?php
/*Needs the connection object created in the connect.php file to work*/
header("LOCATION:customers.html");
require('connect.php');
/*require('customers.html');*/
/*Data from the html form is on the right. The objects that will be composed of that data is on the left.*/
if(isset($_POST['submit'])) {
$Company = mysqli_real_escape_string($con, $_POST['Company']);
echo 'Company';
$Position = mysqli_real_escape_string($con, $_POST['Position']);
echo 'Position';
$FirstName= mysqli_real_escape_string($con, $_POST['FirstName']);
echo 'FirstName';
$LastName = mysqli_real_escape_string($con, $_POST['LastName']);
echo 'LastName';
$Address = mysqli_real_escape_string($con, $_POST['Address']);
echo 'Address';
$PhoneNumber = mysqli_real_escape_string($con, $_POST['PhoneNumber']);
echo 'PhoneNumber';
$CellNumber = mysqli_real_escape_string($con, $_POST['CellNumber']);
echo 'CellNumber';
$AlternateNumber = mysqli_real_escape_string($con, $_POST['AlternateNumber']);
echo 'AlternateNumber';
$EMail = mysqli_real_escape_string($con, $_POST['Email']);
echo 'EMail';
$sql = "INSERT INTO tblcustomers (Company, Position, FirstName, LastName, Address, PhoneNumber, CellNumber, AlternateNumber, EMail)
VALUES ('$Customer', '$Position', '$FirstName', '$LastName', '$Address', '$PhoneNumber', '$CellNumber', '$AlternateNumber', '$EMail')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
}
else {
echo "Error: " . $sql . "<br>" . $con->error;
}
$con->close();
}
?>
I've got all of these stored on a folder hosted by a WAMP server- and yes I already know that the html forms are not secured- but that's outside the scope of my problem right now ><.
I don't know exactly why I'm getting the PHP error (POST error?) and am not sure how to address that by getting the form to inject into the database properly.
These files should be in the same folder.
You are not using apostrophe (') for binding variables to your query.
$sql = "INSERT INTO tblcustomers (Company, Position, FirstName, LastName, Address, PhoneNumber, CellNumber, AlternateNumber, EMail)
VALUES ('$Customer', '$Position', '$FirstName', '$LastName', '$Address', '$PhoneNumber', '$CellNumber', '$AlternateNumber', '$EMail')";
You should use *_real_escape_string to prevent some SQL injections.
$Company = mysqli_real_escape_string($con, $_POST['Company']);
Remove your included customers.php in your bankyprinting.html and just let it submit to your customers.php file as instructed in your form's action tag. And you have two action tags in your form, where one should be method tag.
<form method = "post" action = "customers.php" id="customers">
And for your if(isset($_POST["submit"])) condition, in order for it to recognize the submitted form, you should add a name tag for your submit button.
<input type = "submit" name="submit" value = "submit"/>
Why do you have a semi-colon after your closing bracket? Remove it.
}; /* AND TURN IT TO */ }
And also take a look at prepared statement.
It's all in the error message:
<form action = "post" action = "customers.php" id="customers">
should be
<form method= "post" action = "customers.php" id="customers">
The server is looking for a file called post, which it cannot find.
EDIT: Also,
If you have changed the contents of the html file, and you have not configured the cache settings of the Apache server, you might be looking at the old html file instead of the new one with the changes (see mod_expires). You will need to clear your browser's cache, or load the page with CTRL+SHIFT+R in order to get the new html file to be accessed. This happened to me when I was working on webpages a lot.
I'm working on PHP at the moment.
I have a form seen below with a submit button.
I then created a function below also.
As you can see the first thing the function does is checked the submit button is pressed, but it goes into this if upon loading the page(i don't need to press the button), and it out puts the "Entry Submitted" p tag autmoatically, where it shouldn't even be entering the first if statement.
Any help appreciated,
<p>
<input type="submit" name="Submit" id="Submit" value="Submit" tabindex="100"/>
<br />`enter code here`
</p>
</form>
<?php
if (isset($_POST['Submit'])){
$conn_error = 'Could not connect.';
$mysql_host = 'localhost';
$mysql_user = 'auser';
$mysql_pass = 'auser';
$mysql_db = 'ourwebdb';
// Connect to database
if (!#mysql_connect($mysql_host, $mysql_user, $mysql_pass) || !#mysql_select_db($mysql_db)) {
die ($conn_error);
}else {
//echo 'Connected';
// Perform database insert
$name = $_POST["Name"];
$email = $_POST["email"];
$teamSupported = $_POST["radioGroup"];
$comment = $_POST["comment"];
$query = "INSERT INTO visitors (Name, Email,[Supported Team], Comment)
VALUES ('{$name}', '{$email}', '{$teamSupported}', '{$comment}')";
$result = mysql_query($query);
if ($result) {
// Success
$id = mysql_insert_id();
echo '<p> Entry Submitted</p>';
// Do something
} else {
die ("Database query failed. ". mysql_error());
}
}
}
mysql_close();
Change your 1st PHP line
if (isset($_POST['Submit'])){
to
if (isset($_POST['Submit']) && $_POST['Submit']=='Submit' ){
there is nothing wrong in your code (except cut out portion of form). so there is two possible scenario 1. you are refreshing browser url with re-submit 2. there are some onload javascript/jquery function which submit the page (form.submit()..)
Solution for 1. is easy just open the url in new tab. for scenario 2. you need to check Or submit your full code here