Variable not passing in POST method to same page - php

It seems that variables are not being passed to same page using POST method... I'm a beginner in html,php...
Please help...
table-name = member
attribute = name
<?php
include 'connection.php';
if(isset($_POST['submit'])) {
$name = $_POST{'name'};
$query = "INSERT INTO member (`name`) VALUES ('$name')";
mysqli_query($conn, $query);
header('Location: register.php');
}
?>
<form class="form-horizontal" action="register.php" method="post" id="input">
<div class="form-group">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="name" value="" />
</div>
</div><br>
<input type="submit" name="submit" form="input" class="btn btn-primary" value="Register" />
</form>

<?php
/* $_POST is super global array you can check weather you are getting data from post or not by using below line of code and use square brakets for array
instead of { } */
echo '<pre>';
print_r($_POST);
echo '</pre>';
include 'connection.php';
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$query = "INSERT INTO member (`name`) VALUES ('$name')";
mysqli_query($conn, $query);
header('Location: register.php');
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="register.php" class="form-horizontal" id="input" method=
"post" name="input">
<div class="form-group">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input class="form-control" name="name" type="text" value="">
</div>
</div><br>
<input class="btn btn-primary" form="input" name="submit" type="submit"
value="Register">
</form>
</body>
</html>

First of all try by change third line
$name = $_POST{'name'};
to
$name = $_POST['name'];
Because in post we need to use square braces...
and if you are posting to same page then empty action attribute value, bcz empty action attribute means form will post to same page...
so form element will be as below...
<form class="form-horizontal" action="" method="post" id="input">
Let me know if it help or not...

Please Try this :
$name = $_POST{'name'}; to $name = $_POST['name'];
and
Remove form action : action="register.php" to action=""

use this code instead of your code..
<form class="form-horizontal" action="" method="post" id="input">
<div class="form-group">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="name" value="" />
</div>
</div><br>
<input type="submit" name="submit" class="btn btn-primary" value="Register" />
</form>
Replace This Code With Your Existing Code

<?php
include 'connection.php';
if(isset($_POST['name'])) {
$name = $_POST['name'];
$query = "INSERT INTO member(name) VALUES ('".$name."')";
mysqli_query($conn, $query);
}
?>
<form class="form-horizontal" action="register.php" method="post" id="input">
<div class="form-group">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="name" value="" />
</div>
</div><br>
<input type="submit" name="submit" form="input" class="btn btn-primary" value="Register" />
</form>
Also,
Please confirm $conn is not false

If your HTML code and PHP code both on same page then set form action=''
<form class="form-horizontal" action="" method="post" id="input">
Always check mysqli_error() and mysqli_connect_errno() in your query code.
also use exit; after header("Location: YOUR_URL");
Your PHP code should be as below:-
include 'connection.php';
if ( isset( $_POST['submit'] ) ) {
// You have wrongly used bracket. Use [] bracket instead of {}
$name = $_POST['name'];
/* check connection */
if ( mysqli_connect_errno() ) {
printf( "Connect failed: %s\n", mysqli_connect_error() );
exit();
}
$query = "INSERT INTO member(`name`) VALUES('$name')";
// Check your query successfully executed or not
$result = mysqli_query( $conn, $query ) or die( mysqli_error( $conn ) );
header( 'Location: register.php' ); /* Redirect browser */
exit; // Write exit after header
/* Make sure that code below does not get executed when redirect. */
}
Hope it will help you :)

Change
if(isset($_POST['submit']))
to
if(isset($_POST['name']))

Related

Why is the header not working in this code?

