PHP Prepared Statement Problems [duplicate] - php

This question already has answers here:
mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement
(2 answers)
Closed 1 year ago.
slowly getting used to PHP prepared statements, however still get this error
"Warning: mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement in C:\Users\PC\Documents\XAMPP\htdocs\login.php on line 20".
<?php
$mysqli = new mysqli('localhost', 'c3337015', 'c3337015', 'members');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(isset($_GET['loginEmail'])){
session_start();
$stmt = $mysqli->prepare("SELECT Email FROM members WHERE Email=? AND Password=? LIMIT 1");
$email = $_GET['loginEmail'];
$password = $_GET['loginPassword'];
$password = sha1($password);
$stmt->bind_param('ss', $email, $password);
$stmt->execute();
$stmt->bind_result($email, $password);
$stmt->store_result();
if($stmt->num_rows == 1) //To check if the row exists
{
while($stmt->fetch()) //fetching the contents of the row
{$_SESSION['Logged'] = 1;
$_SESSION['Email'] = $email;
header('Location: index.php');
exit();
}
}
else {
echo "Wrong Username or Password!";
}
$stmt->close();
}
else
{
echo "Something went Wrong";
}
$mysqli->close();
?>

$stmt->bind_result($email, $password);
You are binding 2 variables, but only asking for one: SELECT Email FROM members.
I'd also suggest using different variables for bind_result, as it and bind_param both work on references.
$stmt->bind_result($userEmail);

Related

