Getting individual element from session array php to put through MySQL SELECT statement












2















I'm trying to get an individual element of my array (the product ID) then use a MYSQLi SELECT statement to get the additional information about the product. I've used print_r for testing purposes and everything is stored in the array correctly. I just can't work out how to select the individual item from a nested array in a Session variable and then use that to put it in a SQL statement and then loop through to display the items, as this is for a shopping cart.



Also I tried using mysqli_fetch_array and mysqli_fetch_assoc and both ways it comes up with an error
Here is my code:



if (isset($_GET['add'])) {
echo "true";
$pid = $_GET['add'];
$wasFound = false;
$i = 0;
// If the cart session variable is not set or cart array is empty
if (!isset($_SESSION['cart_array']) || count($_SESSION['cart_array']) < 1) {
// RUN IF THE CART IS EMPTY OR NOT SET
$_SESSION['cart_array'] = array(0 => array('item_id' => $pid, 'quantity' => 1));
} else {
// RUN IF THE CART HAS AT LEAST ONE ITEM IN IT
foreach ($_SESSION['cart_array'] as $each_item) {
$i++;
while (list($key, $value) = each($each_item)) {
if ($key == 'item_id' && $value == $pid) {
// That item is in cart already so let’s adjust its quantity using array_splice()
array_splice($_SESSION['cart_array'], $i-1, 1, array(array('item_id' => $pid, 'quantity' => $each_item['quantity'] + 1)));
$wasFound = true;
} // close if condition
} // close while loop
} // close foreach loop
if ($wasFound == false) {
array_push($_SESSION["cart_array"], array("item_id" => $pid, "quantity" => 1));
}
//print_r ($_SESSION["cart_array"]);
$sql = "SELECT * FROM `products` WHERE `productID` = '$pid'";
$result = mysqli_query(Database::dbConnect(),$sql);
while($row = mysqli_fetch_array($result)) {
$str = <<<EOD
<tbody>
<tr>
<td>{$row['productName']}</td>
<td>{$row['productID']}</td>
<td>'quantity'</td>
<td>{$row['price']}</td>

</tr>
</tbody>
EOD;
echo $str;
}
}


}









share|improve this question























  • "both ways it comes up with an error" Is it the same error? What is it? If the errors are similar but different in some details, you should probably post both. What do you expect to happen? What does happen? What does your print_r show? What's the table definition of products? I'll take a swing at what I think you want, but I'm not sure that I understand what you want to do.

    – mdfst13
    Jan 2 at 3:21
















2















I'm trying to get an individual element of my array (the product ID) then use a MYSQLi SELECT statement to get the additional information about the product. I've used print_r for testing purposes and everything is stored in the array correctly. I just can't work out how to select the individual item from a nested array in a Session variable and then use that to put it in a SQL statement and then loop through to display the items, as this is for a shopping cart.



Also I tried using mysqli_fetch_array and mysqli_fetch_assoc and both ways it comes up with an error
Here is my code:



if (isset($_GET['add'])) {
echo "true";
$pid = $_GET['add'];
$wasFound = false;
$i = 0;
// If the cart session variable is not set or cart array is empty
if (!isset($_SESSION['cart_array']) || count($_SESSION['cart_array']) < 1) {
// RUN IF THE CART IS EMPTY OR NOT SET
$_SESSION['cart_array'] = array(0 => array('item_id' => $pid, 'quantity' => 1));
} else {
// RUN IF THE CART HAS AT LEAST ONE ITEM IN IT
foreach ($_SESSION['cart_array'] as $each_item) {
$i++;
while (list($key, $value) = each($each_item)) {
if ($key == 'item_id' && $value == $pid) {
// That item is in cart already so let’s adjust its quantity using array_splice()
array_splice($_SESSION['cart_array'], $i-1, 1, array(array('item_id' => $pid, 'quantity' => $each_item['quantity'] + 1)));
$wasFound = true;
} // close if condition
} // close while loop
} // close foreach loop
if ($wasFound == false) {
array_push($_SESSION["cart_array"], array("item_id" => $pid, "quantity" => 1));
}
//print_r ($_SESSION["cart_array"]);
$sql = "SELECT * FROM `products` WHERE `productID` = '$pid'";
$result = mysqli_query(Database::dbConnect(),$sql);
while($row = mysqli_fetch_array($result)) {
$str = <<<EOD
<tbody>
<tr>
<td>{$row['productName']}</td>
<td>{$row['productID']}</td>
<td>'quantity'</td>
<td>{$row['price']}</td>

</tr>
</tbody>
EOD;
echo $str;
}
}


}