The php code to get to the header after executing the queries
<?php
if (isset($_POST['Submit1'])) {
$con = mysqli_connect("localhost:3306", "root", "", "travels");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$fname1 = $_POST['fname'];
$lname1 = $_POST['lname'];
$pnum1 = $_POST['pnum'];
$email1 = $_POST['email'];
$fcode = $_POST['fcode'];
$sql = "insert into customer_info(fname,lname,pnumber,email) values ('$fname1','$lname1','$pnum1','$email1')";
$sql1 = "insert into booking_info(fname,lname,pnumber,email,f_code) values ('$fname1','$lname1','$pnum1','$email1','$fcode')";
$sql2 = "update flight_info set seats_available=seats_available-1 where flight_code='$fcode'";
mysqli_query($con, $sql);
mysqli_query($con, $sql1);
mysqli_query($con, $sql2);
header("Location: Booking_confirm.php");
}
?>
HTML CODE
<div class="container mt-5">
<div class="row">
<div class="col-md-6">
<form action="Booking.php" method="POST">
<div class="form-group">
<label for="fname">First Name: </label>
<input type="text" name="fname" class="form-control" id="fname"/>
</div>
<div class="form-group">
<label for="lname">Last Name: </label>
<input type="text" name="lname" class="form-control" id="lname"/>
</div>
<div class="form-group">
<label for="pnum">Phone Number: </label>
<input type="text" name="pnum" class="form-control" id="pnum"/>
</div>
<div class="form-group">
<label for="email">Email-Address: </label>
<input type="text" name="email" class="form-control" id="email"/>
</div>
<div class="form-group">
<label for="flight">Flight No: </label>
<input type="text" name="fcode" class="form-control" id="fcode"/>
</div>
<form action="Booking_confirm.php" method="POST" target="_blank">
<button type="Submit" name="Submit1" class="btn btn-primary">Book</button>
</form>
</form>
</div>
This is how my code looks. for some reason my header is not working and i am not able to find out why.
Help would be appreciated.
I have tried every possible change to get the header to work but of no use
You have two nested forms, your first form action="Booking.php" contains all fields while the second, nested form action="Booking_confirm.php", only contains the submit button an NO fields.
Replace
<form action="Booking_confirm.php" method="POST" target="_blank">
<button type="Submit" name="Submit1" class="btn btn-primary">Book</button>
</form>
with
<button type="Submit" name="Submit1" class="btn btn-primary">Book</button>
When clicking submit there is no $_POST['fname'], $_POST['lname'] etc.
Edit: you also might need to replace
<form action="Booking.php" method="POST">
with
<form action="Booking_confirm.php" method="POST" target="_blank">
depending on where your "header"/code is placed
Make sure there is not white space or html tags or any output, before the header() function...
upload the entire code, structure so we can help you find the solution

Selecting data from mysql database from a search form

I am new at this and still learning. I have a search page and want to use the input to search a mysql table and display results in a form to update the record back into the table.
Every time I try and run it I get a PHP Notice: Undefined variable: password in /var/www/html/update.php on line 106, referer: http://172.20.10.161/search.php
in the error_log.
All help would be most appreciated.
I have google and tried various methods to get this right, i feel there is some little thing I am missing here.
Below is the code from my search.php page
<?php
session_start();
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
header("location: login.php");
exit;
}
?>
<form action="update.php" method="post">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" value="">
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Search">
</div>
</form>
Then on my page that should show the results if have the following.
update.php
top of page
<?php
session_start();
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
header("location: login.php");
exit;
}
?>
Code in page to run query
<?php
require_once "include/dbconf.php";
if(isset($_POST['Search']))
{
$name=$_POST['name'];
$sql = "SELECT (name, surname, email, username, password) from net_users WHERE name LIKE '%".$name."%'";
$result = mysqli_query($link, $sql) or die ('Something went wrong');
while($row=mysqli_fetch_array($result))
{
$username =$row['username'];
$password =$row['password'];
$name =$row['name'];
$surname =$row['surname'];
$email =$row['email'];
}
}
mysqli_close($link);
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" value="<?php echo $name; ?>">
</div>
<div class="form-group">
<label>Surname</label>
<input type="text" name="surname" class="form-control" value="<?php echo $surname; ?>">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" value="<?php echo $email; ?>">
</div>
<div class="form-group">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
</div>
<div class="form-group">
<label>Password</label>
<input type="text" name="password" class="form-control" value="<?php echo $password; ?>">
/div>
<div class="form-group">
<input type="update" class="btn btn-primary" value="update">
</div>
</form>
I am hoping to pull the desired input on search $name to search the mysql db and return the results in the form on the update page to update the information back into the database.
I would recommend a couple of changes to update.php.
<?php
session_start();
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
// Can everyone logged in update the system. If not, filter it as required
header("location: login.php");
exit;
}
?>
Given the following connection file dbconf.php with a procedual MySQLi - https://www.php.net/manual/en/mysqli.quickstart.dual-interface.php
<?php
/*
Database credentials.
Assuming you are running MySQL server with default setting (user 'root' with no password)
*/
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'xxxxxxxx');
define('DB_PASSWORD', '**********');
define('DB_NAME', 'users');
/* Attempt to connect to MySQL database */
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check connection
if($link === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
The search query will need to account for SQL Injection - How can I prevent SQL injection in PHP?.
<?php
require_once "include/dbconf.php";
// placeholder for the returned data
$data = array();
// Verify the search query is present
// Or handle empty
if(isset($_POST['name']))
{
// SQL injection - https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php
$name=$_POST['name'];
// TODO: Verify that you need the password here
// Generally passwords are not to be stored as plain text
$sql = "SELECT (id, name, surname, email, username, password) from net_users WHERE name LIKE '?'";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($stmt, 's', $name);
// Execute the query
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
// Copy the result to a local array
// Each entry in $data will be an associative array of values
$data[] = $row;
}
} else {
// TODO : Handle this more gracefully
die('Search query missing');
}
mysqli_close($link);
if (empty($data))
{
// TODO: No records matched, handle gracefully
die('No records matched');
}
?>
Once you have the data, output as needed. Note that I have also selected id column - As all other fields are updateable, it would not be possible to identify the record if all the fields are changed. To work around this, you need a value that will always identify the record being updated. I have chosen the id column, but any other unique - non-updateable field would do.
<?php
foreach($data as $record)
{
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<input type="hidden" name="id" value="<?php echo $record['id']; ?>" />
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" value="<?php echo $record['name']; ?>">
</div>
<div class="form-group">
<label>Surname</label>
<input type="text" name="surname" class="form-control" value="<?php echo $record['surname']; ?>">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" value="<?php echo $record['email']; ?>">
</div>
<div class="form-group">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $record['username']; ?>">
</div>
<div class="form-group">
<label>Password</label>
<input type="text" name="password" class="form-control" value="<?php echo $record['password']; ?>">
/div>
<div class="form-group">
<input type="update" class="btn btn-primary" value="update">
</div>
</form>
<?php
}
?>

