I am a complete beginner when it comes to PHP. I have successfully created a login form/page that requires a user to enter his/her username and password which is then added to a database. I have also managed to create a page (using php) to display the data contained in all the data fields. I have the db connection file separately which works well. I have a functions.php file which contains the functions.
Now, I have created a php file in which I should be able to update the data in the various fields in the database. Instead of updating/replacing the existing data (username & password) in the selected row (targeting the id) it creates a new row in the db with the new username & password. Herewith my code to update existing data fields.
<?php include "db.php";?>
<?php include "functions.php";?>
<?php
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$id = $_POST['id'];
$query = "UPDATE users SET ";
$query .= "username = '$username', ";
$query .= "password = '$password', ";
$query .= "WHERE id = $id ";
$result = mysqli_query($connection, $query);
if(!$result) {
die("QUERY FAILED" . mysqli_error($connection));
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="col-sm-6">
<form action="login_create.php" method="post">
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" class="form-control">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" class="form-control">
</div>
<div class="form-group">
<select name="id" id="">
<?php
showAllData();
?>
</select>
</div>
<input class="btn btn-primary" type="submit" name="submit" value="UPDATE">
</form>
</div>
</div>
</body>
</html>
I can simply not find the problem. Since people use PHP differently I am unable to find a solution based on the specific coding I have tried.
Update
Kindly note that I am working on a localhost as part of learning php and have not yet started looking at security. I am initialising the $connection via a different file (db.php) which I am calling in the first line of my previous code.
<?php
$connection = mysqli_connect('localhost', 'root', '', 'loginapp');
if(!$connection) {
die("Database connection failed");
}
?>
Since you didn't say what does the login_create.php do and what is the filename of that php code in your post. I can only guess that your login_create.php file is to create a new account not update it. Perhaps your file with that UPDATE query is not named login_create.php. Hence, my guess is that you put a wrong filename in your <form action="login_create.php" method="post">
(Posted solution on behalf of the question author).
The problem was with the incorrect naming of the form action. I used
<form action="login_create.php" method="post">
instead of
<form action="login_update.php" method="post">
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I'm a beginner in PHP and MySQL and I want to add values that come from an input in HTML, to a MySQL database.
I have to find some things on the Internet but this doesn't work and so I tried to learn a little bit more PHP but I still don't understand why the condition in the code below is not valid:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8">
<title>SHAR-APP</title>
</head>
<body>
<div class='div1'>
<div class='div2'>
<label for="name">Name of the user:</label>
<input class ='in'type="text" id="name" name="name" size="20">
</div>
<div class='div2'>
<label class = 'label' for="name">Code:</label>
<input class='in' id ='code' type="text" name="code" size="20">
</div>
<div class="div2" id='b'>
<input type="submit" value="send" class='button'>
</div>
</div>
<?php
echo "test1";
if (isset($_POST['name'])) {
echo "test2";
$mtsqli = mysqli_connect('localhost','the_name_of_my_project','my_password');
mysqli_select_db('project_database', $msqli);
$requete = 'INSERT INTO the_name_of_the_database's_table VALUES(NULL,"' . $_POST['name'] . '","' . $_POST['code'] . '")';
$query = "SELECT * FROM the_name_of_the_database's_table";
echo $_POST['name'];
echo "test3";
}
?>
</body>
</html>
I'm on this for 3 days and I'm really blocked. Maybe I have others mistake in the PHP code. If I can do that with another language i prefer to stay on PHP because I don't want to learn too much languages. If I can do a bridge between HTML and MySQL with Python or JavaScript I'm OK to know that.
THIS PART IS GOOD but another problem is come ...
when i want to connect on my database this error message is display
C:\Users\titou>set PATH=$PATH$;C:\Program Files\MySQL\MySQL Server 8.0\bin
C:\Users\titou>mysql -h localhost -u root -p
Enter password: **********
ERROR 1045 (28000): AccŠs refus‚ pour l'utilisateur: 'root'#'#localhost' (mot de passe: OUI)
its in french but you can see that there is two # instand of one ('root'#'localhost')
First you need to add a Form Method
<form action="" method="POST">
<div class='div2'>
<label for="name">Name of the user:</label>
<input class ='in'type="text" id="name" name="name" size="20">
</div>
<div class='div2'>
<label class = 'label' for="name">Code:</label>
<input class='in' id ='code' type="text" name="code" size="20">
</div>
<div class="div2" id='b'>
<input type="submit" value="send" class='button'>
</div>
</form>
The is some kind of class that tells the browser to expect inputs and then on the button click- to treat them.
The Action="" is for initializing where to treat the given inputs.
In your case, since your php code is in the same class as the form, you can leave it blank, either way you should initialize the path you want to send those data.
The Method="POST" is just a Method for treating your data on the web. It is also more secure than GET method which it works too but it's more sensitive since all the data from the inputs it's going to be exposed also in the URL.
Furthermore, I hope you have already installed XAMPP and already created a database in MySQL.
Add the form attribute to your form and in it add a method and an action. Method is needed to tell the form to post, and action is needed to tell the form what to do when you submit.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8">
<title>SHAR-APP</title>
</head>
<body>
<form method="post" action="">
<div class='div1'>
<div class='div2'>
<label for="name">Name of the user:</label>
<input class ='in'type="text" id="name" name="name" size="20">
</div>
<div class='div2'>
<label class = 'label' for="name">Code:</label>
<input class='in' id ='code' type="text" name="code" size="20">
</div>
<div class="div2" id='b'>
<input type="submit" value="send" class='button'>
</div>
</div>
</form>
<?php
if (isset($_POST['name'])) {
$db = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$requete = 'INSERT INTO the_name_of_the_database's_table VALUES(NULL,"' . $_POST['name'] . '","' . $_POST['code'] . '")';
mysqli_query($db, $requete);
$query = "SELECT * FROM the_name_of_the_database's_table";
$Data = mysqli_query($db, $query);
var_dump[$Data];
}
?>
</body>
</html>
Now an important thing to note, never use this in a live website as it would open up your website to SQL injection. You should use prepared statements instead, but for learning purposes, this is fine.
This question already has answers here:
How can I get useful error messages in PHP?
(41 answers)
Closed 3 years ago.
My HTML on my page is eliminated after running my PHP validation on the input form.
HTML: InsertUser.php
<?php
session_start();
require_once('File Below');
echo $errors; //Errors is local variable within insertBackend.php i know. i just wanted this example to be exact compared next to my code.
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script
</head>
<body>
<div class="container">
<form class="form-horizontal" role="form" method="post" action="InsertUser.php">
<div class="form-group">
<label for="txtName" class="col-sm-2 control-label">Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputName" name="txtName" placeholder="Name" value="">
</div>
</div>
<div class="form-group">
<label for="txtPassword" class="col-sm-2 control-label">Password:</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword" name="txtPassword" placeholder="Password" value="">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="btnSubmit" name="insert_form" type="submit" value="Submit" class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="btnCreate" onclick="location.href = 'createUser.php';" name="createUser" type="button" value="Create User" class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="btnsame" onclick="location.href = 'InsertUser.php';" name="InsertUser" type="button" value="Insert User" class="btn btn-primary">
</div>
</div>
</form>
</div>
</body>
</html>
PHP Page: InsertBackend.php
<?php
session_start();
require_once('*DIRECTORY CONTAINING SQL CONNECTION*'); //works fine
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
if(isset($_POST['insert_form']))
{
$_SESSION['InsertUser'] = "Insert User Pass"; //This ensures i make it INTO the method
$name= "";
$password = "";
$nameInsert = mysqil_real_escape_string($_POST['txtName']);
//^This right here. mysqli_real_escape_string();
$passInsert = mysqil_real_escape_string($_POST['txtPassword']);
//^This right here. mysqli_real_escape_string();
$errors = array();
if(empty($nameInsert))
{
array_push($errors, "Please enter your Name");
}
if(empty($passInsert))
{
array_push($errors, "Please enter your password");
}
if(count($errors = 0))
{
$name = mysqil_real_escape_string($con, $_POST['txtName']);
$password = mysqil_real_escape_string($con, $_POST['txtPassword']);
$hashPass = password_hash($password, PASSWORD_DEFAULT);
$sqlInsert = "INSERT INTO Table (Name, Phash)
VALUES ('$name', '$hashPass')";
$_SESSION['VerifyHash'] = $hashPass; // Super security issue using a hashed password as a flag? I know. Just wanted visual representation of pass to compare next to my database
if ($con->query($sqlInsert) === TRUE)
{
header('location: InsertUser.php');
echo "New record created successfully <br>";
}
else
{
header('location: InsertUser.php');
echo "Error: " . $sql . "<br>" . $con->error;
}
}
}
echo "Connected"; //Flag to verify Database connection throughout usage. If it makes it here then its connected. End flag.
//CLOSE DATABASE CONNECTION
mysqli_close($con);
?>
When I run all of this together and enter test data. It arrives on: InsertUser.php. and directs properly. However it displays nothing. No code, no Sessions, no HTML. Nothing? However when I simply refresh the page without navigating anywhere it displays the entire insert form fine. And 2 of my flags display:
ConnectedInsert User Pass
I then proceed to eliminate session data. Then I just see
Connected
above the login form. After this all takes place there is no change in my Database? And no users are actually added.
Using this information I can deduce that:
my form submits to my InsertBackend.php file when called from the form.
is connected to my database appropriately.
And that my Backend script is:
Not correctly inserting into the database.
Not properly hashing my password input.
Not rendering the HTML when called back to the insert form.
I have tried really hard to figure out where exactly in this chain of events things are going awry. However I have been unable to figure out why it is not all calling properly, and why my inserts are not working at all.
I really tried finding something on here that would help me figure it out. Unfortunately I was unable to locate anything that gave me clarity. And after the last few hours i have decided to see if anyone here might have any helpful insight into my issue. Just to even have a second set of eyes on it.
This was just poorly built with no session checking. The session cannot be created if it already exists i suppose.
Using
print_r(error_get_last());
Provides me with
Array ( [type] => 8 [message] => session_start(): A session had already been started - ignoring [file] => *InsertBackend.php* [line] => 2 )
Maybe? I guess i have to test this theory. I will update code as i progress until page is all displaying and inserting into database in case anyone else runs into a similar issue down the road.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
So, i am learning how to write php now.I want to build a small shopping website. My index.html looks something like this:
<!DOCTYPE html>
<html>
<head>
<link href="index.css" rel="stylesheet" />
<title>
eShop
</title>
</head>
<body>
<div class="topnav">
<a class="active" href="#index.html">Home</a>
Administrator
Register User
Register New Account
</div>
<img class="centerImage" src="eshop.jpg">
</body>
</html>
and the loginAdmin.php file looks like this:
<?php
session_start();
// here is the code that connects to the database. Note that the username
// and password are "hard-coded".
$user="root";
$passwd="";
$database="";
$link = mysqli_connect(localhost,$user,$passwd);
#mysqli_select_db($link,$database) or die ("Unable to select database");
// try to create a new record from the submission
$username = mysqli_real_escape_string($link,$_REQUEST['username']);
$password= mysqli_real_escape_string($link,$_REQUEST['password']);
if ($username && $password) {
// here we define the SQL command
$query = "SELECT * FROM people WHERE Username='$username' AND Password='$password'";
// submit the query to the database
$res=mysqli_query($query);
// make sure it worked!
if (!$res) {
echo mysql_error();
exit;
}
// find out how many records we got
$num = mysqli_numrows($res);
if ($num==0) {
echo "<h3>Invalid login</h3>\n";
exit;
} elseif ($num!=1) {
echo "<h3>Error - unexpected result!\n";
exit;
}
// valid login, set the session variable
$_SESSION['userid']=mysql_result($res,0,'userid');
echo "<h3>Welcome $username</h3>\n";
?>
<head>
<link href="login.css" rel="stylesheet" />
<title>
eShop
</title>
</head>
<body>
<div class="login-page">
<div class="form">
<form class="login-form">
<input type="text" placeholder="User Name:" />
<input type="password" placeholder="Password:" />
<button onclick="writeMsg()">login</button>
</form>
</div>
</div>
</body>
If the user pressed on the loginAdmin link so the php code will be executed, and i dont want that, only after the user pressed on the login button i want the php code block will be executed. How can i do that? Maybe i should seperate the files (php and html) and not user href on the php files in the index.html ? and the index.html file should be index.php?
You need to add your php code within a condition which satisfies when the form submission happens. Also you need to add name to your input fields
Your code will look like this,
<?php
session_start();
if(isset($_POST['username']) && isset($_POST['password'])) { //Added this line
// here is the code that connects to the database. Note that the username
// and password are "hard-coded".
$user="root";
$passwd="";
$database="";
$link = mysqli_connect(localhost,$user,$passwd);
#mysqli_select_db($link,$database) or die ("Unable to select database");
// try to create a new record from the submission
$username = mysqli_real_escape_string($link,$_REQUEST['username']);
$password= mysqli_real_escape_string($link,$_REQUEST['password']);
if ($username && $password) {
// here we define the SQL command
$query = "SELECT * FROM people WHERE Username='$username' AND Password='$password'";
// submit the query to the database
$res=mysqli_query($query);
// make sure it worked!
if (!$res) {
echo mysql_error();
exit;
}
// find out how many records we got
$num = mysqli_numrows($res);
if ($num==0) {
echo "<h3>Invalid login</h3>\n";
exit;
} elseif ($num!=1) {
echo "<h3>Error - unexpected result!\n";
exit;
}
// valid login, set the session variable
$_SESSION['userid']=mysql_result($res,0,'userid');
echo "<h3>Welcome $username</h3>\n";
}
} //Added this line
?>
<head>
<link href="login.css" rel="stylesheet" />
<title>
eShop
</title>
</head>
<body>
<div class="login-page">
<div class="form">
<form class="login-form" method="POST"> <!-- edited this line -->
<input type="text" name="username" placeholder="User Name:" /> <!-- edited this line -->
<input type="password" name="password" placeholder="Password:" /> <!-- edited this line -->
<button onclick="writeMsg()">login</button>
</form>
</div>
</div>
</body>
I have just added name to the form fields & then kept all your PHP code within a condition
I'm trying to create a registration page. The page is successfully connected to phpMyAdmin database but it does not echo anything when i click the register button.
<html>
<head>
</head>
<body>
<?php
INCLUDE "connect.php";
INCLUDE "functions.php";
INCLUDE "titlebar.php";
?>
<div id="loginform">
<h1>Register</h1>
<form name="Register" action="register.php" method="post">
<?php
if(isset($POST["submit"])){
$username = $_POST["username"];
$password = md5 ($_POST["password"]);
if(empty($username) or empty($password)){
echo "<p>Fields Empty!</p>";
} else {
mysql_query("INSERT INTO login VALUES('',$username','$password','2','')");
echo "<p>Successfully Registered!</p>";
}
}
?>
<p>
<label for="username">Username: </label>
<input type="text" name="username" id="username"/></p><p>
<label for="password">Password: </label>
<input type="password" name="password" id="password"/></p><p>
<input type="submit" name="submit" value="Register" />
</p>
</form>
</div>
</body>
The problem is with the post method.
use $_POST instead of $POST
You have mysql error
Not: $username'
but '$username'
And next time display mysql errors with mysql_error().
At the beginning, I am not sure what isset($_POST['submit'] should return, but as already mentioned in the comments you missed a single quote.
Additionaly i would use:
$password = password_hash($_POST['password'],
md5 is deprecated and thus not safe. If you write a login script you can use password_verify(plainPW, hashPW)
You also need to specify a database and login into it. I recommend to look at the W3 Schools examples they are very in-depth and have good examples.
W3 school mysqli page
also write a die() at the end of your script and do not foregt to close the connection.
I have a simple script for user login. I have the passwords encrypted as SHA1 in mySQL database table (using charset utf8_unicode_ci).
When I run "$q" in the database with values it returns result all right. But through the script even after entering correct credentials, I am not able to login. Also, it is working fine if I remove the encryption at both places (script and database). Same problem occurs if I use MD5 instead.
I am not sure what I am missing at. I tried to echo the SHA1 output and it comes out to be different than the encrypted password visible in the database. I have checked for any extra spaces in my input as well. Please help me understand what is wrong. Let me know if you need anything else. Thanks in advance!
connection.php holds the login credentials to the database and the below line:
$dbc = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
Below is the login page : "login.php"
<?php
#Start the session:
session_start();
include('../setup/connection.php');
if($_POST) {
$q = "select * from users where email = '$_POST[email]' and password = SHA1('$_POST[password]');";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) == 1) {
$_SESSION['username'] = $_POST['email'];
header('Location: index.php');
}
else {$msg="Username/Password incorrect. Please try again!";}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Admin Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<?php include('config/css.php'); ?>
<?php include('config/favicon.php'); ?>
<?php include('config/js.php'); ?>
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/r29/html5.min.js"></script>
<![endif]-->
</head>
<body>
<!--NAVIGATION BAR-->
<?php //include(D_TEMPLATE.'/navigation.php'); ?>
<div class="container">
<div class="col-lg-4 col-lg-offset-4">
<div class="panel panel-info">
<div class="panel-heading">
<h1 class="lato fs20"><strong>Login</strong></h1>
</div>
<div class="panel-body">
<?php echo $msg; ?>
<form role="form" method="post" action="login.php">
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" class="form-control" name="password">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
For the "$q" variable, you should use php sha1 function:
$q = "select * from users where email = '$_POST[email]' and password = '" . sha1($_POST[password]) . "'";
But as Fred-ii said you really shoud (have to) protect your variables before.
For example :
$_POST['email'] = mysqli_real_escape_string($_POST['email']);
It will protect your variable against SQL injection (https://php.net/manual/en/mysqli.real-escape-string.php)