share|improve this question























  • "both ways it comes up with an error" Is it the same error? What is it? If the errors are similar but different in some details, you should probably post both. What do you expect to happen? What does happen? What does your print_r show? What's the table definition of products? I'll take a swing at what I think you want, but I'm not sure that I understand what you want to do.

    – mdfst13
    Jan 2 at 3:21














2












2








2








I'm trying to get an individual element of my array (the product ID) then use a MYSQLi SELECT statement to get the additional information about the product. I've used print_r for testing purposes and everything is stored in the array correctly. I just can't work out how to select the individual item from a nested array in a Session variable and then use that to put it in a SQL statement and then loop through to display the items, as this is for a shopping cart.



Also I tried using mysqli_fetch_array and mysqli_fetch_assoc and both ways it comes up with an error
Here is my code:



if (isset($_GET['add'])) {
echo "true";
$pid = $_GET['add'];
$wasFound = false;
$i = 0;
// If the cart session variable is not set or cart array is empty
if (!isset($_SESSION['cart_array']) || count($_SESSION['cart_array']) < 1) {
// RUN IF THE CART IS EMPTY OR NOT SET
$_SESSION['cart_array'] = array(0 => array('item_id' => $pid, 'quantity' => 1));
} else {
// RUN IF THE CART HAS AT LEAST ONE ITEM IN IT
foreach ($_SESSION['cart_array'] as $each_item) {
$i++;
while (list($key, $value) = each($each_item)) {
if ($key == 'item_id' && $value == $pid) {
// That item is in cart already so let’s adjust its quantity using array_splice()
array_splice($_SESSION['cart_array'], $i-1, 1, array(array('item_id' => $pid, 'quantity' => $each_item['quantity'] + 1)));
$wasFound = true;
} // close if condition
} // close while loop
} // close foreach loop
if ($wasFound == false) {
array_push($_SESSION["cart_array"], array("item_id" => $pid, "quantity" => 1));
}
//print_r ($_SESSION["cart_array"]);
$sql = "SELECT * FROM `products` WHERE `productID` = '$pid'";
$result = mysqli_query(Database::dbConnect(),$sql);
while($row = mysqli_fetch_array($result)) {
$str = <<<EOD
<tbody>
<tr>
<td>{$row['productName']}</td>
<td>{$row['productID']}</td>
<td>'quantity'</td>
<td>{$row['price']}</td>

</tr>
</tbody>
EOD;
echo $str;
}
}


}









share|improve this question














I'm trying to get an individual element of my array (the product ID) then use a MYSQLi SELECT statement to get the additional information about the product. I've used print_r for testing purposes and everything is stored in the array correctly. I just can't work out how to select the individual item from a nested array in a Session variable and then use that to put it in a SQL statement and then loop through to display the items, as this is for a shopping cart.



Also I tried using mysqli_fetch_array and mysqli_fetch_assoc and both ways it comes up with an error
Here is my code:



if (isset($_GET['add'])) {
echo "true";
$pid = $_GET['add'];
$wasFound = false;
$i = 0;
// If the cart session variable is not set or cart array is empty
if (!isset($_SESSION['cart_array']) || count($_SESSION['cart_array']) < 1) {
// RUN IF THE CART IS EMPTY OR NOT SET
$_SESSION['cart_array'] = array(0 => array('item_id' => $pid, 'quantity' => 1));
} else {
// RUN IF THE CART HAS AT LEAST ONE ITEM IN IT
foreach ($_SESSION['cart_array'] as $each_item) {
$i++;
while (list($key, $value) = each($each_item)) {
if ($key == 'item_id' && $value == $pid) {
// That item is in cart already so let’s adjust its quantity using array_splice()
array_splice($_SESSION['cart_array'], $i-1, 1, array(array('item_id' => $pid, 'quantity' => $each_item['quantity'] + 1)));
$wasFound = true;
} // close if condition
} // close while loop
} // close foreach loop
if ($wasFound == false) {
array_push($_SESSION["cart_array"], array("item_id" => $pid, "quantity" => 1));
}
//print_r ($_SESSION["cart_array"]);
$sql = "SELECT * FROM `products` WHERE `productID` = '$pid'";
$result = mysqli_query(Database::dbConnect(),$sql);
while($row = mysqli_fetch_array($result)) {
$str = <<<EOD
<tbody>
<tr>
<td>{$row['productName']}</td>
<td>{$row['productID']}</td>
<td>'quantity'</td>
<td>{$row['price']}</td>

</tr>
</tbody>
EOD;
echo $str;
}
}


}






