Help a desperate university student understand a bit of PHP

FUNCTION 1

<?php  
     session_start();  
    $connect = new mysqli("localhost", "root", "", "test");
    $connect->set_charset("utf8");
    
     if(isset($_POST["add_to_cart"]))
     {  
          if(isset($_SESSION["shopping_cart"]))  
          {  
               $item_array_id = array_column($_SESSION["shopping_cart"], "item_id");  
               if(!in_array($_GET["id"], $item_array_id))  
               {  
                    $count = count($_SESSION["shopping_cart"]);  
                    $item_array = array(  
                         'item_id'               =>     $_GET["id"],  
                         'item_name'               =>     $_POST["hidden_name"],  
                         'item_price'          =>     $_POST["hidden_price"],  
                         'item_quantity'          =>     $_POST["quantity"]  
                    );  
                    $_SESSION["shopping_cart"][$count] = $item_array;  
               }  
               else  
               {  
                    echo '<script>alert("Item Already Added")</script>';  
                    echo '<script>window.location="/Sport/Sportsprodukter/basketballnet.php"</script>';  
               }  
          }  
          else  
          {  
               $item_array = array(  
                    'item_id'               =>     $_GET["id"],  
                    'item_name'               =>     $_POST["hidden_name"],  
                    'item_price'          =>     $_POST["hidden_price"],  
                    'item_quantity'          =>     $_POST["quantity"]  
               );  
               $_SESSION["shopping_cart"][0] = $item_array;  
          }  
     } 
     if(isset($_GET["action"]))  
     {  
          if($_GET["action"] == "delete")  
          {  
               foreach($_SESSION["shopping_cart"] as $keys => $values)  
               {  
                    if($values["item_id"] == $_GET["id"])  
                    {  
                         unset($_SESSION["shopping_cart"][$keys]);  
                         echo '<script>window.location="shoppingcart.php"</script>';  
                    }  
               }  
          }  
     }  
     ?>  

FUNCTION 2

<?php  
 session_start();  
$connect = new mysqli("localhost", "root", "", "test");
$connect->set_charset("utf8");

 if(isset($_POST["add_to_cart"]))
 {  
      if(isset($_SESSION["shopping_cart"]))  
      {  
           $item_array_id = array_column($_SESSION["shopping_cart"], "item_id");  
           if(!in_array($_GET["id"], $item_array_id))  
           {  
                $count = count($_SESSION["shopping_cart"]);  
                $item_array = array(  
                     'item_id'               =>     $_GET["id"],  
                     'item_name'               =>     $_POST["hidden_name"],  
                     'item_price'          =>     $_POST["hidden_price"],  
                     'item_quantity'          =>     $_POST["quantity"]  
                );  
                $_SESSION["shopping_cart"][$count] = $item_array;  
           }  
           else  
           {  
                echo '<script>alert("Produkt allerede tilføjet til kurven")</script>';  
                echo '<script>window.location="/root/Sport/Sportsprodukter/golf.php"</script>';  
           }  
      }  
      else  
      {  
           $item_array = array(  
                'item_id'               =>     $_GET["id"],  
                'item_name'               =>     $_POST["hidden_name"],  
                'item_price'          =>     $_POST["hidden_price"],  
                'item_quantity'          =>     $_POST["quantity"]  
           );  
           $_SESSION["shopping_cart"][0] = $item_array;  
      }  
 } 
 ?> 

This is more of a request than a question. It also might be against the rules, but I am at my wits end. I through tutorials and StackOverflow managed to create the shopping cart above with the ability to add products with function 2. I am afraid however that I depended on the help online too much, and thus lack the experience and understand to know how it truly works. The lack of know-how has now come back to bite me in the ■■■, as I’m nearing the end of my university project in my 2nd semester, and is this project I am required to explain parts of my code.

So I come to ya’ll in the hopes of a merciful soul willing to help me with gaining an understanding of the inner works of this code, and how to best explain it. I’m not looking for the answer per say, but merely a few keywords to allow me to best explain it.

Hello there!

