MySQLi Prepared Statement Query Issue - php

I'm relatively new to MySQLi prepared statements, and running into an error. Take this code:
$user = 'admin';
$pass = 'admin';
if ($stmt = $mysqli->query("SELECT * FROM members WHERE username='$user' AND password='$pass'"))
{
echo $stmt->num_rows;
}
This will display "1", as it should.
This next piece of code though, returns "0":
$user = 'admin';
$pass = 'admin';
if ($stmt = $mysqli->prepare("SELECT * FROM members WHERE username=? AND password=?"))
{
$stmt->bind_param("ss", $user, $pass);
$stmt->execute();
echo $stmt->num_rows;
}
Any ideas why?

you need to call store_result() before you get the number of rows
$user = 'admin';
$pass = 'admin';
if ($stmt = $mysqli->prepare("SELECT * FROM members WHERE username=? AND password=?"))
{
$stmt->bind_param("ss", $user, $pass);
$stmt->execute();
$stmt->store_result(); // add this line
echo $stmt->num_rows;
}

Related

How to get count using prepared statment in PHP?

$con = mysqli_connect("localhost","root","","uploads");
if($con)
{
$sql = "SELECT COUNT(id) FROM products";
$obj = mysqli_query($con,$sql);
if(is_object($obj))
{
$rows = mysqli_fetch_row($obj);
$totalrows = $rows[0];
enter code here
}else{
echo "not object";
}
}else
{
echo "db issue";
}
This code is perfectly fine but i want to perform same operation using prepared statment.i have tried but could't get the same result using prepared statment. what i have to do?
Check out the following solutions
//db configuration
$server = 'localhost';
$dataBase = 'uploads';
$UserName = 'root';
$Password = '';
PHP MySQLi Prepared Statement
$con = mysqli_connect($server, $userName, $password, $dataBase);
$sql = "SELECT COUNT(id) FROM products";
$stmt = mysqli_prepare($con, $sql);
if(mysqli_stmt_execute($stmt)) {
mysqli_stmt_bind_result($stmt, $totalRows);
mysqli_stmt_fetch($stmt);
echo $totalRows;
}
PHP MySQLi Object-oriented
$con = new mysqli($server, $userName, $password, $dataBase);
$stmt = $con->query("SELECT COUNT(id) FROM products");
if ($stmt->num_rows > 0) {
while($row = $stmt->fetch_row()) {
$totalRows = $row[0];
echo 'Total number of rows is '.$totalRows;
}
}
$stmt->close();
PHP MySQLi with Object-oriented Prepared Statement
$con = new mysqli($server, $userName, $password, $dataBase);
$stmt = $con->prepare("SELECT COUNT(id) FROM products");
$stmt->execute();
$stmt->bind_result($totalRows);
$stmt->fetch();
echo 'Total number of rows is '.$totalRows;
$stmt->close();
PHP PDO with Prepared Statement
try {
$con = new PDO("mysql:host=$server;dbname=$dataBase;", $userName, $password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $con->prepare("SELECT COUNT(id) FROM products");
$stmt->execute();
$totalRows = $stmt->fetchColumn();
echo 'Total number of rows is '.$totalRows;
} catch(PDOException $e){
echo $e->getMessage();
die();
}

Getting results of statement

I have made this example code:
$db = new mysqli("localhost","root","password","xxx");
$statement = $db->prepare("SELECT name, password FROM persons WHERE name=? LIMIT 1");
$statement->bind_param('s', "kevin");
$statement->execute();
if($statement->num_rows){
$statement->bind_result($dbname, $dbpassword);
$statement->free_result();
};
echo $dbname;
echo $dbpass;
How can use/get $dbname and $dbpassword directly without using something like:
while($statement->fetch()){
echo $dbname;
}
I want to use $dbname and dbpassword directly.
What is the best approach? What am I doing wrong.
I found the answer:
I needed to store the result (Store the result (to get properties))
I needed to fetch the result (Fetch results from a prepared statement into the bound variables) Gladfully without a while loop.
$db = new mysqli("localhost","root","password","xxx");
$statement = $db->prepare("SELECT name, password FROM persons WHERE name=? LIMIT 1");
$statement->bind_param('s', "kevin");
$statement->execute();
$statement->store_result(); // this is what I was missing
if($statement->num_rows){
$statement->bind_result($dbname, $dbpassword);
$statement->fetch(); // this is what I was missing
$statement->free_result();
echo $dbname;
echo $dbpass;
};

Getting user and encrypted password from datebase

i got the following code:
public function getUserByNameAndPassword($name, $password) {
$stmt = $this->conn->prepare("SELECT salt FROM `users` WHERE name = ?");
$stmt->bind_param("s", $name);
if ($stmt->execute()) {
$stmt->store_result();
$salt = $stmt->get_result();
}
$encryptedpassword = $this->checkhashSSHA($salt,$password);
$stmt = $this->conn->prepare("SELECT * FROM `users` WHERE name = ? AND encrypted_password = ?");
$stmt->bind_param("ss", $name, $encryptedpassword);
if ($stmt->execute()) {
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
}
else {
return false;
}
}
And the following constructor:
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$db = new Db_Connect();
$this->conn = $db->connect();
}
I'm trying to get user from datebase but it is not working at all, i already tried many things, checked my syntax multiple times but i can't find my mistake. Anybody has an idea?
Edit: Changed code and added log but the log doesent report anything.

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

Retrieve value from column in table using PDO and MySQL

Im using the following to log my users in,
/*** select the users name from the database ***/
$dbh = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("SELECT * FROM access_users
WHERE id = :phpro_user_id");
$stmt->bindParam(':phpro_user_id', $_SESSION['user_id'], PDO::PARAM_INT);
$stmt->execute();
$username = $stmt->fetchColumn();
if($username == false)
{
$message = 'Access Error';
}
else
{
// done
}
I want to retrieve the users level value, which is a column in my table only im unsure how to do this with PDO?
I've tried...
print $result->level;
As it's impossible to get from your question, what column you ant to retrieve, assuming it is called "username":
$stmt = $dbh->prepare("SELECT username FROM access_users WHERE id = ?");
$stmt->execute(array($_SESSION['user_id']));
$username = $stmt->fetchColumn();
This is how fetchColumn() works.
But if you want to get all the user info, and among it, level and username, you have to retrieve usual way, a whole row.
$stmt = $dbh->prepare("SELECT * FROM access_users WHERE id = ?");
$stmt->execute(array($_SESSION['user_id']));
$row = $stmt->fetch();
if(!$row['level'])
{
$message = 'Access Error';
}
echo "Hello ".$row['username'];
Try the following:
$stmt = $dbh->prepare("SELECT user_id,level FROM access_users
WHERE id = :phpro_user_id");
//rest of the code up until here
$result = $stmt->fetchColumn(1);
print("level= $result\n");

Categories