php mysql arrays loops session






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 2 at 2:38









user10848582user10848582

111




111













  • "both ways it comes up with an error" Is it the same error? What is it? If the errors are similar but different in some details, you should probably post both. What do you expect to happen? What does happen? What does your print_r show? What's the table definition of products? I'll take a swing at what I think you want, but I'm not sure that I understand what you want to do.

    – mdfst13
    Jan 2 at 3:21



















  • "both ways it comes up with an error" Is it the same error? What is it? If the errors are similar but different in some details, you should probably post both. What do you expect to happen? What does happen? What does your print_r show? What's the table definition of products? I'll take a swing at what I think you want, but I'm not sure that I understand what you want to do.

    – mdfst13
    Jan 2 at 3:21

















"both ways it comes up with an error" Is it the same error? What is it? If the errors are similar but different in some details, you should probably post both. What do you expect to happen? What does happen? What does your print_r show? What's the table definition of products? I'll take a swing at what I think you want, but I'm not sure that I understand what you want to do.

– mdfst13
Jan 2 at 3:21





"both ways it comes up with an error" Is it the same error? What is it? If the errors are similar but different in some details, you should probably post both. What do you expect to happen? What does happen? What does your print_r show? What's the table definition of products? I'll take a swing at what I think you want, but I'm not sure that I understand what you want to do.

– mdfst13
Jan 2 at 3:21












1 Answer
1






active

oldest

votes


















0














Try replacing $was_found with



$cart_product = null;


And replace your for loop and if with (same first line):



foreach ($_SESSION['cart_array'] as $each_item) {
if ($each_item['item_id'] != $pid) {
continue;
}

$cart_product = $each_item;
}

if (isset($cart_product)) {
$cart_product['quantity']++;
} else {
$cart_product = array('item_id' => $pid, 'quantity' => 1);
array_push($_SESSION['cart_array'], $cart_product);
}


You should not have to loop through the contents of $each_item. The item ID should be available directly if your format is what is shown in the first part of the outer if.



Incidentally, this would be a lot easier if you defined a product class instead of arrays. You could have a cart object which you could query for cart_product objects.



Then replace



            <td>'quantity'</td>


with



            <td>{$cart_product['quantity']}</td>


I'm not at all clear how your SQL query relates to this.



Unrelated to your question, but



        $pid = $_GET['add'];


followed by



            $sql = "SELECT * FROM  `products` WHERE  `productID` = '$pid'";


