MySQL PDO: Invalid parameter number: parameter was not defined - php

I'm building a login page where the username can be that of either a student or teacher, where student names are simply numeric (i.e. 45678). I've made a function account_type($user) which just returns "student" if $user is numeric, and "teacher" if otherwise.
Edit: To clarify, students will type in their SID (i.e. 12345) to log in, and so my function account_type() will determine them to be a student. As such, the MySQL query to access a student account is different than the one to access a teacher's account, wherein an email address is required.
The student log in works fine with the named parameters, but when I try using a string and looking for an email, I get the error:
Invalid parameter number: parameter was not defined
I've tried putting quotes around the :user in the query, but that didn't help. I've triple checked that the queries are right, and they work on MySQL. Any ideas what I should do? The obvious answer is to use mysqli or to not use named parameters, but I'm hoping for it to work with named parameters for more complex queries later on.
Here's my code:
try {
$pdo = new PDO($dsn, DB_USERNAME, DB_PASSWORD);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
die("Could not connect to database. " . $e->getMessage());
}
$user = mysqli_real_escape_string($link, $_POST['user']);
$pass = mysqli_real_escape_string($link, $_POST['pass']);
$account_Type = account_type($user);
if ($account_Type == "student") {
$query = "SELECT id, password FROM students WHERE sid = :user";
}
else if ($account_Type == "teacher") {
$query = "SELECT id, password FROM staff WHERE email = :user";
}
$stmt = $pdo->prepare($query);
$stmt->execute([
':user' => $user
]);
Thanks in advance!

There are two functions:
mysqli_real_escape_string which is supported in PHP 5 and 7 and must be used with mysqli: http://php.net/manual/en/mysqli.real-escape-string.php
And mysql_real_escape_string which was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0 and you can use withou a mysqli connection: http://php.net/manual/en/function.mysql-real-escape-string.php
In the comments of your question you posted a link that uses the mysql_real_escape_string but in your code you are using the mysqli_real_escape_string
So if you are using < PHP 7 or early you can use mysql_real_escape_string to improve your security without mysqli, like this:
$user = mysql_real_escape_string($_POST['user']);
but if you are using > PHP 7 then you must use mysqli, like in the example below:
<?php
//create a connection
$mysqli = new mysqli("localhost", "root", "", "school");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//mysqli_real_escape_string is the procedural version of the function below
$user = $mysqli->real_escape_string('1');
$pass = $mysqli->real_escape_string('student1');
//verify if is a student or teacher
$is_student = is_numeric($user);
if ($is_student == true) {
$query = "SELECT sid, name, password FROM students WHERE sid =? AND password =?";
}
else {
$query = "SELECT sid, name, password FROM staff WHERE email =? AND password =?";
}
if ($stmt = $mysqli->prepare($query)) {
if($is_student){
//i for integer and s for string
$stmt->bind_param("is", $user, $pass);
}else{
//s for string and s for string
$stmt->bind_param("ss", $user, $pass );
}
$stmt->execute();
$stmt->bind_result($sid, $name, $password);
$stmt->fetch();
printf("sid: %s; name: %s; password: %s\n", $sid, $name, $password);
$stmt->close();
}
Hope this helps.

Related

What does the "Unrecognised SQL statement" mean when I am trying to use IF NOT EXISTS?

I am getting the error on line 26 as shown by my browser.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "tut";
$conn = mysqli_connect($servername, $username, $password, $database);
if (!$conn) {
die("Database connection failed: ".mysqli_connect_error());
}
if (isset($_POST['register']))
{
$user = $_POST['username'];
$pass = $_POST['password'];
$pass2=$_POST['password1'];
if(empty($username)||empty ($password)||empty($password1)){
echo "Oops! Can't leave any field blank";
}
elseif($pass!=$pass2){
echo "Passwords don't match";
}
else{
$phash = sha1(sha1($pass."salt")."salt");
$sql=IF NOT EXISTS (SELECT * FROM users WHERE username = '$user')
INSERT INTO users (id, username, password) VALUES ('', '$user', '$phash')
ELSE
RAISERROR 'Username exists, please select a different one';
$result = mysqli_query($conn, $sql);
}
}
?>
Is this not a correct way of writing the IF NOT EXISTS statement. Also when I try to execute this directly in XAMPP I get Unrecognised SQL statement error!
This is how to do it, I have test it and it works:
$sql = "
INSERT INTO users (username, password)
SELECT * FROM (SELECT '$user', '$phash') AS tmp
WHERE NOT EXISTS (
SELECT username FROM users WHERE username = '$user'
) LIMIT 1;
";
This solution is inspired from this answer.
The problem is that you can not combine PHP and MySQL statement like you did, you need to encapsulate all MySQL statements in quote ".
What comes RAISERROR, it is not MySQL function, it belongs to Microsoft.
You could easily make php if statement that checks if $sql contain valid username and return your message. That part is left to your fantasy.
XAMPP has no thing to do with the error, it just a software that provides an Apache and MySQL installation for Windows.
Note: P.S. please learn to use parameterized queries, because your
code is vulnerable to SQL injection. thanks to #BillKarwin for mentioning this.

