For some reason, this form doesn't insert into my database.
Html
<form action="../php/register.php" method="post">
<div id ="personal-form">
<h4><b>Personal Details:</b></h4>
<hr>
<div class="form-group">
<label class="sr-only" for="first-name">First name</label>
First Name
<input type="text" name="firstname" placeholder=""
class="form-control" id="firstname">
<button type="submit" class="btn btn-next" id="submit">
Submit
</button>
</center>
</div>
</div>
</form>
php/register.php
<?php
include('connect.php');
if(isset($_POST["submit"])) {
$firstname = $_POST["firstname"];
$stmt = $conn->prepare("INSERT INTO storeowners (firstname) VALUES
(:firstname)");
$stmt->bindParam(':firstname', $firstname);
$stmt->execute();
header("location: next.php");
}
?>
This is connect.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=blaza", $username,
$password);
//set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "success";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
When I click on submit button, it shows the php/register.php page with the message success which is thesame message in the connect.php code if db connection was successful.
I dont know where the problem is cause it doesnt store the firstname to the database and no error was given.
if(isset($_POST["submit"]))
You have no form controls with name=submit so this condition will never be true.
You connect to the database unconditionally, but you never use the connection to do anything.
Add name="submit" to your button.
<form action="../php/register.php" method="post">
<div id ="personal-form">
<h4><b>Personal Details:</b></h4>
<hr>
<div class="form-group">
<label class="sr-only" for="first-name">First name</label>
First Name
<input type="text" name="firstname" placeholder="" class="form-control" id="firstname">
<button name="submit" type="submit" class="btn btn-next" id="submit">Submit</button></center>
</div>
</div>
</form>
Instead of $_POST["submit"] add this
if(isset($_POST["firstname"]))
Related
I am working on a user registration form where I'm storing user's username and password in a database table. My web page works fine on desktop browsers. But when I tried it on chrome browser in android it is unable to post any data to the database. It doesn't even show the echo that I've used in the php. I'm new to php.
I 'm using 000webhost's free hosting for my website.
Here's my code for form:
<form action="store.php" method="POST">
<div class="form">
<div class="input_field">
<input type="text" name="rname" placeholder="Phone number, username, or email" class="input">
</div>
<div class="input_field">
<input type="password" name="renterPass" placeholder="Password" class="input">
</div>
<button type="submit" class="btn btn-primary btn-sm">
<div class="btn-primary btn-sm">
Log In
</div>
</button>
</div>
<!--<input type="submit"-->
</form>
And the PHP code I've used is:
<?PHP
header('Content-Type: text/plain');
$name = $_POST['rname'];
$pass1 = $_POST['renterPass'];
$servername = "localhost";
$username = "xxxxxxx";
$password = "xxxxxxx";
$dbname = "xxxxxx";
$con = mysqli_connect($servername,$username,$password,$dbname);
if(!$con)
{
die("Error : ".mysqli_connect_error());
}
$sql = "INSERT INTO `new`(`name`, `password`) VALUES('$name','$pass1');";
if(mysqli_query($con,$sql))
{
echo "Registration Done Successfully...";
}
else
{
echo "Something went Wrong...";
}
mysqli_close($con);
?>
**Try This**
<form action="store.php" method="POST">
<div class="form">
<div class="input_field">
<input type="text" name="rname" placeholder="Phone number, username, or email" class="input">
</div>
<div class="input_field">
<input type="password" name="renterPass" placeholder="Password" class="input">
</div>
<button type="submit" name="submit" class="btn btn-primary btn-sm"></button>
</div>
</form>
<?PHP
$servername = "localhost";
$username = "xxxxxxx";
$password = "xxxxxxx";
$dbname = "xxxxxx";
$con = mysqli_connect($servername,$username,$password,$dbname);
if(!$con)
{
die("Error : ".mysqli_connect_error());
}
if(isset($_POST['submit'])){
$name = $_POST['rname'];
$pass1 = $_POST['renterPass'];
$sql = "INSERT INTO `new`(`name`, `password`) VALUES('$name','$pass1');";
if(mysqli_query($con,$sql))
{
echo "Registration Done Successfully...";
}
else
{
echo "Something went Wrong...";
}
}
mysqli_close($con);
?>
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
}
?>
The form is meant to capture a new user and store user data in the database, except that it does not store any data though the form still returns a successful message.
Form page:
<?php
$servername = "*****";
$username = "*****";
$password = "*****";
$database = "*****";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
<div class="row">
<div class="col-xs-12">
<section class="panel">
<header class="panel-heading">
<h2 class="panel-title">Laai Nuwe Lid</h2>
</header>
<div class="panel-body">
<form class="form-horizontal form-bordered" action=""
method="post">
<p><strong>ID:</strong> Nuwe lid</p>
<div class="form-group">
<label class="col-md-3 control-label"
for="FirstName">Naam:</label>
<div class="col-md-6">
<input type="text" class="form-control"
name="FirstName" id="FirstName" value="<?php echo $firstname; ?>">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label"
for="LastName">Van:</label>
<div class="col-md-6">
<input type="text" class="form-control"
name="LastName" id="LastName" value="<?php echo $lastname; ?>"'>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label"
for="Cell">Selfoon:</label>
<div class="col-md-6">
<input type="text" class="form-control"
name="Cell" id="Cell" value="<?php echo $cell; ?>">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label"
for="Address">Addres:</label>
<div class="col-md-6">
<input type="text" class="form-control"
name="Address" id="Address" value="<?php echo $adress; ?>">
</div>
</div>
<div class="row">
<div class="col-sm-9 col-sm-offset-3">
<button value="submit" type="submit"
name="submit" class="btn btn-primary">Stoor nuwe lid</button>
<button type="reset" class="btn btn-
default">Kanselleer</button>
</div>
</div>
</form>
</div>
</section>
</div>
</div>
<?php
// check if the form has been submitted. If it has, start to process the
form and save it to the database
if (isset($_POST['submit'])) {
// get form data, making sure it is valid
$firstname =
mysql_real_escape_string(htmlspecialchars($_POST['firstname']));
$lastname =
mysql_real_escape_string(htmlspecialchars($_POST['lastname']));
$cell = mysql_real_escape_string(htmlspecialchars($_POST['cell']));
$address = mysql_real_escape_string(htmlspecialchars($_POST['address']));
$sql = "INSERT INTO `tblusers` (FirstName, LastName, Cell, Address) VALUES
('$firstname','$lastname', '$cell','$address')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// once saved, redirect back to the view page
header("Location: index.php");
}
?>
I am not sure if the problem is with PHP or the SQL code as I get no error messages.
The database connects fine. The query works in mysql directly, but when I combine the PHP with the HTML form it stores blank rows.
The code does not work because when you tried to comment out the validation part 'if condition' you forgot to comment out its 'else condition'.
I am talking about this line:
//if ($firstname == '' || $lastname == '' || $cell == '' || $address == '') {
The reason it was not working is because the variables were not the same, PHP is case sensitive. E.G lastname while HTML was LastName.
$firstname =
mysql_real_escape_string(htmlspecialchars($_REQUEST['FirstNameirstname']));
$lastname = mysql_real_escape_string(htmlspecialchars($_REQUEST['LastName']));
$cell = mysql_real_escape_string(htmlspecialchars($_REQUEST['Cell']));
$address = mysql_real_escape_string(htmlspecialchars($_REQUEST['Address']));
Kindly use the following function :
$con->mysqli_real_escape_string ( $_POST['...'])
in place of
mysql_real_escape_string(htmlspecialchars($_POST['...']))
I keep submitting form input or attempting to do so I get a 404 with this PHP at the end of the url its in the top of the php snippit I am unsure if that is a clue to the issue. I have the action linked to insert.php I am unsure what is going on. Everything to me looks correct. But obviously its not. I've made sure the header('location: index.html') is correct. As another post suggested. Here is my code
HTML
<!Doctype html>
<html>
<head>
<title>Sign Up</title>
<link rel="stylesheet" href="css/live/app-d159020cbe.min.css">
<link rel="stylesheet" href="css/live/core-89ce772293.min.css">
</head>
<body>
<div class="containsignuptext">
<p>We believe the developer community is stronger togeather, We believe it takes the right community for us to reach the next stage in the future we believe in adding real tools to developers tool belts.</p>
</div>
<form action="insert.php" method="POST" accept-charset="UTF-8" role="form" id="loginForm">
<div class="form-group">
<div class="form-group">
<label for="login_email" class="sr-only">Full Name</label>
<input class="form-control input-lg" id="fullname" placeholder="Full Name" required="required" name="fullname" type="text">
</div>
<div class="form-group">
<label for="login_email" class="sr-only">Username</label>
<input class="form-control input-lg" id="username" placeholder="Username" required="required" name="username" type="text">
</div>
</div>
<div>
<label for="login_email" class="sr-only">Email</label>
<input class="form-control input-lg" id="email" placeholder="Email" required="required" name="email" type="text">
</div>
<div class="form-group">
<label for="login_password" class="sr-only">Password</label>
<input class="form-control input-lg" id="password" placeholder="Password" required="required" name="password" type="password">
<div>
<label for="login_email" class="sr-only">Codelangs</label>
<input class="form-control input-lg" id="codelang" placeholder="Code Language You Like the Most" required="required" name="codelangs" type="text">
</div>
<button method="POST" type="submit" class="btn btn-lg btn-primary btn-block ladda-button" data-style="zoom-in" type="submit" name="insert">
<span class="ladda-label">Get Hacking</span>
</button>
</form>
</body>
</html>
PHP
<?php echo $_SERVER['PHP_SELF']; ?>
I get that in the url idk if it helps the rest is the inser.php code.
<?php
$servername = "localhost";
$username = "Placeholder";
$pass = "FakeForShow";
$dbname = "sign up new";
$fullname=$_POST['fullname'];
$username=$_POST['username'];
$email=$_POST['email'];
$password=$_POST['password'];
$codelangs=$_POST['codelangs'];
// Create connection
$conn = new mysqli($servername, $username, $pass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO newusers (fullname, username, password, email, codelang)
VALUES ( '$fullname', '$username', '$email', '$password', '$codelangs');";
if ($conn->query($sql) === TRUE) {
header("location: index.html");
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
Your database connection should be similar to this.
$s = 'localhost';
$u = 'root';
$p = 'yourUsername';
$d = 'yourPassword';
$mysqli = new mysqli($s, $u, $p, $d);
Check to see if the butt is clicked first.
if(isset($_POST['insert'])){
Do some Error Checks like this you need to add to this this is very basic.
$fullname=$_POST['fullname'];
$username=$_POST['username'];
$email=$_POST['email'];
$password=$_POST['password'];
$codelangs=$_POST['codelangs'];
$alert = '';
$errorFullname = '';
if($_POST['fullname'] == '' || $_POST['username'] || $_POST['email'] || $_POST['password']){
if($_POST['fullname'] == ''){$errorFullname "Cannot be empty.";}//and so on...
$alert = "All fields are required.";} else {
If no Errors insert. Encrypt your passwords before inserting them.
$hashedWord = password_hash($password, PASSWORD_BCRYPT, array("cost" => 17));
$insertdata = $mysqli->prepare("INSERT INTO newusers (fullname, username, password, email, codelang) VALUES('"$fullname"', '"$username"', '"$hashedWord"', '"$email"', '"$codelangs"') ");
$insertdata->execute();
$insertdata->close();
header("location: index.html");
}
}
include 'YourHtmlPage';
You can call the error messages like this.
<div class="form-group">
<label for="login_email" class="sr-only">Full Name</label>
<input class="form-control input-lg" id="fullname" placeholder="Full Name" required="required" name="fullname" type="text">
</div>
<div><?php echo $errorFullname; ?></div>
You can use something like this to check the hashed password. Run a select and match it with what they typed.
password_verify($passwordTheyTyped, $YourHashedPassFromTheDatabase);
Hope it helps a little.
This might help you.
The HTML Code : index.php
<!Doctype html>
<html>
<head>
<title>Sign Up</title>
<link rel="stylesheet" href="css/live/app-d159020cbe.min.css">
<link rel="stylesheet" href="css/live/core-89ce772293.min.css">
</head>
<body>
<div class="containsignuptext">
<p>We believe the developer community is stronger togeather, We believe it takes the right community for us to reach the next stage in the future we believe in adding real tools to developers tool belts.</p>
</div>
<form action="insert.php" method="POST" accept-charset="UTF-8" role="form" id="loginForm">
<div class="form-group">
<label for="login_email" class="sr-only">Username</label>
<input class="form-control input-lg" id="username" placeholder="Username" required="required" name="username" type="text">
</div>
<!-- Other form elements-->
<button method="POST" type="submit" class="btn btn-lg btn-primary btn-block ladda-button" data-style="zoom-in" type="submit" name="insert">
<span class="ladda-label">Get Hacking</span>
</button>
</form>
</body>
</html>
The PHP Code : insert.php
<?php
$servername = "localhost";
$db_username = "DB_USER_NAME";
$db_pass = "DB_USER_PASSWORD";
$dbname = "DB_NAME";
$username = $_POST['username'];
// Other POST elements
$conn = new mysqli($servername, $db_username, $db_pass, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO newusers (username) VALUES ('$username');";
if ($conn->query($sql) === TRUE) {
header("location: index.php");
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
You can add more form elements, Javascript Validations etc as per your requirement.
Submit button does not functioning when I click. All of the code seem to have no errors, but it just does not inserted to my database. I am currently using bootstrap. I don't know what is the error I am having.
index.html
<div class="container">
<div class="col-md-5">
<div class="form-area">
<form role="form">
<br style="clear:both">
<h3 style="margin-bottom: 25px; text-align: center;">Schedule Form</h3>
<form name="form2" method="post" action="scheduleform.php">
<div class="form-group">
<input type="text" class="form-control" id="tajuk" name="tajuk" placeholder="Tajuk" required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="tarikh" name="tarikh" placeholder="Tarikh" required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="mobile" name="mobile" placeholder="Mobile Number" required>
</div>
<div class="form-group">
<textarea class="form-control" type="textarea" id="maklumat" name="maklumat" placeholder="Maklumat" maxlength="140" rows="7"></textarea>
<span class="help-block"><p id="characterLeft" class="help-block ">You have reached the limit</p></span>
</div>
<button><input type="submit" name="submit" class="btn btn-primary pull-right">Submit Form</button>
</form></form>
</div>
</div>
</div>
<!-- /#page-content-wrapper -->
scheduleform.php
<?php
$server = "localhost";
$user = "root";
$pass = "";
$dbname = "kajangdb";
//Creating connection for mysqli
$conn = new mysqli($server, $user, $pass, $dbname);
//Checking connection
if($conn->connect_error){
die("Connection failed:" . $conn->connect_error);
}
$tajuk = mysqli_real_escape_string($conn, $_POST['tajuk']);
$tarikh = mysqli_real_escape_string($conn, $_POST['tarikh']);
$mobile = mysqli_real_escape_string($conn, $_POST['mobile']);
$maklumat = mysqli_real_escape_string($conn, $_POST['maklumat']);
$sql = "INSERT INTO schedule (tajuk, tarikh, mobile, maklumat) VALUES ('$tajuk', '$tarikh', '$mobile', '$maklumat')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
Issues i found with your code.
1. You don't need to wrap form element with another form element
2.
$sql = "INSERT INTO schedule (tajuk, tarikh, mobile, maklumat) VALUES ('$tajuk', '$tarikh', '$mobile', '$maklumat')";
Here you added extra space after "schedule" and "VALUES" which may created problem. change your code as below.
$sql = "INSERT INTO schedule(tajuk, tarikh, mobile, maklumat) VALUES('$tajuk', '$tarikh', '$mobile', '$maklumat')";
1) Nested forms are definitely error-prone. Use more forms in a page, if
you wish, but never nest them. Here you are using form2 inside
another one. Don't do that, delete the outer one.
2) Your submit button syntax is wrong. Use input OR button.
Instead of:
<button><input type="submit" name="submit" class="btn btn-primary pull-right">Submit Form</button>
use:
<input type="submit" name="submit" value="Submit Form" class="btn btn-primary pull-right" />
or:
<button type="submit" name="submit" class="btn btn-primary pull-right">Submit Form</button>
3) Provide validation on $_POST values. Like:
if (
!isset($_POST['tajuk']) ||
!isset($_POST['tarikh']) ||
!isset($_POST['mobile']) ||
!isset($_POST['maklumat'])
) {
echo 'Error: not all values are valid. Please provide valid values.';
}
$conn = new mysqli($server, $user, $pass, $dbname);
//...
I recommend you to always prepare your sql statements for execution, in order to avoid the SQL injection risks. Use prepare() before querying. See: mysqli::prepare.
Also use exception handling. See please The mysqli_sql_exception class
EDIT 1:
It is not allowed to use paragraphs (<p>) inside spans (<span>). Use other container types, like <div> instead of <span>. So, replace
<span class="help-block">
<p id="characterLeft" class="help-block ">
You have reached the limit
</p>
</span>
with
<div class="help-block">
<p id="characterLeft" class="help-block ">
You have reached the limit
</p>
</div>