I have written code with the intention of getting an integer quantity but the result am getting is in an array format.How do I convert that from an array to an integer. Am getting the results from a MySQL database...
Here is my code, Instead of it returning an array I need to get the array value that is at that key
function hcQuantiy($db, $isbn)
{
$query = "SELECT num_hardcover from inventory where isbn = :isbn";
$statement = $db->prepare($query);
$statement->bindValue(':isbn', $isbn);
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
return $result;
}
If you need only one row dont use the method fetchAll which returns an array of rows, use only fetch, which returms an array with one row.
Use PDO::FETCH_NUM for fetch and get the index 0 of the result.
Than convert the result to an int. And there you have your quantity :)
Your code edited:
function hcQuantiy($db, $isbn) {
$query = "SELECT num_hardcover FROM inventory WHERE isbn = :isbn";
$statement = $db->prepare($query);
$statement->bindValue(':isbn', $isbn);
$statement->execute();
$result = $statement->fetch(PDO::FETCH_NUM);
$statement->closeCursor();
return intval($result[0]);
}
You can do accessing the array eg:
while ($row = $statement->fetchAll(PDO::FETCH_ASSOC)) {
echo $row["num_hardcover"] . '<br />;
}
Related
I'm new to mysqli prepared statements. I'm trying to store the results in an associative array so that I can use it further. The results get printed properly before appending to the array but when appended only the first entry gets added. what is the mistake in the approach here?
// order_details_table
$order_details = array();
$invoice = 1234;
$stmt = $con->prepare("SELECT `description`,`amount` FROM order_details_table WHERE invoice_no = ?");
$stmt->bind_param("s", $invoice);
$stmt->execute();
$stmt->bind_result($description,$amount);
while($stmt->fetch())
{
print_r($description." ".$amount); //This prints all the entries for the given query
$row['desc'] = $description;
$row['amount'] = $amount;
$order_details += [$row]; //This appends just the first entry
}
print_r($order_details);
You are using array union operator. From PHP docs:
The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.
Your temporary array has the same key as the array you are collecting into. Both have elements with key 0, so the new row is not added.
To fix it you should use array push operator i.e. [].
while($stmt->fetch())
{
print_r($description." ".$amount); //This prints all the entries for the given query
$row['desc'] = $description;
$row['amount'] = $amount;
$order_details[] = $row; // Append the new row into the array
}
However, I do not recommend such manual approach. mysqli has methods for fetching all the rows at once. You should use fetch_all() instead.
// order_details_table
$invoice = 1234;
$stmt = $con->prepare("SELECT `description`,`amount` FROM order_details_table WHERE invoice_no = ?");
$stmt->bind_param("s", $invoice);
$stmt->execute();
$result = $stmt->get_result(); // Get the result instead of binding
$order_details = $result->fetch_all(MYSQLI_ASSOC);
If you really want to loop on the results one by one and build an array manually then use foreach loop on the mysqli_result object.
// order_details_table
$invoice = 1234;
$stmt = $con->prepare("SELECT `description`,`amount` FROM order_details_table WHERE invoice_no = ?");
$stmt->bind_param("s", $invoice);
$stmt->execute();
$result = $stmt->get_result(); // Get the result instead of binding
$order_details = []; // Instanciate empty array
foreach($result as $row)
{
$newrow['desc'] = $row['description'];
$newrow['amnt'] = $row['amount'];
$order_details[] = $newrow; //This appends just the first entry
}
print_r($order_details);
Dears,
I am trying to fetch all SQL results into an assoc array and then to json but i don't know why i am only getting the last sql row.
<?php
require_once "Xsecure/access.php";
$Arry = array();
$json = array();
$access = new DatabaseAccess();
$sql = $access->Connect();
$stmt = $sql->prepare("select mid from players");
$stmt->execute();
$rowCount = $stmt->rowCount();
$Arry = $result;
while ($result = $stmt->fetchAll(PDO::FETCH_ASSOC) ){
$Arry = $result;
}
// for array data access
foreach($Arry as $row){
$json["mid"] = $row["mid"];
};
// 3. Disconnect db connection
$sql = $access->Disconnect();
// 4. Return json output
echo json_encode($json, JSON_UNESCAPED_SLASHES);
?>
The result output is :
{
"mid": "10"
}
It should mid from 1 to 10 not only the last row. How can i achieve that? what am i missing?
Note: Later on, i want to add extra keys value pairs to the array that are not derived from mySql database so i have to use assoc array.
Thanks in advance,
...
$stmt->execute();
$rowCount = $stmt->rowCount();
$Arry = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($Arry as $row){
$json[]["mid"] = $row["mid"];
};
...
or even just
...
$stmt->execute();
$rowCount = $stmt->rowCount();
$json = $stmt->fetchAll(PDO::FETCH_ASSOC);
...
So whenever I download data from my mysql database, and convert to a JSON array via PHP then display it, I get duplicated values.
I do understand why this is so, but is there any way to remove the numeric duplicates?:/
{"id":"1","0":"1","userId":"23","1":"23","message":"HELLO","2":HELLO"},
{"id":"2","0":"2","userId":"53","1":"53","message":"WOW","2":WOW"}
For PDO use PDO::FETCH_ASSOC flag after query execute
$sth = $dbh->prepare("SELECT col FROM table");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
And for mysql_* functions:
$query = "SELECT col FROM table";
$result = mysqli_query($connection, $query);
$output = array();
while($row = mysqli_fetch_assoc($result)){
$output[] = $row;
}
json_encode($output);
As you've asked, to remove it:
Loop through it, if key is numeric delete.
foreach($array as $key=>$var){
if(is_numeric($key)){
delete $array[$key];
}
}
I believe I am using the PDO fetch functions completely wrong. Here is what I am trying to do:
Query a row, get the results, use a helper function to process the results into an array.
Query
function userName($db){
$q = $db->prepare("SELECT id, name FROM users WHERE id = :user");
$q->bindParam(":user", $user);
$q->execute();
$qr = $q->fetchAll(PDO::FETCH_ASSOC);
if ($qr->rowCount() > 0){
foreach($qr as $row){
$names[$row['id']] = buildArray($row);
}
return $names;
}
}
My custom array building function
function buildArray($row){
$usernames = array();
if(isset($row['id'])) $usernames['id'] = $row['id'];
if(isset($row['name'])) $usernames['name'] = $row['name'];
}
I'm actually getting exactly what I want from this, but when I echo inbetween I see that things are looping 3 times instead of once. I think I am misusing fetchAll.
Any help appreciated
If you're going to build a new array, there's not much point in having fetchAll() build an array. Write your own fetch() loop:
function userName($db){
$q = $db->prepare("SELECT id, name FROM users WHERE id = :user");
$q->bindParam(":user", $user);
$q->execute();
$names = array();
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
$names[$row['id']] = $row;
}
return $names;
}
There's also no need for buildArray(), since $row is already the associative array you want.
I am building a function that acts like Drupal's variable_initialize() function that pulls all key/value pairs into a global variable. I am trying to find the proper parameters I need to put into fetchAll() to remove the row number and get basically what fetch(PDO::FETCH_ASSOC) does but for all returned rows.
I basically want fetchAll to return:
Array {
[name] = value,
[name2] = value2,
[name3] = value3,
}
The variable table is a simple 2 column table (name)|(value)
function variable_init() {
global $db, $variable;
$query = "SELECT * FROM variable";
$stmt = $db->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll(); //need help here
foreach($result as $name => $value) {
$variable[$name] = $value;
}
}
I have tried PDO_COLUMN/PDO_GROUP/etc... but I can't seem to offset the array to remove the row numbers. Thanks.
I think you may be getting confused about what PDOStatement::fetchAll() returns.
The method returns all rows (arrays or objects, depending on fetch style) in an array.
Try this
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
$variable[$row['name']] = $row['value'];
}