PHP, using $_FILES and $_POST at the same time but its not working

I am making a admin page to insert all attribute in MySQL and image upload in one folder but getting some error ,Here is code of form
<form role="form" id="form1" action="" enctype="application/x-www-form-urlencoded" method="post">
<div class="col-lg-6">
<div class="form-group">
<label>Title:</label>
<input type="text" name="title" placeholder="enter title" class="form-control"required>
</div>
<div class="form-group">
<div class="col-lg-6 col-md-6 col-sm-6">
<label>Image:</label>
<input type="file" name="upload" id="postimage" class="form-control">
</div>
</div>
<input type="reset" name="reset" value="reset">
</div>
<div class="col-lg-6">
<div class="form-group">
<label>Content:</label>
<input type="text" class="form-control" name="content" placeholder="explain in brief">
</div>
<div class="form-group">
<label>Age:</label>
<input type="text" class="form-control" placeholder="enter require age" name="age">
</div>
<div class="form-group">
<input type="submit" name="submitpost" value="Submit-Post" class="form-control">
</div>
</div>
</form>
and when i am using PHP code for inserting my image in one folder name img and other attributes in MySQL table.
<?php
$target_dir = "../../img/";
if (isset($_FILES['upload'])and isset($_POST['submitpost'])) {
$target_file = $target_dir . basename($_FILES["upload"]["name"]);
if(move_uploaded_file($_FILES["upload"]["tmp_name"], $target_file)){
$title=$_POST['title'];
$age=$_POST['age'];
$content=$_POST['content'];
$query="INSERT INTO `posts`
(`id`,`title`, `image`,`age`, `content`)
VALUES (null,'$title','$target_file','$age','$content')";
if(mysqli_query($con,$query))
{
echo "<script>alert('passed')</script>";
}else{
echo "<script>alert('not passed')</script>";
}
}else{
echo "<script>alert('problem with image upload')</script>";}
}
?>
But after submitting i am getting nothing, neither error or any notice nothing ,i don't know what is problem help me and I did try some other code then its inserting in table but image does not uploading in target folder .Help me through it i am new in PHP , so
You have added enctype="application/x-www-form-urlencoded" in the form for file input, its wrong. add like below
<form role="form" id="form1" action="" enctype="multipart/form-data" method="post">
Add PHP code like
$target_dir = $_SERVER['DOCUMENT_ROOT'] . '/img/';
if(!empty($_FILES['upload']['name'] && isset($_POST['submitpost']))){
$target_file = $target_dir . basename($_FILES["upload"]["name"]);
if(move_uploaded_file($_FILES["upload"]["tmp_name"], $target_file)){
extract($_POST);
$title = mysqli_real_escape_string($con,$title);
$age = mysqli_real_escape_string($con,$age);
$content = mysqli_real_escape_string($con,$content);
$query = "INSERT INTO `posts` (`id`,`title`,`image`,`age`,`content`)
VALUES (null,'{$title}','{$target_file}','{$age}','{$content}');";
if(mysqli_query($con,$query)){
echo "<script>alert('passed')</script>";
}else{
echo "<script>alert('not passed')</script>";
}
}else{
echo "<script>alert('problem with image upload')</script>";
}
}
please make sure $target_dir is correct path of your image upload directory.

Can't access form variable with php

