Select or update single value using object oriented mysqli concept - php

I have these two methods which are used to set a flag in my users table.
I can see my setEmailSent function is working well, but isEmailSent always return 0, even its value is set to 1.
class Mydatabase{
function connect(){
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
ini_set("error_log","/log/php_error_log");
error_reporting(E_ALL | E_STRICT);
error_reporting('1');
$connect_error = 'Sorry we are experiencing down time.';
$host = "some.com";
$username = "username";
$password ='password';
$db = "loginregister";
$mysqli = new mysqli($host, $username, $password, $db) or die($connect_error);
return $mysqli;
}
}
function isEmailSent($username){
//**********************************************************************************
// #Desc - will check if email already sent to the user
// #Parms - str username
// #return - details int
//**********************************************************************************
//set up database connection
$db = new Mydatabase();
$mysqli = $db->connect();
//sql statement
$sql = "SELECT `emailSent` FROM `users` WHERE `username` = ?";
//sql prepare statement
$stmt= $mysqli->prepare($sql);
//bind sql params
$stmt->bind_param('s', $username);
//sql execute statement
$stmt->execute();
//store sql result
$stmt->store_result();
//bind sql result
$stmt->bind_result($emailSent);
return $emailSent;
}
function setEmailSent($userName){
//**********************************************************************************
// #Desc - will set that email already sent to the user
// #Parms - str username
//**********************************************************************************
//set up database connection
$db = new Mydatabase();
$mysqli = $db->connect();
$stmt = $mysqli->prepare("UPDATE `users` SET `emailSent`=? WHERE `username`=?");
if ($stmt === false) {
trigger_error($mysqli->error, E_USER_ERROR);
}
$stmt->bind_param('is', $emailSent,$userName);
$emailSent = 1;
$stmt->execute();
}
Can anyone tell me where I am wrong ???

You need to fetch data after bind_result as
$stmt->bind_result($emailSent);
$stmt->fetch();// fetch data
return $emailSent;// then return
Read bind_result

Related

PDO Exception : Tried to bind parameter number 65536. SQL Server supports a maximum of 2100 parameters

I want to read user data. But the result showing like
Tried to bind parameter number 65536. SQL Server supports a maximum
of 2100 parameters.
and here is my code of login.php (test with hard code first)
<?php
header("Content-type: application/json");
include_once 'Database.php';
include_once 'master.php';
//$username = $_GET['username'];
//$password = $_GET['password'];
$username = "angela123";
$password = "admin123";
// get database connection
$database = new Database();
$db = $database->getConnection();
$login = new Master($db);
$stmt = $login->Login($username, $password);
?>
and here is function of Login with parameter username and password
public function Login($username,$password)
{
// select all query
try {
$sqlsrvquery = ("
EXEC [dbo].[GetAllAdmin2]
#username = ':username',
#password = ':password',
");
// prepare query statement
$stmt = $this->conn->prepare($sqlsrvquery);
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$admin_arr = array(
"username" => $row['username'],
"password" => $row['password'],
);
}
if ($row = 0) {
$admin_arr = array(
"status" => false,
"message" => "Invalid Get Data Admin!",
);
}
} catch (Exception $e) {
print_r($e->getMessage());
}
print_r(json_encode($admin_arr));
}
What's going on in this code? actually the result is working properly on SQL Server with SP
Here is the Login SP
ALTER Procedure [dbo].[GetAllAdmin2]
(
#username varchar(55),
#password varchar(55)
)
as
begin
SELECT username, password
FROM Admin
WHERE username = #username and password = #password
and status = 'Active';
END
When execute the SP, the output should be showing username and password
username password
angela123 admin123
And here is database.php
<?php
class Database
{
// specify your own database credentials
private $host = "DESKTOP-N550JK\SQLEXPRESS";
private $user = "sa";
private $database = "Library";
private $password = "sqlserver123";
public $conn;
// get the database connection
public function getConnection(){
try {
$this->conn = new PDO("sqlsrv:Server=" .$this->host . ";database=" . $this->database, $this->user, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $exception) {
echo "Connection error: " . $exception->getMessage();
die("Database Connection Error");
}
return $this->conn;
}
}
?>
any solution of this? thanks
You are using parameter binding in a wrong way and you need to remove the quotes around the placeholders (:username and :password). As is explained in the documetation, the statement template can contain zero or more named (:name) or question mark (?) parameter markers for which real values will be substituted when the statement is executed.
<?php
...
// Statement
$sqlsrvquery = "
EXEC [dbo].[GetAllAdmin2]
#username = :username,
#password = :password
";
$stmt = $this->conn->prepare($sqlsrvquery);
// Parameter bindings
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
// Statement execution
$stmt->execute();
...
?>
An additional example, using the ? parameter marker:
<?php
...
// Statement
$sqlsrvquery = "
EXEC [dbo].[GetAllAdmin2]
#username = ?,
#password = ?
";
$stmt = $this->conn->prepare($sqlsrvquery);
// Parameter bindings
$stmt->bindParam(1, $username, PDO::PARAM_STR);
$stmt->bindParam(2, $password, PDO::PARAM_STR);
// Statement execution
$stmt->execute();
...
?>

Getting error when calling connect as function in prepare statement

EDIT. My error ONLY occurs when calling database connection as a function, if I call my database connection normally, the error do not occur.
I'm trying to execute a prepare statement with database connection as a function so that it can be reused inside other functions. Executing normal SQL codes work when using database connection function but I'm getting errors when I try to use in a prepare statement.
This is my code.
function connect(){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
return $conn;
}
if (connect()->connect_error) {
die("Connection failed: " . connect()->connect_error);
} else {
echo "GOOD";
}
$val = "1";
$stmt = connect()->prepare("SELECT * FROM countries WHERE id = ?");
$stmt->bind_param("s",$val);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['name'];
}
$stmt->close();
When connecting database as a normal variable such as this works.
$stmt = $conn->prepare("SELECT * FROM countries WHERE id = ?");
However, I get "Call to a member function fetch_assoc() on bool" whenever I tried to call my connection as a function.
What am I doing wrong with this code?
After searching for a while and based on this answer, I was able fix my problem by declaring a variable for connection. However, this doesn't explain why directly calling connect doesn't work. Can somebody explain to me why the first way doesn't work?
$db = connect();
$stmt = $db->prepare("SELECT * FROM countries WHERE id = ?");

