PHP + MSSQL using PDO with Named Parameters not '?' - php

I'm about to commence building a site using mssql and php.
I plan to use PDO's, however, as I currenlty believe its not possible to use named parameters.
Currently in MySQL I would use named placeholders in my query as such;
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT *
FROM table
LIMIT :numRows";
$st = $this->conn->prepare( $sql );
$st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
However when using MSSQL;
$conn = new PDO("mysql:host=" . DB_HOST .";dbname=" . DB_NAME, DB_USER, DB_PASSWORD);
$sSQLInsert = "SELECT TOP ? *
FROM table";
$aParams = array($iLimit);
$st = sqlsrv_query($dbhandle, $sSQLInsert, $aParams)){}
My worry appears when I have many parameters that need to be bound. Managing the order of them and dancing back and forth between query-parameters doesnt seem ideal.
So my question; is it posible to use named placeholders with MSSQL?

This would be a simple script to write an check, however I found documentation and an example! The answer is YES! Name parameters works with PDO_MSSQL.
https://msdn.microsoft.com/en-us/library/ff628166(v=sql.105).aspx
$stmt = null;
$contact = "Sales Agent";
$stmt = $conn->prepare("select * from Person.ContactType where name = :contact");
$stmt->bindParam(':contact', $contact);
$contact = "Owner";
$stmt->execute();

No You cannot use named Placeholder with sqlsrv_ or any other extension.
This is a feature of PDO only.
I plan to use PDO's, however, as I currenlty believe its not possible
to use named parameters.
You can do it with SQL server:
$sql = "SELECT TOP :numRows *
FROM table";
$st = $this->conn->prepare( $sql );
$st->bindValue( ":numRows", $numRows, PDO::PARAM_INT );
$st->execute();
var_dump($st->fetch());
It is not about the server, it is more about the driver, this PDO advantage since it is compatible with most database. You don't have to change your code, just the connection.

You might have luck looking at the following PDF (auto download of pdf):
http://tinyurl.com/orc2xkc
It has examples binding with variables and arrays.
$sql = ‘select Title,
FirstName,
MiddleName,
LastName
from SalesLT.Customer
where Title = :title and CustomerId<10’;
$query = $conn->prepare($sql);
$title = ‘Mr.’;
$query->bindParam(‘:title’, $title);
$query->execute();
In the meantime I will look up info on mssql driver to use because that apparently plays into it.
Edit ... As for the driver look at the comments under this question:
From PDO to SQLSRV

Many thanks for all the replies to this. After some time I've managed to get it working, so in answer to my question; Yes it is possible to use Named Placeholders with MSSQL.
After installing the SQLSRV PDO extension, placeholders can be used as such;
$database = "";
$server = "";
$conn = new PDO( "sqlsrv:server=$server ; Database = $database", DB_USER, DB_PASSWORD);
$sql = "SELECT * FROM Table WHERE MemberID =:MemberID";
$iMemberID = 5;
$st = $conn->prepare($sql);
//named placeholders within the execute() as an array.
$st->execute(array(':MemberID'=>$iMemberID));
//OR using bind param..
$st->bindParam(':MemberID', $iMemberID);
while ($row = $st->fetch()){
echo "<pre>";
var_dump($row);
echo "</pre>";
}
Thanks to Drew Pierce for the link to the drivers and pdf and everyone else for the help.

Related

PHP SQL prepared select query not returning anything

When I run the code below, it returns nothing. When I explicitly type a string in the place of the '?', it will return the expected result but using the prepared version has not worked for me thus far. I do not believe there is any kind of versioning issue as using prepared statements for INSERT queries has worked for me in the past. What might be the problem here with the prepared statement?
$pdo = new PDO("mysql:host=localhost;dbname=database", $user, $pass);
$sql = "SELECT * FROM table WHERE column LIKE '%?%';";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($_GET['searchterm']));
$results = $stmt->fetchAll();
print_r($results);
You are preparing the value so it isn't behaving as if you just put the string inside of the query.
When preparing a string you don't need to add " or ', that is done for you. You need to add the %'s into the value that you are escaping.
$pdo = new PDO("mysql:host=localhost;dbname=database", $user, $pass);
$sql = "SELECT * FROM table WHERE column LIKE ?;";
$stmt = $pdo->prepare($sql);
$stmt->execute(array("%{$_GET['searchterm']}%"));
$results = $stmt->fetchAll();
print_r($results);

Select 2 columns with PHP PDO Query

