mysqli prepared statement with while loop - php

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

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

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

What is the fetch_array equivelant in prepared statements?

I use fetch_array(MYSQLI_ASSOC) with query but it doesn't work with prepared statements. What is the equivalent of that in prepared statements?
Here it is:
$query = "SELECT `users` FROM `table` WHERE `country` = :country";
$stmt = $pdo->prepare($query);
$stmt->execute(array(
':country' => $country
));
$result = $stmt->fetch(PDO::FETCH_ASSOC); // Here you define how results are fetched
or you can define default FETCH MODE to be an associate array, like this:
$pdo = new PDO(...);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$result = $stmt->fetch(); // The same thing now
In addition to the accepted PDO solution, here is one for mysqli:
The first thing to keep in mind is that mysqli prepared statements do not require results to be bound:
Instead of using bound results, results can also be retrieved through the mysqli_result interface. mysqli_stmt_get_result() returns a buffered result set.
So, for example:
$sql = 'SELECT * FROM mytable ORDER BY column LIMIT ?,' . SOME_CONSTANT;
Once you have bound and executed your statement, you can call get_result():
$stmt = $db->prepare($sql);
$stmt->bind_param('i', $int) || die($db->error);
$stmt->execute() || die($db->error);
$result = $stmt->get_result();
At this point we are functionally equivalent to:
if ($result = $db->query($sql)) {
And can call our familiar fetch_array:
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$results[] = $row;
}
Instead of closing the result as we would in the non-prepared equivalent, we close the statement:
$stmt->close();

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

php sqlsrv_query stored procedure with naming parameters

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.

Categories