This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 7 years ago.
So I have this code that I'm executing when someone presses the "register" button.
I've read over the thing 10 times and can't find what I'm doing wrong.
The problem is: When you click register it doesn't insert the details into the database (even though it says it registered the user). I even looked through my db.php where I store the DB details.
Code for register page:
<?php
if(isset($_POST['register'])){
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$checkUsername = $odb->prepare("SELECT COUNT(*) FROM users WHERE username = :username");
$checkUsername->execute(array(':username' => $username));
$countUsername = $checkUsername -> fetchColumn(0);
$checkEmail = $odb->prepare("SELECT COUNT(*) FROM users WHERE email = :email");
$checkEmail->execute(array(':email' => $email));
$countEmail = $checkEmail -> fetchColumn(0);
if(!($countEmail == 0))
{
echo '<p>This e-mail has been taken.</p>';
}
elseif(!($countUsername == 0))
{
echo '<p>Error - this username has been taken.</p>';
}
else
{
try
{
$insertUser = $odb -> prepare('INSERT INTO users (username,password,email) VALUES(:username, :password, :email)');
$insertUser -> execute(array(':username' => $username, ':password' => $password, ':email' => $email));
echo 'Sucessfully registered.';
}
catch (PDOException $e)
{
echo 'Error: ' .$e->getMessage();
}
}
}
?>
When I use if(isset($_POST['register'])){ it doesn't echo any message or alter the database.
When I use if(isset($_GET['register'])){ it echos user registered but nothing is added to the database.
Here's my DB.php :
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'some_db');
define('DB_USERNAME', 'some_dbuser');
define('DB_PASSWORD', 'password');
$odb = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USERNAME, DB_PASSWORD);
$odb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
I hope someone knows what's going on, thanks!
Your form is processing as a GET request, not POST. The default form method is GET so either change/add method="post" or use $_GET. Using POST is a better option when sending user private user data.
Option A:
<form method="POST">
Option B (changing variable assignment):
if(isset($_GET['register'])){
$username = $_GET['username'];
$password = $_GET['password'];
$email = $_GET['email'];
$checkUsername = $odb->prepare("SELECT COUNT(*) FROM users WHERE username = :username");
$checkUsername->execute(array(':username' => $username));
$countUsername = $checkUsername -> fetchColumn(0);
$checkEmail = $odb->prepare("SELECT COUNT(*) FROM users WHERE email = :email");
$checkEmail->execute(array(':email' => $email));
$countEmail = $checkEmail -> fetchColumn(0);
if(!($countEmail == 0)) {
echo '<p>This e-mail has been taken.</p>';
} elseif(!($countUsername == 0)) {
echo '<p>Error - this username has been taken.</p>';
} else {
try {
$insertUser = $odb -> prepare('INSERT INTO users (username,password,email) VALUES(:username, :password, :email)');
$insertUser -> execute(array(':username' => $username, ':password' => $password, ':email' => $email));
echo 'Sucessfully registered.';
} catch (PDOException $e) {
echo 'Error: ' .$e->getMessage();
}
}
}
Also as previously noted passwords shouldn't be stored in plain text. MD5 and SHA1 are better than doing that but they aren't the best methods any more. Take a look at these posts:
http://php.net/manual/en/faq.passwords.php#faq.passwords.fasthash
https://security.stackexchange.com/questions/211/how-to-securely-hash-passwords
I think you have a problem with the PDO data check this out:
http://php.net/manual/en/pdo.prepare.php
I am a MYSQL guy but I get the same error when not using mysql_real_escape_string and this error looks to be same but with PDO.
Related
I want to execute mysql_qry1 also , how should i do it , till now my code is working fine but i want to execute the second query also(mysql_qry1) , please help.
<?php
require "conn.php";
$status=1;
$user_name = $_POST["user"];
$user_pass = $_POST["pass"];
$mysql_qry = "select * from tbl_client where username like '$user_name' and password like '$user_pass'";
$mysql_qry1 = "insert into login_status (username, status) values ('$user_name','$status)";
$result = mysqli_query($conn , $mysql_qry);
if(mysqli_num_rows($result)==1) {
echo "login success , Hello";
}
else {
echo "login failed";
}
$conn->close();
?>
Your SQL is one of most dangerous, please try to re-write:
//$mysql_qry = "select * from tbl_client where username like '$user_name' and password like '$user_pass'";
I m not sure what is in our conn.php, here is one of the example to update (PDO):
$sql = 'select 1 from tbl_client where username = :user and password = :pass';
$sth = $dbL->prepare($sql);
$sth->execute(':user' => $user_name, ':pass' => $user_pass);
$row = $sth->fetch(PDO::FETCH_NUM);
if ($row[0]) {
echo 'Login OK';
} else {
echo 'Login Failed';
}
$sql = 'insert into login_status (username, status) values (:user, :status)';
$sth = $dbL->prepare($sql);
$sth->execute(':user' => $user_name, ':status' => $status);
OK, so your conn.php is using mysqli_ . Please refer to this page for help:
http://php.net/manual/en/mysqli-stmt.bind-param.php
And change above answer to:
$sql = 'select 1 from tbl_client where username = ? and password = ?';
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, 'ss', $user_name, $user_pass);
mysqli_stmt_execute($stmt);
$row = mysqli_stmt_fetch();
if ($row[0]) {
echo 'Login OK';
} else {
echo 'Login Failed';
}
I have not used mysqli before, so not quite familiar, even php.net is hard to find out some docs about it. Please google howto use: mysqli_stmt_fetch() and replace it with proper code
Why not update your conn.php to use PDO? (be careful, you might need to update all your other pages as well which are calling this file):
// conn.php
$pdo = 'mysql:host=' . $server_name . ';dbname=' . $db_name;
$dbL = new PDO($pdo, $mysql_username, $mysql_password);
I need to do a Login form with PHP an SQlite. Registration works, and I can select all created users and echo them. When I try to check if username and password, which I get by $_POST, are matching: it echoes that I'm logged in now. But when I type in a wrong user/pw, it echoes the "invalid"-string, but there's also the following error:
Notice: Undefined variable: row in D:\xampp\htdocs\phpProjektSnippets\blogLogin.php on line 17
Line 17 is where I've got the if($row['username'] ...
This is my code:
$db = new PDO('sqlite:mysqlitedb.db');
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE user_name = :name AND user_password = :pass";
$statement = $db->prepare($sql);
$statement->execute(array('name' => $username, 'pass' => $password));
try {
$statement = $db->prepare($sql);
$statement->execute(array('name' => $username, 'pass' => $password));
foreach ($statement as $row);
if ($row['user_name'] == $username && $row['user_password'] == $password){
echo "Welcome " .$row['user_name']. ", You are now logged in.<br/ >";
}else{
echo "User Name or Password is invalid";
}
}
catch(PDOException $e) {
echo "Something went wrong: ".$e->getMessage();
}
What's wrong here?
First of all, you should not use an SQL query that looks like yours. It is vulnerable for SQL injections and thereby unsafe!
Please read the answers on How can I prevent SQL-Injection in PHP for some very helpful tips on how to do it right.
The problem is that you append to the SQL string whatever the user submits to the server - that might be malicious code that gives an attacker access to your database or deletes data or other bad things might happen. See the link above for more information.
In your case, the code would look like this:
<?php
$db = new PDO('sqlite:mysqlitedb.db');
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$username = $_POST['username'];
$password = md5($_POST['password']);
$sql = "SELECT * FROM users WHERE user_name = :name ";
try {
$statement = $db->prepare($sql);
$statement->execute(array('name' => $username));
foreach ($statement as $row){
echo $row['user_name'] . '<br />';
}
}
catch(PDOException $e) {
echo "Something went wrong: ".$e->getMessage();
}
?>
Edit: Since you configured PDO with $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ) to throw exceptions in case of an error, you should also catch them. I added the try/catch to the code.
Adding to Hexaholic answer and further to your question.
This line catch your code error
catch(PDOException $e) {
echo "Something went wrong: ".$e->getMessage();
}
If you want to write error in case of invalid user credentials,
use if true...else...statement.
if(some argument){
//do something if the argument result is true;
}else{
do something if the argument is not true;}
So your code should be something like this.
<?php
$db = new PDO('sqlite:mysqlitedb.db');
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE user_name = :name AND user_password = :pass";
try {
$statement = $db->prepare($sql);
$statement->execute(array('name' => $username, 'pass' => $password));
$row = $statement->fetch();
if ($row['user_name'] == $username && $row['user_password'] == $password){
echo "Welcome " .$row['user_name']. ", You are now logged in.<br/ >";
}else{
echo "User Name or Password is invalid";
}
}
catch(PDOException $e) {
echo "Something went wrong: ".$e->getMessage();
}
?>
And if this is working, remember to rectify your hashing issue.
Maybe this picture can better help you understand for the code above
Wrong password output.
Correct password output.
Trouble is with semicolon in this line: foreach ($statement as $row);
Foreach simply does nothing instead of subsequent if.
I have PHP + AS3 user login®ister modul.I want to check registered user by username.But can't do it because I'm new at PHP.If you can help it will helpfull thx.(result_message part is my AS3 info text box.)
<?php
include_once("connect.php");
$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];
$sql = "INSERT INTO users (username, password, user_bio) VALUES ('$username', '$password', '$userbio')";
mysql_query($sql) or exit("result_message=Error");
exit("result_message=success.");
?>
Use MySQLi as your PHP function. Start there, it's safer.
Connect your DB -
$host = "////";
$user = "////";
$pass = "////";
$dbName = "////";
$db = new mysqli($host, $user, $pass, $dbName);
if($db->connect_errno){
echo "Failed to connect to MySQL: " .
$db->connect_errno . "<br>";
}
If you are getting the information from the form -
$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];
you can query the DB and check the username and password -
$query = "SELECT * FROM users WHERE username = '$username'";
$result = $db->query($query);
If you get something back -
if($result) {
//CHECK PASSWORD TO VERIFY
} else {
echo "No user found.";
}
then verify the password. You could also attempt to verify the username and password at the same time in your MySQL query like so -
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password';
#Brad is right, though. You should take a little more precaution when writing this as it is easily susceptible to hacks. This is a pretty good starter guide - http://codular.com/php-mysqli
Using PDO is a good start, your connect.php should include something like the following:
try {
$db = new PDO('mysql:host=host','dbname=name','mysql_username','mysql_password');
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
Your insert would go something like:
$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];
$sql = "INSERT INTO users (username, password, user_bio) VALUES (?, ?, ?)";
$std = $db->prepare($sql);
$std = execute(array($username, $password, $userbio));
To find a user you could query similarly setting your $username manually of from $_POST:
$query = "SELECT * FROM users WHERE username = ?";
$std = $db->prepare($query)
$std = execute($username);
$result = $std->fetchAll();
if($result) {
foreach ($result as $user) { print_r($user); }
} else { echo "No Users found."; }
It is important to bind your values, yet another guide for reference, since I do not have enough rep yet to link for each PDO command directly from the manual, this guide and website has helped me out a lot with PHP and PDO.
its a little difficult to explain. I've build the mysql function which works fine and with the depreciation of mysql I will need to change this function to use mysqli rather than the mysql method.
I current have:
$con = mysql_connect("host", "username", "pass");
mysql_select_db("db", $con);
$Username = mysql_real_escape_string($_POST['user']);
$Password = hash_hmac('sha512', $_POST['pass'], '&R4nD0m^');
$Query = mysql_query("SELECT COUNT(*) FROM users WHERE username = '{$Username}' AND password = '{$Password}'") or die(mysql_error());
$Query_Res = mysql_fetch_array($Query, MYSQL_NUM);
if($Query_Res[0] === '1')
{
//add session
header('Location: newpage.php');
}
else {
echo 'failed login';
}
Now I've applied mysqli to this and it's not returning any data or errors but the function still complies.
$log = new mysqli("host", "user", "pass");
$log->select_db("db");
$Username = $log->real_escape_string($_POST['user']);
$Password = hash_hmac('sha512', $_POST['pass'], '&R4nD0m^');
$qu = $log->query("SELECT COUNT(*) FROM users WHERE username = '{$Username}' AND password = '{$Password}'");
$res = $qu->fetch_array();
if($res[0] === '1'){
//add session
header('Location: newpage.php');
}
else {
$Error = 'Failed login';
sleep(0.5);
}
echo $res['username'].' hello';
}
But I'm unsure on why this is wrong. I know it's probably a simply answer
Just to have it as an answer:
http://php.net/manual/en/pdo.prepared-statements.php
http://php.net/manual/en/pdo.prepare.php
e.g.
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
You may check if the connection is establishing before using real_escape_string()
if ($log->connect_errno) {
echo "Failed to connect to MySQL: (".$log->connect_errno.")".$log->connect_error;
}
afaik, there's no problem with $log->real_escape_string($_POST['user']);
I am unsure if I am doing it properly but I just started working with PDO and I am not able to get my code to work. I continue to get the error "sorry could not connect" and I am unable to figure out what is wrong.
Included below is the code that I am using:
function doRun( $data )
{
try
{
$db = new PDO('mysql:host=localhost;dbname=testData', 'root', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare(' SELECT
username, pass
FROM
testTable
WHERE
username = :name
AND
pass = :pass
');
$stmt->bindParam(':name', $username, PDO::PARAM_STR);
$stmt->bindParam(':pass', $pass, PDO::PARAM_STR);
$stmt->execute();
//$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$result = $stmt->fetchColumn();
if($result == false)
{
echo 'sorry could not connect';
}
else
{
$_SESSION['username'] = $user;
echo 'logged in as' . $user;
}
}
catch (PDOException $e)
{
echo "throw";
}
$db = NULL;
}
This would give you 0 rows as it seems that $username and $pass are not defined:
$stmt->bindParam(':name', $username, PDO::PARAM_STR);
$stmt->bindParam(':pass', $pass, PDO::PARAM_STR);
^^^^^^^^^
You probably want some elements from $data variable you are feeding to the function as a username and password.
Later on you are using a variable $user that is undefined as well.
What does $data contain?
The reason that you are "unable to connect", even though you are connecting but you're not finding a match, is because your user variables are not defined.
Try the following solution:
<?php
function doRun( $data )
{
$msg = '';
$username = isset($_POST['name']);
$pass = isset($_POST['pass']);
try
{
$db = new PDO('mysql:host=localhost;dbname=testData', 'root', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare('
select
username
,pass
from
testTable
where
username = :name
and pass = :pass
');
$stmt->execute(array(':name' => $username, ':pass' => $pass);
$result = $stmt->fetchAll();
if(!empty($result)){
$_SESSION['username'] = $user;
$msg = "logged in as $user";
}else{
$msg = "Unable to connect";
}
} catch (PDOException $e) {
echo "Error: $e";
}
echo $msg
$db = NULL;
}
?>