Prepared Statements Select with Variables - php

Trying to just set up something to verify that username = password via num_rows = 1.
Trying to use prepared statements, that I have never used before and i'm missing something. Where does the var in bind_results('s',$variable) come from??
Also, its just not working for me.
<?php
require ($_SERVER['DOCUMENT_ROOT'].'/db-connect.php');
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user = $_POST['username'];
//$user = $mysqli->real_escape_string($user);//
$password = $_POST['password'];
//$password = $mysqli->real_escape_string($password);//
if ($stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ? AND password = ?")) {
$stmt->bind_result('ss', $username);
$stmt->execute();
$result = $stmt->num_rows;
echo $result;
$stmt->close();
}
$mysqli->close();
?>
I see three problems with this:
$stmt->bind_result('ss', $username);
First, bind_result PHP documentation:
"Binds columns in the result set to variables."
I think you're looking for bind_param. PHP documentation:
"Bind variables for the parameter markers in the SQL statement that was passed to mysqli_prepare()."
Second, your statement has two parameter markers (?), your bind statement indicates two strings (ss), but you provide only one variable ($username).
Third, $username is not what you're getting from $_POST['username']. You've assigned that to $user. $username is for your database connection.
I think it should work for you with this line instead:
$stmt->bind_param('ss', $user, $password);

How to authenticate users with credentials in MySQL database

