PHP PDO with Microsoft SQL Server: Prepare Statement issues? - php

I am fairly new to PDO. I am trying to run a query(Microsoft Sql Server). Eventually i am going to add more fields after WHERE.
$complex = 'Shipping';
$username= 'username';
$password = 'password';
try {
$conn = new PDO('sqlsrv:Server=server,1433;Database=dbname', $username, $password);
$query = "SELECT DATA FROM TrimTable WHERE COMPLEX LIKE ?";
$stmt = $conn->prepare($query, array($complex));
$stmt->execute();
while($row = $stmt->fetch())
{
echo "$row\n";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
I keep getting this error:
Fatal error: Call to a member function execute() on a non-object in
What am i doing wrong?
UPDATE
I tried this as well:
try {
$conn = new PDO('sqlsrv:Server=mzrefd39,1433;Database=ger_mapv', $username, $password);
$sth = $conn->prepare("SELECT AREA FROM TrimTable WHERE COMPLEX LIKE ?");
$sth->execute(array($complex));
$data = $sth->fetchAll();
print_r($data);
}
In my page i get Array( ). I am not getting any values?

You can use bindParam() before execute, Try this code
$conn = new PDO('sqlsrv:Server=server,1433;Database=dbname', $username, $password);
$query = "SELECT DATA FROM TrimTable WHERE COMPLEX LIKE ?";
$stmt = $conn->prepare($query); // check $complex is removed from this line
$stmt->bindParam(1, $complex);
$stmt->execute();
Use bindParam(); for condition to execute query for conditions

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 = ?");

Simple PHP MYSQL select statement doesn't return anything

Alright, so I have a simple database with one table, and I have a function which is supposed to get all the rows for that one table:
function get_days() {
global $db;
$query = 'SELECT * FROM days'
. 'ORDER BY idDays';
$statement = $db ->prepare($query);
$statement ->execute();
$the_days = $statement->fetchAll();
//$statement->closeCursor();
return $the_days;
//return $statement;
}
I've checked everything else, everything else functions just fine, including the part of my site where I input data into the table, that insert statement works just fine, so I've narrowed it down to this one select statement.
The problem is in you SQL syntax. You should do this:
function get_days() {
global $db;
$query = 'SELECT * FROM days '
. 'ORDER BY id';
$statement = $db ->prepare($query);
$statement ->execute();
$the_days = $statement->fetchAll();
//$statement->closeCursor();
return $the_days;
//return $statement;
}
The problem is the string concatenation of your query:
$query = 'SELECT * FROM days' . 'ORDER BY idDays';
This results in: SELECT * FROM daysORDER BY idDays
Include a space character instead:
$query = 'SELECT * FROM days' . ' ORDER BY idDays';
You can avoid problems like this with proper error handling:
try{
$statement->execute();
}
catch(PDOException $e){
exit($e->getMessage());
}
You might also want to remove the spaces in:
$db ->prepare($query);
$statement ->execute();
So they become:
$db->prepare($query);
$statement->execute();
This is simple way to select you can use a function for it.
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM days ORDER BY idDays";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//do anything
}
} else {
echo "0 results";
}

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();
}

PHP bindParam not working - blindValue is not the solution

I can't figure this out. I've googled it and a lot of answers refer to blindValue as the solution but I've also tried that with no luck.
The problem is that the SELECT statement is returning zero records but it should return one record. If I hard code the values into the SQL statement it works but passing them in as parameters isn't. Can some one please help me out with this? Thanks.
<?php
function checklogin($email, $password){
try
{
// Connection
$conn;
include_once('connect.php');
// Build Query
$sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = :email AND Password = :password';
// $sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = "a" AND Password = "a"';
// Prepare the SQL statement.
$stmt = $conn->prepare($sql);
// Add the value to the SQL statement
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
// Execute SQL
$stmt->execute();
// Get the data in the result object
$result = $stmt->fetchAll(); // $result is NULL always...
// echo $stmt->rowCount(); // rowCount is always ZERO....
// Check that we have some data
if ($result != null)
{
// Start session
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Search the results
foreach($result as $row){
// Set global environment variables with the key fields required
$_SESSION['UserID'] = $row['pkUserID'];
$_SESSION['Email'] = $row['Email'];
}
echo 'yippee';
// Return empty string
return '';
}
else {
// Failed login
return 'Login unsuccessful!';
}
$conn = null;
}
catch (PDOexception $e)
{
return 'Login failed: ' . $e->getMessage();
}
}
?>
the connect code is;
<?php
$servername = 'localhost';
$username = 'admin';
$password = 'password';
try {
// Change this line to connect to different database
// Also enable the extension in the php.ini for new database engine.
$conn = new PDO('mysql:host=localhost;dbname=database', $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo 'Connected successfully';
}
catch(PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>
I'm connecting to mySQL. Thanks for the help,
Jim
It was a simple but stupid error.
I had a variable called $password also in the connect.php file which was overwriting the $password that I was passing to the checklogin.
Jim

Categories