PDO Username validation if already exists

I have a problem with register form.My form works properly but whenever i try to insert username that already exists it doesn't shows any error.
here is my php register file:
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=dblogin", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($_POST['submit'])) {
$user_name = $_POST['user_name'];
$user_email = $_POST['user_email'];
$user_pass = $_POST['user_pass'];
$hash = password_hash($user_pass, PASSWORD_DEFAULT);
$stmt = $con->prepare("SELECT user_name FROM users WHERE user_name = :user_name");
if($stmt->rowCount() > 0){
echo "exists!";
}
else{
$insert = $conn->prepare("INSERT INTO users (user_name,user_email,user_pass) values(:user_name,:user_email,:user_pass)");
$insert->bindparam(':user_name',$user_name);
$insert->bindparam(':user_email',$user_email);
$insert->bindparam(':user_pass',$hash);
$insert->execute();
}
}
catch(PDOException $e)
{
echo "connection failed";
}
?>
Thanks for your support
You are not executing the select statement. You need to bind params and execute the select statement, try this after the select statemnt.
$stmt->bindparam(':user_name',$user_name);
$stmt->execute();
public function usernameCheck($username)
{
$sql = "SELECT * FROM $this->table where username = :username";
$query = $this->pdo->prepare($sql);
$query->bindValue(':username', $username);
$query->execute();
if ($query->rowCount() > 0) {
return true;
} else {
return false;
}
}
use this one in your project hope it will work... :)
missing } in if statement
if (isset($_POST['submit'])) {
$user_name = $_POST['user_name'];
$user_email = $_POST['user_email'];
$user_pass = $_POST['user_pass'];
$hash = password_hash($user_pass, PASSWORD_DEFAULT);
$stmt = $con->prepare("SELECT user_name FROM users WHERE user_name = :user_name");
if($stmt->rowCount() > 0){
echo "exists!";
}
}else{
}
I notice 4 things (2 of which have been mentioned by others):
First and smallest is you have a spelling error ($con instead of $conn) - don't worry it happens to the best of us - in you first $stmt query which means your select-results becomes NULL instead of 0 - so you rowCount find that it is not over 0 and moves on without your error message
Second you forgot to bind and execute the parameters in your first $stmt query which gives the same result for your rowCount results
Third always clean your variables even when using prepared statements - at a bare minimum use
$conn->mysql_real_escape_string($variable);
and you can with advantage use
htmlspecialchars($variable);
And fourth since you are not doing anything with the database (other than looking) you could simplify your code by simply writing:
$stmt = $conn->query("SELECT user_name FROM users WHERE user_name = '$user_name' LIMIT 1")->fetch();
as I said - no need to bind or execute in the first query
and as a general rule - don't use rowCount - ever - if you have to know the number of results (and in 99% of cases you don't) use count(); but if you as here just want to know if anything at all was found instead use:
if ( $stmt ) {
echo "exists!";
} else {
// insert new user as you did
}
Edit:
Also - as a side note - there are a few things you should consider when you initially create your connection...
Ex:
// Set variables
$servername = "localhost";
$username = "***";
$password = "***";
$database = "***";
$charset = 'utf8'; // It is always a good idea to also set the character-set
// Always create the connection before you create the new PDO
$dsn = "mysql:host=$servername;dbname=$database;charset=$charset";
// Set default handlings as you create the new PDO instead of after
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // And add default fetch_mode
PDO::ATTR_EMULATE_PREPARES => false, // And ALWAYS set emulate_prepares to false
];
// And now you are ready to create your new PDO
$conn = new PDO($dsn, $username, $password, $opt);
Just a suggestion... happy trails

