How to retrieve a query using PDO inside a function

Question

I have seen similar questions but none of them actually fix this problem. I am trying to have a query in a function:

function retrieve() {
    try {
    $resultsall1 = $conn->prepare("SELECT productName, productVendor, SUBSTRING(productDescription, 1, 150), quantityInStock, buyPrice, productcat, MSRP FROM products LEFT JOIN productlines ON products.productLine = productlines.productLine");

    $resultsall1->execute();
    } catch (exception $e) {
        echo "Unable to retrieve results";
    }
    $productsAll1 = $resultsall1->fetchAll();
    return $productsAll1;
}

And the problem comes when I need to call this function to retrieve the information, what do I do? I have seen the following, which I tried, but I cant find the answer. Using this without a function does work.

$productAll2 = retrieve();
        foreach ($productAll2 as $Pitem) {
            if ($Pitem['productcat'] == $_GET["cat"]) {
                echo "<div class='Pitem'><img src='Assets/Images/products/"
                .$Pitem['productName']
                .".jpg'><h2>"
                . $Pitem['productName']
                . "</h2><p><b>Description: </b>"
                . $Pitem['SUBSTRING(productDescription, 1, 150)']
                . "...</p><p><b>Product Vendor: </b>"
                .$Pitem['productVendor']
                . "<p><b>Quantity in Stock: </b>"
                .$Pitem['quantityInStock']
                . "<p><b>Price: </b>"
                .$Pitem['buyPrice']
                . "k$<p><b>MSRP: </b>"
                .$Pitem['MSRP']
                ."</p></div>";
            }
        }

Thank you for the help. Also, What is the difference between $conn->prepare and $pdo->prepare ? Thank you for all your help. Keep in mind that I am new to this PHP and PDO so go easy on me :)


Show source
| function   | pdo   | php   2017-01-06 23:01 1 Answers

Answers to How to retrieve a query using PDO inside a function ( 1 )

  1. 2017-01-06 23:01

    In this function of yours, you refer to $conn which you have not bothered to define inside that function:

    function retrieve() {
        try {
        $resultsall1 = $conn->prepare("SELECT productName, productVendor, SUBSTRING(productDescription, 1, 150), quantityInStock, buyPrice, productcat, MSRP FROM products LEFT JOIN productlines ON products.productLine = productlines.productLine");
    
        $resultsall1->execute();
        } catch (exception $e) {
            echo "Unable to retrieve results";
        }
        $productsAll1 = $resultsall1->fetchAll();
        return $productsAll1;
    }
    

    You must either pass the variable $conn in as a parameter or declare it as a global variable using the global keyword inside the function:

    global $conn
    

    See the docs on variable scope.

Leave a reply to - How to retrieve a query using PDO inside a function

◀ Go back