I'm trying to confirm if a user submitted valid credentials.
HTML
<form action="assets/php/account/login_user.php" method="post" id="login" class="center">
<div id="register_errorloc"></div>
<div class="form-group">
<input type="text" name="login_username" id="login_username" class="form-control" placeholder="Username" />
</div>
<div class="form-group">
<input type="password" name="login_password" id="login_password" class="form-control" placeholder="Password" />
</div>
<div class="form-group">
<input type="submit" value="login" id="submit_login" class="btn btn-success form-control"/>
</div>
</form>
PHP
$username = trim($_POST['login_username']);
$password = hash('sha512',trim($_POST['login_password']));
//to check if values are correct by myself
echo '<br>' . $username . '<br>' . $password . '<br>';
include_once '../../../assets/php/DB/DBConnect.php';
//check if valid credentials are entered
$stmt = $conn->prepare("SELECT * FROM tbl_users WHERE username = ?");
echo $stmt->bind_param('s', $username);
echo $stmt->execute();
echo $stmt->store_result();
if($stmt->num_rows == 1){
echo 'Good Creds';
}else{
echo 'Bad Creds';
}
When I'm doing this it always shows 0 results. When I change the querystring to
$stmt = $conn->prepare('SELECT * FROM tbl_users WHERE username = "abc"');
I get the result I'm looking for. I'm confused because I'm using the same approach on a different page and it's working like a charm.
Screenshots
Login form
Submitted form
Row I'm looking for
Edit: Added all code.
Edit2: Added screenshots
Edit3: Added Form HTML
Edit4:
Nothing is wrong with the form submit. When I'm hardcoding the variable like this:
$username ='abc';
It still doesn't work
I'm sorry but you posted screenshots that don't help us.
In order to avoid further commenting, am submitting the following.
Your form and its related elements may be failing and require a POST method and that name attributes exist for each of them.
I.e.:
<form method="post" action="???">
<input type="text" name="login_username">
...
Edit:
Try the following, comments are getting too extensive:
$check = $conn->prepare("SELECT * FROM tbl_users WHERE username=?");
$check->bind_param("s", $username);
$check->execute();
$check->store_result();
$row_chqry = $check->num_rows;
if($row_chqry > 0 ) {
echo "Exists";
$check->close();
$conn->close();
}
Edit #2:
OP posted an answer stating that they were using the same variable for their db connection.
Something I would have spotted right away and causing a conflict, had full code been posted. I've seen that happen quite a few times before, and remember posting answers for them too. As to where they are exactly, it would take some time for me to find them; but I do remember posting answers for related questions.
Oh well, problem solved.
Solutions:
Use a different variable for your username(s).
Use unique variables.
I finally found the error:
When connecting to my DB I use:
$servername = "";
$username = "";
$password = "";
$db = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $db);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
In my submission script I also use $username. Including the DBconnection file caused my local variable ($username that I get from the form) to be overwritten with the username found in the DBconnect.
Related
I'm attempting to create a page, where I can search for case files from my database, however, I can't get my code to work.
I already have pages showing all content of the database and where I can add new content.
I've read guides, tutorials and questions on stackoverflow, but can't find an answer on how to proceed.
I have the following php code in searchcasescript.php
<?php
$servername = "localhost";
$username = "test";
$password = "";
$dbname = "test";
$conn = mysqli_connect($servername, $username, $password, $dbname) or
die("connection failed: " . mysqli_connect_error());
mysqli_select_db($conn, $dbname) or die("something went wrong");
if(isset($_GET["form_submit"]))
{
$journalnummer =$_GET["journalnummer"];
$stmt = $conn->prepare("select * from testcases where journalnummer=? ");
$stmt->bind_param("s",$journalnummer);
$stmt->execute();
$val = $stmt->get_result();
$row_count= $val->num_rows;
if($row_count >0)
{
$result =$val->fetch_assoc();
print_r($result);
}
else{
echo "wrong number";
}
$stmt->close();
$conn->close();
}
?>
and my html:
<div class="container-fluid">
<div class="form-group">
<form action="searchcasescript.php" method="post">
<label for="journalnummer">Journalnummer:</label>
<input type="text" name="journal" class="form-control" required>
<div class="form-group"> <br>
<input type="submit" name="form_submit" class="btn btn-basic" value="Søg">
</form>
I've had different results depending on my changes to the php, but currently I'm getting nothing. Pressing search opens a new, blank page.
What I would like to end up with was being able to enter full or part of a case number and the search results being displayed on the same or a new page.
Can anyone point me in the right direction to read more about this and/or where to proceed with my code?
And apologies, if I've somehow missed the answer in one of the questions here.
UPDATED WITH "LIKE":
$stmt = $conn->prepare("SELECT * FROM straffesager WHERE journalnummer LIKE ?");
$stmt->bind_param("s", '%' . $journal . '%');
$journalnummer =$_GET["journalnummer"];
Your looking for journalnummer but your input has a name of journal
<input type="text" name="journal" class="form-control" required>
$_POST['journal'];
This is what should contain the number .
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am trying take some data of a specific row from the table users by checking if the username and password are correct.
I cant see why it is not working!!
EDIT: I insert the code of the whole page. I am using to form because i in the same form i have the register button and the log in button. I am checking which one the user pressed and then do things.
$host = "xx";
$user = "xx";
$pass= "xx";
$dbname = "xx";
$conn = new mysqli($host,$user,$pass, $dbname );
if ($conn->connect_error) {
die("Connection failed : ".$conn->connect_error); //fixme
}
if ( isset($_POST['login']) ) {
if ($_POST["actionb"] == 'Login') {
$username = isset($_POST["username"]) ? $conn->real_escape_string($_POST["username"]) : "";
$password = isset($_POST["password"]) ? $conn->real_escape_string($_POST["password"]) : "";
echo $username;
echo $password;
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$results=$conn->query($query);
if (mysqli_num_rows($results) > 0 ) {
$_SESSION['username'] = $username;
if ($results->num_rows > 0) {
// output data of each row
while ($row = $results->fetch_assoc()) {
$email = $row["email"];
$postalcode = $row["postalcode"];
$phonenumber = $row["phonenumber"];
}
}
$_SESSION['postalcode'] = $postalcode;
$_SESSION['phonenumber'] = $phonenumber;
$_SESSION['email'] = $email;
echo "You are now logged in";
header('location: confirm.php');
} else {
//echo "Wrong username/password combination";
}
}
}
?>
<html>
<style type ="text/css">
...
</style>
<body>
<form action="" method="post">
<div class="header">
<h1>For existing users</h1>
</div>
<input type="hidden" name="actionb" value="Login" >
<label for="username"><b>Username</b></label>
<input type="text" placeholder="Enter username" name="username" required>
<label for="password"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="password2" required>
<div class="clearfix">
<button type="submit" name="login" value="Login">Login</button>
</div>
</form>
</body>
</html>
First: like #IdontDownVote said, you should always(!) hash/encrypt passwords before storing them in a database (see php.net/manual/en/book.password.php). One hack and all your users will hate you for not doing it. ;)
Second: can it be you are getting more then one row back? (As presumed by your if ($results->num_rows > 0) { later in the code.) The error also fires then, because you check for ==1, might change it to >0.
Third: check if the mysqli_query() call was successfull by added it in your if statement with $results && mysqli_num_rows(..etc..
Fourth: the password is actually send as $_POST['password2']
Fifth: (As #FunkFortyNiner pointed out correctly) using header() as a redirection must be the first thing to output to the browser (so no echo's before that) and followed by a exit(); to prevent something else echo-ing after that (which is also not valid in PHP).
Sixth: (As #FunkFortyNiner pointed out as well) While developing, always turn error reporting on using error_reporting(E_ALL | E_STRICT | E_NOTICE); and
ini_set('display_errors', 1); at the top of you PHP. This way all errors, warnings etc are explicitly printed in the browser, so you can debug/clean/fix.
I have a form in HTML, but it's not setup like normal I guess. I'll post the code form the HTML (PHP) file and the php to send it to the db.
<form action="upload.php" method="POST">
<!-- Name input-->
<div class="form-group">
<label class="control-label" for="name">Name</label>
<div class="">
<input id="name" name="name" placeholder="First and Last Name" class="form-control input-md" type="text" required>
</div>
</div>
<div class="form-group">
<label class=" control-label" for="supportingDoc">Upload Supporting Documentation</label>
<div class="">
<input id="supportingDoc" name="supportingDoc" class="input-file" type="file" style="margin-top: .5em; margin-left: 4em;">
</div>
</div>
<hr>
<!-- Submit -->
<div class="form-group">
<label class="control-label" for="submit"></label>
<div class="">
<button value="Submit" type="submit" id="submit" name="submit" class="btn btn-danger" style="border-radius: 25px;">Submit</button>
</div>
</div>
</form>
Here is my SQL/PHP
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$con = mysqli_connect("localhost","xxx","xxx","xxx");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_REQUEST['name'])){
// set variables
$name = mysql_real_escape_string($_POST['name']);
$supportingDoc = mysql_real_escape_string($_POST['supportingDoc']);
$sql = "INSERT INTO `tablew` (name, supportingDoc) VALUES ('$name', '$supportingDoc')";
$result = mysqli_query($con,$sql);
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
printf("New record created successfully");
} else {
echo "Error: " . $sql . "<br>" . $con->error;
printf("Error: " . $sql . "<br>" . $con->error);
}
$con->close();
}
?>
I've tried all sorts of variations and nothing is showing in phpmyadmin. I've even replicated from a previous site I created and it still didn't work lol.
I see that there are variables for the login info and still put it in the mysqli, but I've been at this one thing for about 8 hours now and am out of juice, so hopefully someone sees what I messed up on.
Thanks in advance for any help everyone.
===========================================================================
UPDATE:
I made all the changes mentioned above and now get this:
Warning: mysqli_connect(): (HY000/1049): Unknown database
I can see the database in phpmyadmin and Sequel Pro. I've also made sure to set the password and login to 'root'. My code is as follows for login:
$con = mysqli_connect("localhost","root","root","epboarding");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
and this is my POST:
if (isset($_REQUEST['submit'])){
// set variables
$name = mysqli_real_escape_string($con, $_POST['name']);
$sql = "INSERT INTO `wos` (name) VALUES ('$name')";
$result = mysqli_query($con,$sql);
Following issues can be there:
Uploading error. Use enctype="multipart/form-data" in form tag.
Correct Mysql_connect details i.e. Username, Password, Dbname.
mysql_real_escape_string is depricated. Use mysqli.
Recheck your column names i.e. name, supportingDoc.
Your html code wrong. Whenever you want to use input type file, you need to put <form> tag to <form enctype="multipart/form-data">. If you re not declaring the enctype, then the PHP cannot read the file.
you have to put
<form enctype="multipart/form-data">
when uploading file . correct your html.
Try This
The issue is after clicked on submit button it's not hitting the (isset($_REQUEST['name']))
Change it
if (isset($_REQUEST['submit'])){ //code here}
because you button name is submit.
Use SQL injection like
$con->real_escape_string($_POST['name']);
for the unknown database error. I simply went to operations in phpmyadmin and changed the name of the database and it worked. give it a try if you haven't fixed the problem yet.
in addition to #tbi
answer
Check php.ini for max post size it cause the POST request to fail if the size exceeds the size set in php.ini
post_max_size=20M
upload_max_filesize=20M
check your SQL connection and your permissions on the DB
use enctype="multipart/form-data" in your form only when you need to upload files (for security reasons)
finally, don't forget to bind your post params to prevent SQL-Injection
Params Binding
If you are using a default account on a local installation, then your connection code will probably look like this:
<?php $con = mysqli_connect('localhost','root','');
mysqli_select_db('epboarding', $con); ?>
use enctype="multipart/form-data" in form tag when you use file type.
<form name="" method="POST" action="" enctype="multipart/form-data">
3.change the following line
if (isset($_REQUEST['name'])){
to
if (isset($_REQUEST['submit'])){
correct the syntax when post data like mysql to mysqli.
From the PhpMyAdmin screenshot, it looks like the database is running on port 8889, meaning you would need:
$con = mysqli_connect("localhost","xxx","xxx","xxx", 8889);
In addition to what the others have said, I thought I'd provide a tidied script and some (hopefully) useful resource for you other issues.
http://php.net/manual/en/mysqli.construct.php
What's wrong with using $_REQUEST[]?
https://www.w3schools.com/sql/sql_injection.asp
As for your unknown database error this is either your database doesn't exist, is incorrectly named in your PHP script or is unavailable through localhost.
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli ( $servername, $username, $password, $dbname );
// Check connection
if ( $conn->connect_error ) {
echo "Failed to connect to MySQL: " . $conn->connect_error;
}
// Check if values are set with post rather than request, as this is deprecated and can output unexpected results
if ( isset( $_POST['name'] ) ) {
// Set variables
$name = $_POST['name'];
$supportingDoc = $_POST['supportingDoc'];
// Prepare a statement and bind parameters to prevent sql injection
$stmt = $conn->prepare( "INSERT INTO `tablew` (name, supportingDoc) VALUES (?, ?)" );
$stmt->bind_param( 'sb', $name, $supportingDoc );
if ( $stmt->execute() ) {
echo "New record created successfully";
printf( "New record created successfully" );
} else {
echo "Error: " . $stmt->error;
printf( "Error: " . $stmt->error );
}
$stmt->close();
$conn->close();
}
This problem is really giving me a hard time. I have 4 files, one for DB config, the other for login page, 3rd for login-processing and lsat one for the redirect after successful login)
This is my db-connect.php:
<?php
$servername = "localhost";
$username = "dbroot";
$password = "dbpassword";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
the form in my user-login.php:
<form action="includes/login-process.php" id="login" class="formoid-metro-black" style="background-color:transparent;font-size:14px;font-family:'Open Sans','Helvetica Neue','Helvetica',Arial,Verdana,sans-serif;color:#FFFFFF;max-width:400px;min-width:150px; float:right;" method="post" enctype="multipart/form-data"><div class="title"><h2>Log In</h2></div>
<div class="element-input"><label class="title">Username<span class="required">*</span></label><input class="large" type="text" name="username" required="required"/></div>
<div class="element-password"><label class="title">Password<span class="required">*</span></label><input class="large" type="password" name="password" value="" required="required"/></div>
<div class="submit"><input type="submit" name="submit" value="Log In"/></div></form><script type="text/javascript" src="forms/sign-up-form_files/formoid1/formoid-metro-black.js"></script>
The login-process.php:
<?php include ("db-connect.php");
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$encrypt = md5($password);
$userquery = "SELECT * FROM user WHERE `user-username`='$username' AND `user-password`='$password'";
$run = mysqli_query($conn,$userquery);
if(mysqli_num_rows($run)>0){
$_SESSION['username']=$username;
?>
<script>alert('Login successful.')</script>
<script>window.open('../user-profile.php','_self')</script>
<?php
}
else {
?>
<script>alert('Username or Password Incorrect.','_self')</script>
<script>window.open('../user-login.php','_self')</script>
<?php
}
}
?>
And in my login page, after i successfully log in, proven by the script alert being successful, however, as the user-profile.php opens (where I put a session_start() on top), it directly runs the condition inside the if statement, ignoring the fact that i already successfully logged in.
This is my user-profile.php:
<!DOCTYPE html>
<?php
session_start();
if(!isset($_SESSION['username'])){
?>
<script> alert('Please Log-in first.','_self')</script>
<?php include_once('user-login.php');
}
else {
$first_name= $_SESSION['fname'];
$first_name= ucfirst($first_name);
?>
//rest of my code
The code above should run what's inside the else statement, but instead i keep getting the alert to login first. (Just ignore the $firstname codes, I want to get it for output below). Does any of you have any idea about this? If so, pleeeease help me. Thank you!
In your login-process.php, you must session_start() first before setting values to session variables.
you are accessing session directly without declaring the session. User session_start() before accessing session variables and you may use session_close() once you are done accessing them.
I am trying to build a login system with registration etc.
now for the registration i use a form and the method "post". Now it fails in what i think is sending the input trough the post. can you help me fix it? here is the code involved in it:
above !doctype
<?php
include('connect.php');
// If the values are posted, insert them into the database.
if (isset($_POST["username"]) && isset($_POST["password"])){
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$query = "INSERT INTO `user` (username, password, email) VALUES ($username, $password, $email)";
$result = mysqli_query($query);
if($result){
$msg = "User Created Successfully.";
}
else
{echo "fail";}
}
?>
the form:
<div class="register-form">
<?php
if(isset($msg) & !empty($msg)){
echo $msg;
}
?>
<h1>Registreer</h1>
<form action="" method="POST">
<p><label>User Name : </label>
<input id="username" type="text" name="username" placeholder="username" /></p>
<p><label>E-Mail : </label>
<input id="password" type="email" name="email" required placeholder="name#email.com" /></p>
<p><label>Password : </label>
<input id="password" type="password" name="password" placeholder="password" /></p>
<a class="btn" href="login.php">Login</a>
<input class="btn register" type="submit" name="submit" value="Registreer" />
</form>
</div>
The connect.php
<?php
$servername = "localhost";
$username = "sqluser";
$password = "Welkom01!";
$dbname = "users";
$connection = mysqli_connect($servername, $username, $password);
if (!$connection){
die("Database Connection Failed". mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, $dbname);
if (!$select_db){
die("Database Selection Failed" . mysqli_error($connection));
}
?>
Thanks in advance.
As per your originally posted question and without marking it as an edit under your newly edited question, should anyone wonder why the answer.
Since we're more than likely dealing with strings
VALUES ($username, $password, $email)
needs to be wrapped inside quotes:
VALUES ('$username', '$password', '$email')
you also need to pass DB connection to your query $result = mysqli_query($query);
Edit: (you added your DB connection code after) from your original post
Since you've not shown what your DB connection is, this would be something like
$result = mysqli_query($connection,$query);
plus, adding or die(mysqli_error($connection)) to mysqli_query()
You also have a missing & in if(isset($msg) & !empty($msg)){ which should read as if(isset($msg) && !empty($msg)){
However, your present code is open to SQL injection.
Use prepared statements, or PDO with prepared statements, they're much safer.
Passwords
I also noticed that you may be storing passwords in plain text. This is not recommended.
Use one of the following:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PHP 5.5's password_hash() function.
Compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/
Other links:
PBKDF2 For PHP