php sqlsrv_query stored procedure with naming parameters - php

Im using php 5.4 with sqlsrv extension and I'm trying to call this sample stored procedure (NorthWind database):
create PROCEDURE [dbo].[GetCategories]
#CategoryID int = null
AS
SELECT * from dbo.Categories where CategoryID= IsNull(#CategoryID,CategoryID)
And I'm using this sqlsrv_query syntax:
$sql = "{ call dbo.GetCategories (?)}";
$catID=2;
$params = array($catID);
$stmt = sqlsrv_query( $conn, $sql,$params);
I want to specify parameter name and value in $params, just like this:
$sql = "dbo.GetCategories";
$catID=2;
$params = array("#CategoryID"=>$catID);
$stmt = sqlsrv_query( $conn, $sql,$params);
It return this error: String keys are not allowed in parameters arrays.
How can i solve this problem?
Thanks

I found this solution using PDO:
$dbh = new PDO('sqlsrv:server= ...');
$sql = "{CALL dbo.GetCategories (#CategoryID=:CategoryID)}";
$stmt = $dbh ->prepare($sql);
$stmt->bindParam('CategoryID', $catID, PDO::PARAM_INT);
$stmt->execute();
$results = array();
do {
$results []= $stmt->fetchAll();
} while ($stmt->nextRowset());
echo '<pre>';
echo($results[0][0]['CategoryID'] . ', '.
$results[0][0]['CategoryName'] . ', '.
$results[0][0]['Description']);
echo '</pre>';
$stmt->closeCursor();
unset($stmt);

You can't use associative arrays for binding values to SQL parameters. The elements in the array must be in the same order as the parameters.

Related

Iteration error when fetching mysqli data with php [duplicate]

I am trying to do an extremely simple query using mysqli. It is driving me mad!
I just want $data to be an array of the values from the sql query.
This is my code...
$req = $app->request();
$hashtag = $req->get('hashtag');
require_once 'Slim/lib/database.php';
$db = connect_db();
$statement = $db->prepare("SELECT `content` FROM `posts` WHERE `content` LIKE ?");
$newhashtag = '%#' . $hashtag . '%';
$statement -> bind_param("s", $newhashtag);
$statement -> execute();
$statement -> bind_result($result);
while ( $row = mysqli_fetch_array($statement) ) {
$data[] = $row;
}
print_r($data);
$statement -> close();
I just get an error mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given and it doesn't make a difference using $result or $statement on the fetch_array
You can try this:
$statement = $db->prepare("SELECT `content` FROM `posts` WHERE `content` LIKE ?");
$newhashtag = "%#$hashtag%";
$statement->bind_param("s", $newhashtag);
$statement->execute();
$result = $statement->get_result();
while ($row = $result->fetch_assoc())
{
$data[] = $row;
}
This uses the get_result() function, which is used to get the result from a prepared statement.
This is initialised outside the while loop and assigned to a new variable, in this instance $result.
Then $result->fetch_assoc() is assigned to $row and can be accessed within the loop. Accessing each column as a key from the array such that $row["content"] would return the content from each row under that column
To get the result object from the prepared statement you can use get_result(). This object can then be iterated with a foreach loop.
$statement->execute();
$result = $statement->get_result();
foreach ($result as $row) {
print_r($row);
}
If you need to fetch all rows into an array, you can use fetch_all().
$statement->execute();
$result = $statement->get_result();
$data = $result->fetch_all(MYSQLI_ASSOC);
print_r($data);
You can also fetch the data by binding each column to a variable. First, you specify a variable you want to be populated using bind_result() and then you call fetch() to populate that variable.
$statement->execute();
$statement->bind_result($content);
while ( $statement->fetch() ) {
// Every time fetch is called a value from the next row will be inserted into $content
$data[] = $content;
}
print_r($data);

mysqli prepared statement with while loop

I am trying to do an extremely simple query using mysqli. It is driving me mad!
I just want $data to be an array of the values from the sql query.
This is my code...
$req = $app->request();
$hashtag = $req->get('hashtag');
require_once 'Slim/lib/database.php';
$db = connect_db();
$statement = $db->prepare("SELECT `content` FROM `posts` WHERE `content` LIKE ?");
$newhashtag = '%#' . $hashtag . '%';
$statement -> bind_param("s", $newhashtag);
$statement -> execute();
$statement -> bind_result($result);
while ( $row = mysqli_fetch_array($statement) ) {
$data[] = $row;
}
print_r($data);
$statement -> close();
I just get an error mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given and it doesn't make a difference using $result or $statement on the fetch_array
You can try this:
$statement = $db->prepare("SELECT `content` FROM `posts` WHERE `content` LIKE ?");
$newhashtag = "%#$hashtag%";
$statement->bind_param("s", $newhashtag);
$statement->execute();
$result = $statement->get_result();
while ($row = $result->fetch_assoc())
{
$data[] = $row;
}
This uses the get_result() function, which is used to get the result from a prepared statement.
This is initialised outside the while loop and assigned to a new variable, in this instance $result.
Then $result->fetch_assoc() is assigned to $row and can be accessed within the loop. Accessing each column as a key from the array such that $row["content"] would return the content from each row under that column
To get the result object from the prepared statement you can use get_result(). This object can then be iterated with a foreach loop.
$statement->execute();
$result = $statement->get_result();
foreach ($result as $row) {
print_r($row);
}
If you need to fetch all rows into an array, you can use fetch_all().
$statement->execute();
$result = $statement->get_result();
$data = $result->fetch_all(MYSQLI_ASSOC);
print_r($data);
You can also fetch the data by binding each column to a variable. First, you specify a variable you want to be populated using bind_result() and then you call fetch() to populate that variable.
$statement->execute();
$statement->bind_result($content);
while ( $statement->fetch() ) {
// Every time fetch is called a value from the next row will be inserted into $content
$data[] = $content;
}
print_r($data);

How to get variable from pdo query? Error showed

I am trying to get variable from pdo query but I got an error and could not figure it out. Error I get is PDO::query() expects parameter 1 to be string, object given.
// first I get variable, and when I echo variable I get good result.
$id=$_POST("kolicina");
$stmt=$conn->prepare("SELECT Kolicina FROM table1 where Kolicina=$id");
$q=$conn->query($stmt);
while($row = $q ->fetch(PDO::FETCH_ASSOC)){
$kolicina=$row["Kolicina"];
}
echo $kolicina;
Use instead:
id=$_POST("kolicina");
$stmt=$conn->prepare("SELECT Kolicina FROM table1 where Kolicina=:id");
$stmt->execute(array('id' => $id));
the :id is binded to $id on the execute statement.
And to fetch the result use:
$stmt->fetch(PDO::FETCH_ASSOC);
First read here PHP MANUAL PDO
Second what you did there is wrong.
$id = $_POST['yourvarfromform'];
$stmt = $conn->prepare("SELECT * FROM table1 WHERE Kolicina = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_STR) // if it's string you can check on pdo manual because you can use int and others.
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $key => $value {
// Run Some Code Here
}
Change your code to be like this:
$stmt=$conn->prepare('SELECT Kolicina FROM table1 where Kolicina = :id');
$array = array('id' => $id);
$stmt->execute($array);
And you can fecth all results like this:
$result = $stmt->fetchAll();
print_r($result);
?>

PDO method for mysql_fetch_assoc()?

I used to do :
$resource = mysql_query("SELECT * FROM table WHERE id = " . $id);
$user = mysql_fetch_assoc($resource);
echo "Hello User, your number is" . $user['number'];
I read that mysql statements are all deprecated and should not be used.
How can i do this with PDO?
The first line would be :
$stmt = $db->prepare("SELECT * FROM table WHERE id = " . $id); // there was an aditional double quote in here.
$stmt->execute(array(':id' => $id));
What about the mysql_fetch_assoc() function?
I am using php
You can use (PDO::FETCH_ASSOC) constant
Usage will be
while ($res = $stmt->fetch(PDO::FETCH_ASSOC)){
....
}
Here's the reference (documentation precisely) : http://www.php.net/manual/en/pdostatement.fetch.php
All well documentned in the manual: http://php.net/manual/en/pdostatement.fetchall.php
As example:
<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?>
There is a nice manual right here.
From which you can learn what you don't need to set fetch mode explicitly with every fetch.
...and even what with PDO you don't need no arrays at all to echo a number:
$stmt = $db->prepare("SELECT number FROM table WHERE id = ?");
$stmt->execute(array($id));
echo "Hello User, your number is".$stmt->fetchColumn();
This is a nice tutorial:
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$stmt = $db->query("SELECT * FROM table");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_dump($results);
?>
You can use PDO::FETCH_ASSOC for the same.
$stmt = $db->prepare("SELECT * FROM table WHERE id = :id");
$stmt->execute(array(':id' => $id));
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
while($record = $stmt->fetch()) {
//do something
}
You can find a good tutorial here

How can I properly use a PDO object for a parameterized SELECT query

I've tried following the PHP.net instructions for doing SELECT queries but I am not sure the best way to go about doing this.
I would like to use a parameterized SELECT query, if possible, to return the ID in a table where the name field matches the parameter. This should return one ID because it will be unique.
I would then like to use that ID for an INSERT into another table, so I will need to determine if it was successful or not.
I also read that you can prepare the queries for reuse but I wasn't sure how this helps.
You select data like this:
$db = new PDO("...");
$statement = $db->prepare("select id from some_table where name = :name");
$statement->execute(array(':name' => "Jimbo"));
$row = $statement->fetch(); // Use fetchAll() if you want all results, or just iterate over the statement, since it implements Iterator
You insert in the same way:
$statement = $db->prepare("insert into some_other_table (some_id) values (:some_id)");
$statement->execute(array(':some_id' => $row['id']));
I recommend that you configure PDO to throw exceptions upon error. You would then get a PDOException if any of the queries fail - No need to check explicitly. To turn on exceptions, call this just after you've created the $db object:
$db = new PDO("...");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
I've been working with PDO lately and the answer above is completely right, but I just wanted to document that the following works as well.
$nametosearch = "Tobias";
$conn = new PDO("server", "username", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare("SELECT `id` from `tablename` WHERE `name` = :name");
$sth->bindParam(':name', $nametosearch);
// Or sth->bindParam(':name', $_POST['namefromform']); depending on application
$sth->execute();
You can use the bindParam or bindValue methods to help prepare your statement.
It makes things more clear on first sight instead of doing $check->execute(array(':name' => $name)); Especially if you are binding multiple values/variables.
Check the clear, easy to read example below:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname LIMIT 1");
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetch(PDO::FETCH_ASSOC);
$row_id = $check['id'];
// do something
}
If you are expecting multiple rows remove the LIMIT 1 and change the fetch method into fetchAll:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname");// removed limit 1
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetchAll(PDO::FETCH_ASSOC);
//$check will now hold an array of returned rows.
//let's say we need the second result, i.e. index of 1
$row_id = $check[1]['id'];
// do something
}
A litle bit complete answer is here with all ready for use:
$sql = "SELECT `username` FROM `users` WHERE `id` = :id";
$q = $dbh->prepare($sql);
$q->execute(array(':id' => "4"));
$done= $q->fetch();
echo $done[0];
Here $dbh is PDO db connecter, and based on id from table users we've get the username using fetch();
I hope this help someone, Enjoy!
Method 1:USE PDO query method
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
Getting Row Count
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$row_count = $stmt->rowCount();
echo $row_count.' rows selected';
Method 2: Statements With Parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->execute(array($name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Method 3:Bind parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->bindValue(1, $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
**bind with named parameters**
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->bindValue(':name', $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
or
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->execute(array(':name' => $name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Want to know more look at this link
if you are using inline coding in single page and not using oops than go with this full example, it will sure help
//connect to the db
$dbh = new PDO('mysql:host=localhost;dbname=mydb', dbuser, dbpw);
//build the query
$query="SELECT field1, field2
FROM ubertable
WHERE field1 > 6969";
//execute the query
$data = $dbh->query($query);
//convert result resource to array
$result = $data->fetchAll(PDO::FETCH_ASSOC);
//view the entire array (for testing)
print_r($result);
//display array elements
foreach($result as $output) {
echo output[field1] . " " . output[field1] . "<br />";
}

Categories