0

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;
   }
1
  • Do you want the num_hardcover has the result? Commented Oct 30, 2016 at 13:08

2 Answers 2

2

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]); 
   }
Sign up to request clarification or add additional context in comments.

1 Comment

works like a charm...only thing is I didn't see it until I had spent an hour going in loops thanks
0

You can do accessing the array eg:

while ($row = $statement->fetchAll(PDO::FETCH_ASSOC)) {
   echo $row["num_hardcover"] . '<br />;
}

5 Comments

@Fred-ii- . thanks .. .. i have just edit .. hope is the right solution
let's see what the OP has to say. PDO isn't my strongest when it comes to converting an array to int.
You got to love those "moments of silence" eh? Well, we'll see who gets the "green" in about 4 mins. ;-)
@Fred-ii- .. i have a lot of green flag .. in a day.. but this time could be that the green is for others .. .. but i . don't like much the wait .. .
Yeah, it's the "waiting" and not knowing if answers given are what they're looking for, leaving people wondering if what they posted works for them or not, in turn taking the word "guesswork" to a higher/new level.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.