is horribly insecure. See How can I prevent SQL injection in PHP?






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54000624%2fgetting-individual-element-from-session-array-php-to-put-through-mysql-select-st%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Try replacing $was_found with



    $cart_product = null;


    And replace your for loop and if with (same first line):



    foreach ($_SESSION['cart_array'] as $each_item) {
    if ($each_item['item_id'] != $pid) {
    continue;
    }

    $cart_product = $each_item;
    }

    if (isset($cart_product)) {
    $cart_product['quantity']++;
    } else {
    $cart_product = array('item_id' => $pid, 'quantity' => 1);
    array_push($_SESSION['cart_array'], $cart_product);
    }


    You should not have to loop through the contents of $each_item. The item ID should be available directly if your format is what is shown in the first part of the outer if.



    Incidentally, this would be a lot easier if you defined a product class instead of arrays. You could have a cart object which you could query for cart_product objects.



    Then replace



                <td>'quantity'</td>


    with



                <td>{$cart_product['quantity']}</td>


    I'm not at all clear how your SQL query relates to this.



    Unrelated to your question, but



            $pid = $_GET['add'];


    followed by



                $sql = "SELECT * FROM  `products` WHERE  `productID` = '$pid'";


    is horribly insecure. See How can I prevent SQL injection in PHP?






    share|improve this answer




























      0














      Try replacing $was_found with



      $cart_product = null;


      And replace your for loop and if with (same first line):



      foreach ($_SESSION['cart_array'] as $each_item) {
      if ($each_item['item_id'] != $pid) {
      continue;
      }

      $cart_product = $each_item;
      }

      if (isset($cart_product)) {
      $cart_product['quantity']++;
      } else {
      $cart_product = array('item_id' => $pid, 'quantity' => 1);
      array_push($_SESSION['cart_array'], $cart_product);
      }


      You should not have to loop through the contents of $each_item. The item ID should be available directly if your format is what is shown in the first part of the outer if.



      Incidentally, this would be a lot easier if you defined a product class instead of arrays. You could have a cart object which you could query for cart_product objects.



      Then replace



                  <td>'quantity'</td>


      with



                  <td>{$cart_product['quantity']}</td>


      I'm not at all clear how your SQL query relates to this.



      Unrelated to your question, but



              $pid = $_GET['add'];


      followed by



                  $sql = "SELECT * FROM  `products` WHERE  `productID` = '$pid'";


      is horribly insecure. See How can I prevent SQL injection in PHP?






      share|improve this answer


























        0












        0








        0







        Try replacing $was_found with



        $cart_product = null;


        And replace your for loop and if with (same first line):



        foreach ($_SESSION['cart_array'] as $each_item) {
        if ($each_item['item_id'] != $pid) {
        continue;
        }

        $cart_product = $each_item;
        }

        if (isset($cart_product)) {
        $cart_product['quantity']++;
        } else {
        $cart_product = array('item_id' => $pid, 'quantity' => 1);
        array_push($_SESSION['cart_array'], $cart_product);
        }


        You should not have to loop through the contents of $each_item. The item ID should be available directly if your format is what is shown in the first part of the outer if.



        Incidentally, this would be a lot easier if you defined a product class instead of arrays. You could have a cart object which you could query for cart_product objects.



        Then replace



                    <td>'quantity'</td>


        with



                    <td>{$cart_product['quantity']}</td>


        I'm not at all clear how your SQL query relates to this.



        Unrelated to your question, but



                $pid = $_GET['add'];


        followed by



                    $sql = "SELECT * FROM  `products` WHERE  `productID` = '$pid'";


        is horribly insecure. See How can I prevent SQL injection in PHP?






        share|improve this answer













        Try replacing $was_found with



        $cart_product = null;


        And replace your for loop and if with (same first line):



        foreach ($_SESSION['cart_array'] as $each_item) {
        if ($each_item['item_id'] != $pid) {
        continue;
        }

        $cart_product = $each_item;
        }

        if (isset($cart_product)) {
        $cart_product['quantity']++;
        } else {
        $cart_product = array('item_id' => $pid, 'quantity' => 1);
        array_push($_SESSION['cart_array'], $cart_product);
        }


        You should not have to loop through the contents of $each_item. The item ID should be available directly if your format is what is shown in the first part of the outer if.



        Incidentally, this would be a lot easier if you defined a product class instead of arrays. You could have a cart object which you could query for cart_product objects.



        Then replace



                    <td>'quantity'</td>


        with



                    <td>{$cart_product['quantity']}</td>


        I'm not at all clear how your SQL query relates to this.



        Unrelated to your question, but



                $pid = $_GET['add'];


        followed by



                    $sql = "SELECT * FROM  `products` WHERE  `productID` = '$pid'";


        is horribly insecure. See How can I prevent SQL injection in PHP?







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 2 at 3:49









        mdfst13mdfst13

        545412




        545412
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54000624%2fgetting-individual-element-from-session-array-php-to-put-through-mysql-select-st%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Monofisismo

            Angular Downloading a file using contenturl with Basic Authentication

            Olmecas