I'm new to Web development and have been messing around with BootStrap. I've been trying to make a Web form on my new website, but I can't seem to access the username variable.
Here's my form code:
<form class="navbar-form navbar-left" role="search" action="username">
<div class="form-group">
<input name="username" type="text" class="form-control" placeholder="Username">
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>
And here's my index.php in the username folder:
<?php
echo $_POST['username'];
echo 'fail';
echo 'username';
if(isset($_POST['username'])) {
$name = $_POST['username'];
echo 'success';
}
?>
With my debugging, I get the message fail to show up, but not the username, so I assume I am doing something wrong either with setting the username, or accessing it.
According to your description, your HTML code should look something like this:
<form method="post" class="navbar-form navbar-left" role="search" action="username/index.php">
<div class="form-group">
<input name="username" type="text" class="form-control" placeholder="Username">
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>
You could also use <input class="btn btn-default" type="submit" value="Search"/> instead of <button type="submit"></button>.
You have the following mistakes
You didn't set the method attribute in your form.So when the form is submitted the data will be posted via get method.And you need to access $_GET variable for getting the form data. So here when you submit the form the data will be in $_GET variable.But you are trying to access $_POST variable in your code.So you can try like setting the method attribute to method="post in your form and continue with the same code in index.php or try changing $_POST to $_GET` in your index.php and making no changes in your form
You are definging the code in index.php when the form is submitted.So you need to set the action="index.php" in your form
So it will be like this finally
<form class="navbar-form navbar-left" role="search" action="username/index.php" method="post">
<div class="form-group">
<input name="username" type="text" class="form-control" placeholder="Username">
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>
index.php
<?php
echo $_POST['username'];
echo 'fail';
echo 'username';
if(isset($_POST['username'])) {
$name = $_POST['username'];
echo 'success';
}
?>
OR
<form class="navbar-form navbar-left" role="search" action="username/index.php">
<div class="form-group">
<input name="username" type="text" class="form-control" placeholder="Username">
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>
index.php
<?php
echo $_GET['username'];
echo 'fail';
echo 'username';
if(isset($_GET['username'])) {
$name = $_GET['username'];
echo 'success';
}
?>
Set your action attribute to index.php and set your method="post" if you access the username with $_POST['username'].

Bootstrap PHP Login

I'm having issues with my PHP login. I'm using bootstrap and When ever I click 'Login' nothing is happening. If I am correct it should be submitting me to a blank page.
Any suggestions?
Bootstrap Code:
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Please sign in</h3>
</div>
<div class="panel-body">
<form accept-charset="UTF-8" role="form">
<form action="submit.php" method="post">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Username" name="Username" type="text">
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="password" type="password" value="">
</div>
<input class="btn btn-lg btn-primary btn-block" type="submit" value="Login">
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
PHP code:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username&&$password)
{
$connect = mysql_connect("localhost", "sfmin", "password") or die("Error");
mysql_select_db("rothienc_login") or die("error");
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if($numrows!=0)
{
}
else
die("That user doesn't exist!");
}
else
die("ERROR");
?>
You defined <form> twice:
<form accept-charset="UTF-8" role="form">
<form action="submit.php" method="post">
Change this to just one element:
<form action="submit.php" method="post" accept-charset="UTF-8" role="form">
Make your username <input> name attribute lowercase:
<input class="form-control" placeholder="Username" name="username" type="text">
Escape your SQL query properly:
$query = mysql_query(
"SELECT * FROM users WHERE username='" . mysql_real_escape_string($username) . "'"
);
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Please sign in</h3>
</div>
<div class="panel-body">
<form action="submit.php" method="post">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Username" name="Username" type="text">
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="password" type="password" value="">
</div>
<input class="btn btn-lg btn-primary btn-block" type="submit" value="Login" name="submit" >
</fieldset>
</form>
</div>
</div>
</div>
php:
$connect = mysqli_connect("localhost", "sfmin", "password", "rothienc_login") or die("Error");
if(isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$query = mysqli_query($connect, "SELECT * FROM users");
if($username == $row['username'] && $password == $row['password'])
{
// User exists
$numrows = mysqli_num_rows($connect, $query);
if($numrows!=0)
{
}
else
die("That user doesn't exist!");
}
else
die("ERROR");
} else {
$username = "";
$password = "";
}
?>
this checks if the submit button was clicked if(isset($_POST['submit'])) then it checks for user match database records and then if it is correct it logs the user in also remember to set session variables
If you want a beauty and modern Login whit PHP and this, man! use JQuery Ajax.
In the input button change the type "Submit" for "button" and you need generate a basic ajax whit jquery.
$.ajax({
url: 'URL_PHP_LOGIN.php',
type: "POST",
data: {user: user, pass: pass},
success: function(html){
alert(html)//Alert when the login is correct.
}
});

Categories