I'm pretty new to PHP and PDO and I'm trying to make a simple login system. Now, I'm trying to fetch the id and password from my table to compare with the password that the user input(I'm using one way encryption with salt). So, now the problem is, when I do $password = $stmt->fetchColumn(1) only, my login system works. Now when I try to get the id by doing $id = $stmt->fetchColumn(0) just before $password, I cannot login anymore and I get my "Wrong Username/Password" error.
Now I'm pretty sure that I'm doing something wrong with the fetchColumn but I can't figure it out.
Here's a code snippet that works:
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
//set how pdo will handle errors
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//this would be our query.
$sql = "SELECT id, password FROM user_admin WHERE email = :email";
//prepare the statements
$stmt = $con->prepare( $sql );
//give value to named parameter :email
$stmt->bindValue( "email", $this->email, PDO::PARAM_STR );
$stmt->execute();
$password = $stmt->fetchColumn(1);
Now the following doesn't work. Notice that this happens when I added the $id:
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
//set how pdo will handle errors
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//this would be our query.
$sql = "SELECT id, password FROM user_admin WHERE email = :email";
//prepare the statements
$stmt = $con->prepare( $sql );
//give value to named parameter :email
$stmt->bindValue( "email", $this->email, PDO::PARAM_STR );
$stmt->execute();
$id = $stmt->fetchColumn(0); //That's the problem
$password = $stmt->fetchColumn(1);
Any help is greatly appreciated.
From the documentation:
PDOStatement::fetchColumn — Returns a single column from the next row of a result set
Each time you call fetchColumn it advances to the next row of the result set.
Try using PDOStatement::fetch instead to fetch the entire row as an an array and then accessing the values from there.
$stmt->execute();
$row = $stmt->fetch();
$id = $row[0];
$password = $row[1];

Can't get a prepared statement to print in php

I'm trying to get to grips with mysqli but finding it a struggle compared to the now depreciated mysql. So far with the old methods I've been able to get information back about my tables in an associative array. I'm trying to form a prepared statement and echo the id number back. I would also like to be able to print the whole sql statement that has been binded, but seen as I can't even echo the id number from a single SELECT statement, it is out of the question at the moment.
$db = new mysqli('xxx', 'xx', 'xx', 'xxxx');
$sql = "SELECT user_id, name FROM users WHERE name=?"
$statement = $db -> prepare($sql);
$statement -> bind_param("s", "Emma");
$statement -> execute();
$statement -> bind_result($id, $name);
$output = $statement -> fetch();
echo $output -> $id . " " . $name;
I seem to be getting lost at the line bind_result. I figured if statement is an object, then I should be able to echo them in the form I have devised? When I refresh my page I just get nothing. I have 2 entries in my table and 1 of them does have the name string that is used above.
You think too complex. Just try this:
$db = new mysqli('xxx', 'xx', 'xx', 'xxxx');
$sql = "SELECT user_id, name FROM users WHERE name=?";
$statement = $db->prepare($sql);
$statement->bind_param("s", "Emma");
$statement->execute();
$statement->bind_result($id, $name);
while ($statement->fetch()) {
echo $id . " " . $name;
}
The bind_result() methods takes care that for each $statement->fetch() you execute you get fresh values in the variables $id and $name.
You should take a look at the good documentation of those methods.

First run with PDO getting a Call to a member function bindParam() on a non-object error

This is my first run with PDO, not sure how much better it is than using mysqli but its part of a project I have to create.
Here is the code that is causing the message, all I am trying to do is update pieces of data within my db table.
<?php
//PHP Data Objects
try{
//Connect
$dbh = new PDO('mysql:host=localhost; dbname = company; charset=utf-8','root', 'bachi619');
} catch(PDOException $e){
echo $e->getMessage();
}
$id = 4;
$name = "logan";
$department = "Design";
$sth = $dbh->query("UPDATE employees SET department=:department,last_name=:lastname WHERE id=:id");
//bind
$sth->bindParam(':id',$id);
$sth->bindParam(':lastname',$name);
$sth->bindParam(':department',$department);
$sth->execute();
?>
you have to use
$dbh -> prepare("UPDATE employees SET department=:department,last_name=:lastname WHERE id=:id");
Use prepare for PDO, check this http://in3.php.net/manual/en/pdostatement.bindparam.php
$sth = $dbh->prepare('UPDATE employees SET department=:department,last_name=:lastname WHERE id=:id' );
The dsn should be non spaced
$dbh = new PDO('mysql:host=localhost;dbname=company','root', 'bachi619');
You need to prepare the SQL statement like this
$sth = $dbh->prepare( 'UPDATE employees SET department=:department,last_name=:lastname WHERE id=:id' );
Then bind the parameters
$sth->bindParam(':id',$id);
$sth->bindParam(':lastname',$name);
$sth->bindParam(':department',$department);
and finally execute the query
$sth->execute();

mysql statement not working properly in php code

Following is the code in my script. the $sql statement is properly working when executed in phpmyadmin. But it dosent work in the following code. displaying only one row of data.
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql="SELECT DISTINCT productId FROM bid WHERE userId =:id";
$st = $conn->prepare( $sql );
$st->bindParam( ":id", $_SESSION['id'], PDO::PARAM_INT );
$st->execute();
$data=$st->fetch(PDO::FETCH_ASSOC);
$conn=null;
print_r($data);
In both methods, replace
$data = $st->fetch(PDO::FETCH_ASSOC);
with the code given.
One of the method would be:
$data = $st->fetchAll(PDO::FETCH_ASSOC);
Loop
while( $data = $st->fetch(PDO::FETCH_ASSOC) )
print_r($data);
$conn=null;

Categories