Error when trying to check if email already exists in db

I am receiving this error when I try to check if an email already exists in the database and not sure why:
Fatal error: Call to a member function bind_param() on a non-object in ""
Here is my code:
$email = $_POST['email'];
//prepare and set the query and then execute it
$stmt = $conn2->prepare("SELECT COUNT (*) FROM users WHERE email = ?");
$stmt->bind_param('s', $email);
$stmt->execute();
// grab the result
$stmt->store_result();
// get the count
$numRows = $stmt->num_rows();
if( $numRows )
{
echo "<p class='red'>Email is already registered with us</p>";
}
else
//if we have no errors, do the SQL
I have a seperate database connection file:
function DB2($host='', $user='', $password='', $db='') {
/* Create a new mysqli object with database connection parameters */
$mysqli = new mysqli($host, $user, $password, $db);
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
return $mysqli;
}
Which is linked to this file using:
$conn2 = DB2();
You didn't say what language this is in. I'm assuming it's perl and dbi.
$email = $_POST['email'];
//prepare and set the query and then execute it
$stmt = $conn2->prepare("SELECT COUNT (*) FROM users WHERE email = ?");
$stmt->bind_param($email);
$stmt->execute();
should be
$email = $_POST['email'];
//prepare and set the query and then execute it
$stmt = $conn2->prepare("SELECT 1 FROM users WHERE email = ? fetch first row only");
$stmt->execute($email);
I don't know what store_result() is. I don't think it's part of DBI. You possibly want to do:
#found = $stmt->selectrow_array();
if ($#found) { #email was found }

Cannot get mysqli bind_param bind a variable

I am writing following code to fetch a row from table:
$query = "SELECT ........FROM ............WHERE........AND ID = ?";
$conn = new Connection();
$stmt = $conn->mysqli->prepare($query);
$stmt->bind_param('i', $_SESSION['id']);
$stmt->execute();
echo 'Num rows = '.$stmt->num_rows();
Here's the code for Connection();
define('SERVER', 'localhost');
define('USER', 'root');
define('PASS', 'xxx');
define('DB', 'xxx');
class Connection{
var $mysqli = null;
function __construct(){
try{
if(!$this->mysqli){
$this->mysqli = new MySQLi(SERVER, USER, PASS, DB);
if(!$this->mysqli)
throw new Exception('Could not create connection using MySQLi', 'NO_CONNECTION');
}
}
catch(Exception $ex){
echo "ERROR: ".$e->getMessage();
}
}
}
If I echo the query and run it on Navicat with ID equal to the value of $_SESSION['id'], it does return me a row. But on the web-page, it show output as:
Num rows = 0
What's wrong with the code? Plz note that echo $_SESSION['id'] displays the value.
Thanks
Store your result set with store_result(), then access $stmt->num_rows as a property, not a method. (don't use ())
$query = "SELECT ........FROM ............WHERE........AND ID = ?";
$conn = new Connection();
$stmt = $conn->mysqli->prepare($query);
$stmt->bind_param('i', $_SESSION['id']);
$stmt->execute();
// Call store_result() before accessing num_rows()
$stmt->store_result();
// And access num_rows as a property, not a method
echo 'Num rows = '.$stmt->num_rows;

Categories