PHP will not insert user data into SQL? [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
How can I prevent SQL injection in PHP?
(27 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 4 years ago.
I have created this for a user registration. I am testing this to be input into the SQL database prior to going further. For some reason, this will not input into my database. Any ideas?
I appreciate your assistance.
<?php
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
$email = $_POST['email'];
if (!empty($uid) || !empty($pwd) || !empty($email)) {
$host = "localhost";
$dbUsername = "connectg";
$dbPassword = "";
$dbname = "my_connectg";
//create connection
$conn = new mysqli($host, $dbUsername, $dbPassword, $dbname);
if (mysqli_connect_error()) {
die('Connect Error('. mysqli_connect_errno().')'. mysqli_connect_error());
} else {
$SELECT = "SELECT email From users Where email = ? Limit 1";
$INSERT = "INSERT Into users (uid, pwd, email) values(?, ?, ?)";
//Prepare statement
$stmt = $conn->prepare($SELECT);
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($email);
$stmt->store_result();
$rnum = $stmt->num_rows;
if ($rnum==0) {
$stmt->close();
$stmt = $conn->prepare($INSERT);
$stmt->bind_param("ssi", $uid, $pwd, $email);
$stmt->execute();
echo "New record inserted sucessfully";
} else {
echo "Someone already register using this email";
}
$stmt->close();
$conn->close();
}
} else {
echo "All field are required";
die();
}
?>

How to debug the PHP warning "Number of bind variables doesn't match number of fields in prepared statement"? [duplicate]

This question already has answers here:
mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement
(2 answers)
Closed 7 years ago.
This is my PHP code for Android login register app, am getting this in my server address:
Warning: mysqli_stmt_bind_result() [function.mysqli-stmt-bind-result]:
Number of bind variables doesn't match number of fields in prepared
statement in /home/a6546950/public_html/FetchUserdetails.php on line
15
Here is the PHP:
<? php
$con = mysqli_connect("XXX", "XXX", "XXX", "XXX");
mysqli_report(MYSQLI_REPORT_STRICT);
$name = $_POST["name"];
$collegename = $_POST["collegename"];
$batch = $_POST["batch"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "SELECT * FROM LoginList WHERE username = ? AND password =?");
mysqli_stmt_bind_param($statement, "ss", $username, $password);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $name, $collegename, $batch, $username, $password);
$LoginList = array();
while (mysqli_stmt_fetch($statement)) {
$LoginList[name] = $name;
$LoginList[collegename] = $collegename;
$LoginList[batch] = $batch;
$LoginList[username] = $username;
$LoginList[password] = $password;
}
echo json_encode($user);
mysqli_stmt_close($statement);
mysqli_close($con);
?>
The issue is exactly what the error says. You are binding onto 5 variables ($name, $collegename, $batch, $username, $password) using mysqli_stmt_bind_result. Your query is likely selecting more (or possibly less) fields than 5.

PHP: Errors in my code, mainly mysqli_fetch_assoc() expects parameter mysqli_result, object given [duplicate]

This question already has answers here:
mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement
(2 answers)
Closed 1 year ago.
Can somebody help me fix my code?
I am trying to access a database of password hashes and use them to validate the user login, but I get a couple of errors.
<?php
$servername="localhost";
$username = "*****";
$password = "*******";
$dbname = "*****";
$conn = new mysqli($servername,$username,$password,$dbname);
if($conn->connect_error){
die("Connection to database failed: ".$conn->connect_error);
}
$uname=mysqli_real_escape_string($conn, $_POST['entered_username']);
$pw=mysqli_real_escape_string($conn, $_POST['entered_password']);
$stmt=$conn->prepare("SELECT username,password,password_hash FROM users WHERE username=?");
$stmt->bind_param('s',$uname);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($result);
$stmt->fetch();
if(!$stmt){
echo $conn->connect_error();}
if($stmt){
echo 'Connection successful';}
$found=FALSE;
while($row=mysqli_fetch_assoc($stmt))
{
if($password_verify($pw,$row['password_hash'])) {
$found=TRUE;
}
}
if($found){
echo "You have successfully logged in as ".$uname."!";
}
else {
echo "Login as ".$uname." failed!";
}
$stmt->close();
$conn->close();
?>
What I get as output:
Warning: mysqli_stmt::bind_result(): Number of bind variables doesn't
match number of fields in prepared statement in
/****/login3.php on line 27
Connection successful
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result,
object given in /****/login3.php on line 37
Login as admin failed!
Thanks guys! It works now! I changed the bind_result statement and got rid of the fetch statement. Apparently, $stmt is of type mysqli_stmt, not mysqli_result and the mysqli_stmt class doesn't have a method fetch_assoc() defined for it.
$stmt=$conn->prepare("SELECT username,password_hash FROM users WHERE username=?");
$stmt->bind_param('s',$uname);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($user,$password_hash);
$found=FALSE;
while($stmt->fetch())
{
if(password_verify($pw,$password_hash)) {
$found=TRUE;
}
}
You are mixing it up. Try with -
$stmt=$conn->prepare("SELECT username,password,password_hash FROM users WHERE username=?");
$stmt->bind_param('s',$uname);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($result);
if(!$stmt){
echo $conn->connect_error();}
if($stmt){
echo 'Connection successful';}
$found=FALSE;
while($row=$stmt->fetch_assoc();)
{
if($password_verify($pw,$row['password_hash'])) {
$found=TRUE;
}
}
you have to bind the columns, as it has to match number of fields requiring:
check this out:
<?php
$servername="localhost";
$username = "*****";
$password = "*******";
$dbname = "*****";
$conn = new mysqli($servername,$username,$password,$dbname);
if($conn->connect_error){
die("Connection to database failed: ".$conn->connect_error);
}
$uname=mysqli_real_escape_string($conn, $_POST['entered_username']);
$pw=mysqli_real_escape_string($conn, $_POST['entered_password']);
$stmt=$conn->prepare("SELECT username,password,password_hash FROM users WHERE username=?");
$stmt->bind_param('s',$uname);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($username,$password,$password_hash);
$stmt->fetch();
if(!$stmt){
echo $conn->connect_error();}
if($stmt){
echo 'Connection successful';}
$found=FALSE;
while($row=mysqli_fetch_assoc($stmt))
{
if($password_verify($pw,$password_hash)) {
$found=TRUE;
}
}
if($found){
echo "You have successfully logged in as ".$uname."!";
}
else {
echo "Login as ".$uname." failed!";
}
$stmt->close();
$conn->close();
?>

PHP/MySQL: Check if username exists

I'm a beginner in php and I want to check if the username entered already exists.
Here is my code.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if (isset($_POST['submit'])) {
include "connect.php";
ValidateUser();
}
function ValidateUser()
{
if (!empty($_POST['username']) AND !empty($_POST['password'])) {
$queryrow=mysqli_query("SELECT * FROM websiteusers WHERE username = '$_POST['username']'");
if ($rows=mysqli_num_rows($queryrow)=0) {
RegisterUser();
}
}
function RegisterUser() {
echo "works up to here";
}
?>
It doesn't even give me an error despite turning error reporting on.
Have you even initialized a mysqli_connect?
$Connection = mysqli_connect("host","user","pass","database");
Then pass it to a function which uses mysqli_query() by:
function foo ($DB){
mysqli_query($DB,"QUERY HERE");
// Do other stuff
return /* Whatever you wish to return here*/
}
foo($Connection);
What you are trying to achieve can be done very easily with the following code. A bigger concern is security. It is good practice to both sanitize your input every time the user has a chance to input text.
Also, using prepared query's will put yet another layer of security.
Although this isn't using your provided code directly, I believe it is good to teach good habits.
If you have any questions feel free to ask.
$username = $_POST['username']; <-- sanitize this
$message = null;
$mysqli = new mysqli("localhost", "user", "password", "database");
$stmt = $mysqli->prepare("SELECT username FROM websiteusers WHERE username=?");
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($usernamesql);
$stmt->fetch();
if ($stmt->num_rows() > 0) {
RegisterUser();
} else {
$message .= 'username already exists';
}
Later on when you require more items to be queried, or more results to be bound:
$stmt = $mysqli->prepare("SELECT username,password,other1,other2 FROM websiteusers WHERE username=?");
$stmt->bind_param('s', $username); <-- the "s" means the argument is a strings, if a argument is stored as an int use "i", but one character for each argument is required.
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($usernamesql);
$stmt->fetch();
Multiple Arguments:
$stmt = $mysqli->prepare("SELECT username,password,other1,other2 FROM websiteusers WHERE username=? AND authenticated=?");
$stmt->bind_param('si', $username,$isauthenticated); <-- second argument is a INT or BOOL
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($usernamesql,$passwordsql,$other1sql,$other2sql);
$stmt->fetch();
When your expecting multiple results, and lets say you want to dump them into arrays:
$userarray = array();
$stmt = $mysqli->prepare("SELECT username FROM websiteusers WHERE username=?");
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($usernamesql);
while($stmt->fetch()){
array_push($userarray, $usernamesql);
}
$userarray is now an array of all the results fetched from the database.
Here is the right way to do this:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if (isset($_POST['submit'])) {
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if(check_user($mysqli, $_POST['username']){
registerUser();
}else{
echo 'user exist, cannot register';
}
}
function check_user($conn, $username){
$query = "SELECT * FROM websiteusers WHERE username = ?";
if ($stmt = $conn->prepare($query)) {
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->close();
}
return $stmt->num_rows === 0;
}
function registerUser() {
echo "registering user ...";
}
Read up on prepared statement

Mysqli prepared statements error? [duplicate]

This question already has answers here:
mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement
(2 answers)
Closed 1 year ago.
I've ran into this error with prepared statements, I've just started with prepared statements so go easy on me please, Heres the error:
Warning: mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement in C:\wamp\www\darkhorizons\login.php on line 31
Heres my code:
if (isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
if(isset($username) && isset($password)) {
$mysqli = new mysqli("localhost","root","","phplogin") or die("Couldnt connect!");
if(mysqli_connect_errno()){
echo "Connection failed: ". mysqli_connect_errno();
exit();
}
if($stmt = $mysqli -> prepare("SELECT * FROM users WHERE username =? AND password =? LIMIT 1")){
$stmt -> bind_param("ss", $username, $password);
$stmt -> execute();
$stmt -> bind_result($result);
$stmt -> fetch();
$numrows = mysqli_num_rows($result);
} else {
die("Please enter a username and password!");
}
if($numrows == 1){
$_SESSION['username'] = $_POST['username'];
$_SESSION['loggedin'] = true ;
$query = "SELECT adminflag FROM users WHERE username = '{$_SESSION['username']}' LIMIT 1;";
$result2 = mysqli_query($connect, $query);
$numrows2 = mysqli_num_rows($result2);
if ($numrows2 == 1) {
$_SESSION['isadmin'] = true;
}
header("Location: {$pageLoc}");
exit(); //It's good to use exit or die (same thing) AFTER using header to redirect
} else {
}
}
}
As a side note, Please ignore any mistakes in the code below the prepared statement, im redoing my login script that ive been using to learn.
Going through your code you didn't really need to query you DB twice, you should read the adminflag in that same select.
SELECT * is never a good idea always select specific fields.
And I also noticed you are using two differnt style, I suggest you to stick to the Object oriented approach.
<?php
if (isset($_POST['submit'], $_POST['username'] , $_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$mysqli = new mysqli("localhost","root","","phplogin");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT adminflag FROM users WHERE username = ? AND password = ? LIMIT 1";
if ($stmt = $mysqli->prepare($query)) {
$stmt -> bind_param("ss", $username, $password);
$stmt->execute();
$stmt->store_result();
$numrows = $stmt->num_rows;
printf("Number of rows: %d.\n", $numrows );
if($numrows == 1){
$stmt->bind_result($admin_flag);
$stmt->fetch();
session_start();
if ($admin_flag== 1) {
$_SESSION['isadmin'] = true;
}
$_SESSION['username'] = $username;
$_SESSION['loggedin'] = true ;
header("Location: {$pageLoc}");
}else{
echo 'user not found';
}
}
$stmt->close();
$mysqli->close();
}else{
echo 'required field missing';
}
?>

Categories