$username = $_POST["user_name"];
$password = $_POST["user_password"];
$type = $_POST["user_type"];
$query = "SELECT * FROM users WHERE user_name='$username' AND user_password='$password' AND
user_type='$type'";
When run, I get an error message that states that the first three lines of code have undefined indexes. Could someone help me figure out what went wrong here and how to fix it?
if(isset($_POST["username"]) && isset($_POST["user_password"]) && isset($_POST["user_type"])){
$username = $_POST["user_name"];
$password = $_POST["user_password"];
$type = $_POST["user_type"];
$query = "SELECT * FROM users WHERE user_name='$username' AND user_password='$password' AND
user_type='$type'";
}
else{
// required value is missing
}
When you use $_POST you must check that the required values are in $_POST in not. So you should use isset()
Well we can't see the contents of your $_POST array, but likely your form is not posting correctly, or you have misnamed your input fields, because the "user_name," "user_password," and "user_type" indexes of the $_POST array do not exist, according to the error.
Could you post the form code? Or echo $_POST and tell us what the output contains?
Change your code so it checks whether it's there or not
$username = iseet($_POST["user_name"]) ? $_POST["user_name"] : '';
$password = isset($_POST["user_password"]) ? $_POST["user_password"] : '';
$type = isset($_POST["user_type"]) ? $_POST["user_type"] : ;
//NOTE - You have an sql injection vulnerability in the below code
$query = "SELECT * FROM users WHERE user_name='$username' AND user_password='$password' AND
user_type='$type'";
Always check whether your indices are set or not.
Also, don't insert array values directly into your SQL like that. At least use mysql_real_escape_string or consider using MySQL PDO
http://php.net/manual/en/function.mysql-real-escape-string.php
Related
I wrote code for sign up where I check username , if it is exists in database or not than add new user accordingly. I am new to sql->prepare statement, Problem is in count function , when checking username it works properly, but in else part when adding user it gives me following error
Uncaught TypeError: count(): Argument #1 ($value) must be of type
Countable|array, bool
Here is my adduser.php code.
<?php
include 'config.php';
//checkusername
$check = $con->prepare("select username from users where username = ?");
$check->bindParam(1,$username);
$username = $_POST['username'];
$check->execute();
$row = $check->fetch(PDO::FETCH_ASSOC);
if(count($row)){
echo -1;
}
else{
$sql = $con->prepare("insert into users(name,username,password) values(?,?,?)");
$sql->bindParam(1,$name);
$sql->bindParam(2,$username);
$sql->bindParam(3,$password);
$name = $_POST['name'];
$username = $_POST['username'];
$password = md5($_POST['password']);
$sql->execute();
echo 1;
}
?>
It doesn't make much sense to use count here, you don't need to know how many fields are in the row.
Just check if it's false or not - see php.net/manual/en/pdostatement.fetch.php which mentions that fetch() will return false when it fails (i.e. there is no row available).
This would make more sense:
if($row) {
$sql = $con->prepare("insert into users(name,username,password) values(?,?,?)");
//...etc...
}
else {
echo -1;
}
After executing the query with $check->execute();, you can use the built-in method to count the returned rows: $check->rowCount();.
I think the statement above returned 0 rows, so you can't do $check->fetch() and it returns false.
Example:
// Your code here...
$check = $con->prepare("select username from users where username = ?");
$username = $_POST['username']; // This line needs to be before the next one, because you used the variable $username before defining it
$check->bindParam(1,$username);
$check->execute();
if($check->rowCount() > 0) {
// User does exist
} else {
// User does not exist
}
Edit 2: I just realised that the answer I've given below is wrong. The thing I suggest instead is checking if there's any value by using the PDO rowCount() method, like this: if ($check->rowCount()>0)
wrong stuff below
You're assigining $username a value after binding it.
$check = $con->prepare("select username from users where username = ?");
$check->bindParam(1,$username); //bind $username
$username = $_POST['username']; //assign value
$check->execute();
Try switching those two lines so $username is assigned a value when you're binding it.
$check = $con->prepare("select username from users where username = ?");
$username = $_POST['username']; //assign value
$check->bindParam(1,$username); //bind $username
$check->execute();
Edit
In case you're still having issues, try checking if there's any error in the sql statement execution.
After your $check->execute(); you can add print_r($check->errorInfo()); to see if your MySQL statement has any issues in it.
ok, so i have a little issue here with php. I know there are alot of similar questions, but ones i found did not help.
I dont want to use anything more like javascript or something. I got mysql set up, there are 3 columns ID username and password.
<?php
$username = $_POST['user'];
$password = $_POST['pass'];
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
mysql_connect("localhost","root","");
mysql_select_db("login");
$result = mysql_query("select * from users where username='$username' and password= '$password'")
or die("failed to query DB".mysql_error());
$row = mysql_fetch_array($result);
if ($row['username'] == $username && $row['password'] == $password) {header(suc.html);
die();}else{header("Location: fail.html");die();}
?>
This code, it works but when i dont fill in any details and press submit too, it gets me to the suc.html which shows successful login. Now i want to make the following:
I'll make ID's similar to each individual html's names, then the php will go match the ID number with the file name in the directory, and show the page for the respective user.
like lets say user1.
Login userlol password 123 ID user1 file user1.html
then what code to use that it goes and matches the ID user1 with the .html name, then redirects the user to their own custom page. Is there a way? Kinda getting started with php ,so cut some slack please :)
p.s i know these codes are older php codes, but anything works for me personally.
You are getting that sort of behaviour because when a username and password is not submitted, their respective values evaluates to null and your SQL query is successful but returns 0 rows thereby making your $row['username'] and $row['password'] to be null. In general, your $row['username'],$row['password'],$username,$password would all be equal to null which fulfills all the requirements to redirect to "suc.html"
To solve this problem, simply check if mysql_num_rows($result)==1 because usually, a successful login would return just one row due to unique usernames.
But
I would not advice you to continue with deprecated mysql and SQL Injection susceptible logic. Please allow me to rewrite your logic as follows:
<?php
$username = $_POST['user'];
$password = $_POST['pass'];
// You don't have to escape or sanitize user inputs if you use Prepared Statement plus sanitizing user password is highly discouraged.
// $username = stripcslashes($username);
// $password = stripcslashes($password);
// $username = mysql_real_escape_string($username);
// $password = mysql_real_escape_string($password);
// Initiate a PDO connection and set your error mode to exception.
$conn=new pdo("mysql:host=localhost;dbname=login;","root","",array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
try{
// Prepare your query and replace all values with ? which would be provided as an array in execute(); I added limit 1 to make sure we are getting a maximum of one row from our query.
$result_stmt = $conn->prepare("select * from `users` where (`username`=? and `password`=?) limit 1");
$result_stmt->execute([$username,$password]);
// fatch() would return a single row just like mysql_fetch_array or mysql_fetch_assoc while fetchAll() would return all rows.
$result=$result_stmt->fetch();
if(count($result)==1){
// There is no need to check this again because your query to the database already did.
// if ($row['username'] == $username && $row['password'] == $password)
// Redirect users to the same page but identify each user through session (recommended)
header("location:suc.html");
}else{
header("location:fail.html");
}
}catch(Exception $e){
echo $e->getMessage();
}
?>
I was wondering how to construct the correct syntax for the if-else statement, or if there's something missing in my code.
<?php
include "../dbcon.php";
session_start();
ob_start();
$sql = mysqli_query($con,"SELECT * FROM clientdocuments WHERE docID = $_POST[docID]");
$rows = mysqli_fetch_array($sql, MYSQLI_ASSOC);
//IF CSS input value is filled
if(!empty($_POST)){
$output = '';
$message = '';
$docID = mysqli_real_escape_string($con, $_POST["docID"]);
$docSIG_Contract = mysqli_real_escape_string($con, $_POST["docSIG_Contract"]);
//I don't get what this "if(isset($_POST["docID"])){" purpose (Sorry very new to php)
if(isset($_POST["docID"])){
if (!empty($docID)) {
$query = "UPDATE clientdocuments(docID, docSIG_Contract) VALUES('$docID', '$docSIG_Contract');"; //UPDATE ONCE docID ALREADY EXIST ON THE DATABASE
} else {
$query = "INSERT INTO clientdocuments(docID, docSIG_Contract) VALUES('$docID', '$docSIG_Contract');"; //INSERT IF THE docID doesn't exist yet
}
$str = mysqli_query($con,$query);
if(!$str){
echo 'FAILED';
}
}else{
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
}
}
?>
remove this if statment: if (!empty($docID)) {
Make sure that u send with each post update the "docID" value
if(isset($_POST["docID"])) statement checks to see whether the input with the name docID has a value.
if(!empty($_POST)) I am not sure whether this will work, my guess is that you are trying to check whether the request method is POST (if the save button was clicked). For this I use
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
I would then check to see whether docID has a value ie
(isset($_POST["docID"])) OR (!empty($_POST["docID"]))
Difference between isset and !empty
What's the difference between 'isset()' and '!empty()' in PHP?
If there is a value, $query would be the update statement
If there is no value $query would be the insert statement In this situation don't enter the DocID value (because then it would always be 0 which will also cause errors)
Hope that makes sense!
This register form was made by me, but it doesn't do what I want it to do.
I want it to connect to a mysql database and store the information that was given by the form. I want it to hash the $password in md5 and store it in the "gebruikers" table. Please don't reply with "Damn, you have no idea what you are doing" or something like that. I am learning PHP by looking to examples and following tutorials. Please keep in mind that the mysql insert code is not filled in right, because I got stuck a few lines above.
So, my question is: I want to check if the mysql table already contains $email. If it IS already in the mysql table, I want to display an error message that I can place somewhere else in my PHP page. If the email adress given is unique, than the $password should hash into md5 and store into the mysql database, just like the other form entries.
How do I do that?
<?php
// Fetching all the form details
$email = $_POST["email"];
$password = $_POST["password"];
$voornaam = $_POST["voornaam"];
$tussenvoegsel = $_POST["tussenvoegsel"];
$achternaam = $_POST["achternaam"];
$dag = $_POST["dag"];
$maand = $_POST["maand"];
$jaar = $_POST["voornaam"];
$straat = $_POST["straat"];
$postcode = $_POST["postcode"];
$woonplaats = $_POST["woonplaats"];
$cniveau = $_POST["cniveau"];
$oniveau = $_POST["oniveau"];
$voornaam = $_POST["voornaam"];
$aboutme = $_POST["aboutme"];
//Here's where I don't know how to continue
$check = mysql_query("SELECT * FROM `gebruikers` WHERE `email` = '$email'");
if($check === FALSE) {
//there is a user already registered
echo("$email is al in gebruik. <a href='login.php'>Inloggen</a>?");
} else {
//There isn't a username
//mysql_query("INSERT INTO `user` (`id` ,`username` ,`password`) VALUES (NULL , '{$_POST['email']}', MD5( '{$_POST['password']}' ))");
echo("You have been registered!");
}
P.S.: I'm not a native English speaker, so please ignore my grammar mistakes/typos.
First of all, you made a major mistake: There is a SQL-Injection security hole.
Please read this: http://php.net/manual/en/security.database.sql-injection.php
Second, you should use mysqli instead of mysql, because mysql is deprecated.
Your error is that SQL does only return false if the query is invalid, not if there are no results. So the correct way of checking if there are results is to use http://php.net/manual/en/mysqli-result.num-rows.php
$result = mysql_query("SELECT * FROM `gebruikers` WHERE `email` = '$email' LIMIT 1");
if(mysql_fetch_array($result) !== false)
{
...
} else {
....
}
You should also read up on preventing SQL injection.
Maybe you've forgot to set the mysql_connect statement.
But I strongly recommend you stick from now on, with the mysqli_ functionality, since, as Aragon0 said, mysql is deprecated in PHP's newest versions.
Besides, mysqli statements are simpler than the mysql ones, for example you use one statement (mysqli_connect) to connect to your host and select your database at the same time, instead of using separated statements (both mysql_connect and mysql_select_db).
Oh, and no additional service package is required to use it. :)
The code will display the returned values and and if it is greater than one it will return "Yes". But I am having trouble with the WHERE clause in $check. When I take it out the code works just fine but when I add it, the page returns incorrect values. Any ideas what's wrong?
<?php
$con = mysqli_connect("127.0.0.1","root","","lian");
$u= $_GET['username'];
$pw = $_GET['password'];
$check = "SELECT username,password FROM users WHERE username='$u' AND password='$pw'";
$login = mysqli_query($con,$check) or die(mysqli_error($con));
$num_rows = mysqli_num_rows($login);
echo "$num_rows \n";
if (mysqli_num_rows($login) == 1) {
$row = mysqli_fetch_assoc($login);
echo 'Yes';
exit;
}
else {
echo 'No';
exit;
}
Leaving aside the injection vulnerabilities, it may be because of special characters or whitespace. Try trim'ing your GET values.
$u = trim($_GET['username']);
$pwd = trim($_GET['password']);
Are you getting the number of results as 0? Also try echoing the statement in a development environment to check exactly what the statement is.
Try like this
$u= trim(mysqli_real_escape_string($_GET['username']));
$pw = trim(mysqli_real_escape_string($_GET['password']));
$check = "SELECT username,password FROM users WHERE username='$u' AND password='$pw'";
Also I hope you are ensuring unique combination of username and password.
Because suppose there are two entries in your users table
username="abc" password ="12345"
Then mysqli_num_rows() function will return two rows and the
if (mysqli_num_rows($login) == 1)
condition will return false meaning the user desn't exist.
The above comments are valid to improve the security of your code and protect vs sql injection.
Regarding your actual problem if the code executes correctly when you don't have the where clause in place but fails when you do there are a couple of possibilities:
The username or password are wrong - where wrong can mean they have extra whitespace, case insensitivities or that the column names are incorrect(case sensitive database?)
The string you are passing to the server is not displaying correctly.
Check both options by doing an echo of $u, $pw and $check right after you form your SQL string. If it's still not clear then copy whatever is echoed for $check and past it directly into the parser(management studio I guess?) and see what it returns.
Good Luck.