On my form page, I have two textboxes with the names name and password.
When the user hits submit, it sends that data into two columns in a MySQL database named 'name' and 'password'.
After the data is recorded (which is the part I understand and don't need help with), I want the user to be at the sign-in page and type in his/her name and password and only be allowed into the site if the name and password data already exist in the database (part that I don't understand).
Would I use the following query :
SELECT * FROM tablename WHERE name & password = "'$_POST[name]', $_POST[password]'
You should use AND or && instead of just a single ampersand (&), and separate the variables to be binded accordingly to their column name.
You should also consider sanitizing your variables before using them to your queries. You can use *_real_escape_string() to prevent SQL injections.
$name = mysql_real_escape_string($_POST["name"]);
$password = mysql_real_escape_string($_POST["password"]);
"SELECT * FROM tablename WHERE name = '".$name."' AND password = '".$password."'"
But the best recommendation that I can give to you is to use prepared statement rather than the deprecated mysql_*
if($stmt = $con->prepare("SELECT * FROM tablename WHERE name = ? AND password = ?")){ /* PREPARE THE QUERY; $con SHOULD BE ESTABLISHED FIRST USING ALSO mysqli */
$stmt->bind_param("ss",$_POST["name"],$_POST["password"]); /* BIND THESE VARIABLES TO YOUR QUERY; s STANDS FOR STRINGS */
$stmt->execute(); /* EXECUTE THE QUERY */
$noofrows = $stmt->num_rows; /* STORE THE NUMBER OF ROW RESULTS */
$stmt->close(); /* CLOSE THE STATEMENT */
} /* CLOSE THE PREPARED STATEMENT */
For securing password, you could also look at password_hash().
Please Always use Prepared statement to execute SQL code with Variable coming from outside your code. Concatenating variable from user input into SQL code is dangerous ( consider SQL injection ), you could use prepared statement with mysqli or PDO ( recommended ).
Mysqli example:
$mysqli = new mysqli("example.com", "user", "password", "database");
// error check you connection here
$query='select * from tablename where user =? AND password=?';
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ss", $user,$password);
$stmt->execute();
if($stmt->num_rows!=1) {
// check failed
}else{
// check success
}
PDO example (recommended )
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// error check you connection here
$query='select * from tablename where user =? AND password=?';
$stmt = $dbh->prepare($query);
$stmt->bindParam(1,$user);
$stmt->bindParam(2,$password);
$stmt->execute();
if($sth->fetchAll()) {
// check success
}else{
// check failure
}
Additionally you should also consider using some form of 1-way password encryption ( password hashing ) before storing it in your database and compare it to the hash( the most accepted way to do it is using Bcrypt).
You can use something like
SELECT count(*) FROM tablename WHERE name = "'.$_POST[name].' AND password = "'. $_POST[password].'"
You should expect count to be exactly 1 - indicating valid user, 0 - indicating invalid user
Anything greater than 1 should be invalid scenario indicating some kind of inconsistency in your database...
You should assign the variables to name & pass subsequently.
You can try this:
$con = mysqli_connect("localhost","YOURUSER","YOURPASS","YOURDB");
if (mysqli_connect_errno())
{
echo"The Connection was not established" . mysqli_connect_error();
$user
= mysqli_real_escape_string($con,$_POST['user']);
$pass = mysqli_real_escape_string($con,$_POST['password']);
$query = "select * from tablename where user ='$user' AND password='$pass' ";
$run = mysqli_query($con,$query);
$check = mysqli_num_rows($run );
if($check == 0)
{
echo "<script> alert('Password or Email is wrong,try again!')</script>";
}
else
{
//get a session for user
$_SESSION['user']=$user;
// head to index.php; you can just put index.php if you like
echo"<script>window.open('index.php?login=Welcome to Admin Area!','_self')</script>";
}

MySQL query not fetching results (PHP)

I have the following script with an SQL problem which is not working.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "Freepaste";
$conn = mysqli_connect($servername, $username, $password,$dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$user = $_POST['user'];
$pass = $_POST['pass'];
echo $user." ".$pass;
$stmt = $conn->prepare("SELECT * FROM users where users.username= ? AND users.password = ?");
$stmt->bind_param('ss', $user, $pass);
$stmt->execute();
$result = $stmt->get_result();
printf("Errormessage: %s\n", $mysqli->error);;
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<br>id: " . $row["username"]." Password ".$row["password"]. "<br>";
}
}
else {
echo "<br>0 results <br>";
printf("Errormessage: %s\n", $mysqli->error);
}
mysqli_close($conn);
?>
The statement without the "where" clause gets me all the results, so I know the keys are right. Also, I ran the query in MySQL and it is working fine. I tried adding "" to $user and $pass, still not working. I checked the names in HTML, they are correct too. What am I missing?
Here's the link to the HTML:
http://pastebin.com/CWLuafVq
You are missing the quotes (although you are saying you tried) i think it should have worked. Your query should be:
SELECT * FROM users where users.username='$user' AND users.password='$pass'
Your query is vulnerable to SQL injection and in order to avoid it (and avoid hassle like requiring quotes in SQL statement), you should use PreparedStatement.
For your example, you just need to put single quotes around $user and $pass in the query.
BUT!!!!!! Your query is open to SQL injection. You should change the way you write queries. Use bound parameters instead, then you can almost forget about that issue.
Example:
$stmt = $conn->prepare("SELECT * FROM users where users.username= ? AND users.password = ?");
$stmt->bind_param('ss', $user, $pass);
$stmt->execute();
$result = $stmt->get_result();
See here for more information
As it stands, when your variables are put into the sql query, it ends up looking like this WHERE users.username=goelakash AN.... Without quotes around username and password, mysql is going to think you're comparing two columns.
What your query needs to look like is this.
$sql = "SELECT * FROM users where users.username=\"$user\" AND users.password=\"$pass\"";
Do yourself a huge favor, and put mysqli_error() calls after your calls to mysqli_query(). These will tell you exactly what mysql is crying about.
It is also worth noting that your queries are open to sql injection and you should take a look at prepared statements to mitigate that.
make sure your database password is 'root'? If yes then follow the query string
$sql = "SELECT * FROM users WHERE users.username='$user' AND users.password='$pass'";
just replace it. I think it will work fine :)

PHP Prepare statement error

Fatal error: Call to a member function prepare() on a non-object in
/home/melazabi/public_html/assigment/The/include/process.php on line
15
// check if the username exists in the database
// line 15 is the one below:
$statement = $conn->prepare("select * from users where username=? AND password=?");
//prepare statment is to try to stop sql injection
$statement->bindParam(1, $un);
$statement->bindParam (2, $pw);
$statement->execute();
As per what you shown in your comment:
You're using a mysql_* based connection
$conn = mysql_connect('localhost','admin','admin') or die("error2"); mysql_select_db("admin") or die("error");
with a PDO query.
You need to use: (replace with actual DB credentials)
$dbname = 'admin';
$username = 'admin';
$password = 'admin';
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
The error is telling you the your query failed for any number of reasons.
Your db connection failed, either authentication problem or complete failure to connect.
Your params are not defined correctly.
you can debug this by
print_r($statement->errorInfo());
this will give you what the error returned by sql was.
also make user variables are set. If i were to guess not having seen the rest of your code. you probably want $_POST['un'] and $_POST['pw']
echo $un;
echo $pw;
edit
connect to db:
$conn = new PDO('mysql:host='SERVERADDRESS';dbname=DBNAME;charset=utf8', 'USERNAME', 'PASSWORD');
then your query
$statement = $conn->prepare("select * from users where username=? AND password=?");
//prepare statment is to try to stop sql injection
$statement->bindParam(1, $un);
$statement->bindParam (2, $pw);
$statement->execute();

Categories