Although you have requested a bit of help in understanding the code, I would like to know if you know the basis of PHP like variables, functions and object oriented programming. This is really important since I could explain the whole code in either easy or hard way based on your knowlede. The hard way could be explaining the basis along with each piece of the above code, the easy one should be just the entire program flow based on conditions.

Hello!

I have a simple general understanding of the basics you mention, so I would imagine simply the program flow explanation would help tremendously!

Thanks so much for taking your time to give me a little assistance!

Okay, let’s do it:

  • Function call

This line calls for some function named session_start whose purpose is unknown for me. I assume it is gonna be related to your project code.

session_start(); 
  • Connecting to the database

As you should know, most programming languages require a SQL connection statement in order to connect and manipulate any database like MySQL, PostgreSQL, MariaDB, etc. In order to understand what is MySQL (since it is the common choice), take a look to Codecademy SQL Course or PHP MySQL Tutorial W3School. The former is very quickly explaining how to do stuff while the CC course is slower but detailed. The most helpful source is the php documentation, that has every PHP function and method like mysqli-construct.

Based on the above doc:

$connect = new mysqli("localhost", "root", "", "test");

This creates a object called $connect that has the connection parameters host, port, username, password, dbname and socket.

The host (localhost) parameter defines either host name or an IP address. The username (root) defines the MySQL user name that you can check on phpmyadmin while password (empty in your case) is related to authentication. At last, dbname (test) is the name of the database you want to work in.

This line:
$connect->set_charset("utf8");

Even though the documentation notes says: “MySQL always assumes the server default charset.”, it is a good practice to set the charset to utf-8 (standard encoding) as you did.

  • Determine if a variable is defined

To do it, there is a built-in function called isset which basically evaluate if a variable is defined on the code. In this case, it is used to verify the variables submitted to the PHP script using the $_POST and $_REQUEST methods. You can check examples at variables external.

Looking at this code block:

if(isset($_POST["add_to_cart"]))
 {  
      if(isset($_SESSION["shopping_cart"]))  
      {  
           $item_array_id = array_column($_SESSION["shopping_cart"], "item_id");  
           if(!in_array($_GET["id"], $item_array_id))  
           {  
                $count = count($_SESSION["shopping_cart"]);  
                $item_array = array(  
                     'item_id'               =>     $_GET["id"],  
                     'item_name'               =>     $_POST["hidden_name"],  
                     'item_price'          =>     $_POST["hidden_price"],  
                     'item_quantity'          =>     $_POST["quantity"]  
                );  
                $_SESSION["shopping_cart"][$count] = $item_array;  
           }  
           else  
           {  
                echo '<script>alert("Produkt allerede tilføjet til kurven")</script>';  
                echo '<script>window.location="/root/Sport/Sportsprodukter/golf.php"</script>';  
           }  
      }  

Basically it check if the variable with name "add_to_cart" was passed to the php script, if true, then it will evaluate another variable called shopping_cart.

If true, then it will execute this line:

$item_array_id = array_column($_SESSION["shopping_cart"], "item_id");

whose function is to store in a variable called $item_array_id one column from the input array $_SESSION["shopping_cart"]. The column you want to return is defined by the second argument (“item_id”). Based on the function array-column, you had passed an associative array (the ones that has column names).

The next line:

if(!in_array($_GET["id"], $item_array_id))  

is used to check if the value exist in the array using the function in_array(array, value to check). Since there is a exclamation mark which denotes a logical NOT operator, the real behaviour would be checking if the values doesn’t exist in the array.

If this doesn’t, then the script creates a new $item_array which has multiple parameters (like item_id, item_name), and store it at the array $_SESSION["shopping_cart"][$count] at the index defined by $count.

If this does, then the script will trigger an alert window.

1 Like

Thanks so much for your help.
I do however have one more question, if you have the time.

In the piece of code under “Function 1” the two arrays confuses me a bit .
If I’m not completely wrong they each create an array within the variable $item_array, with the data from within my database; ID, Name, Price and quantity. At least something in that regard, I’m all the way lost or at least on the right track?

Check my previous answer, got a bit busy while answering but now it is complete.