View items in a cart - student project

Hi everyone! I am new to PHP and am creating a prototype for a school project. When I add items to a cart in session they are being added successfully, however, I can’t get them to actually appear in the cart. The cart is created, and the item says “item is already in cart” when I try to add it again.

Parts of this code are pre-written for me from the textbook we’re using, and then I am to edit them to use the MySQL database and the design of my project and scope. This is what I have for the page where my cart appears:

<?php
session_start();
//check session first
if (!isset($_SESSION['email'])){
    include ("../includes/header.php");
    echo "You are not logged in!<br /><br />";
    echo ("<a href=../Home/index.php class='buttons2'>Login</a>"); 
    exit();
}else{
    //include the header
    include ('../includes/header.php');
    require_once ('../../mysqli_connect.php');
    echo ("<center>"); 
    echo ("<h3>Rentals</h3>");
    echo ("<div class='buttons2'><a href=searchformrentals.php class='buttons2'>Search Rentals</a></div>"); 

    // Check if the form has been submitted (to update the cart):
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {

        // Change any quantities:
        foreach ($_POST['qty'] as $k => $v) {

            // Must be integers!
            $pid = (int) $k;
            $qty = (int) $v;

            if ( $qty == 0 ) { // Delete.
                unset ($_SESSION['cart'][$pid]);
            } elseif ( $qty > 0 ) { // Change quantity.
                $_SESSION['cart'][$pid]['quantity'] = $qty;
            }
        } // End of FOREACH.
    } // End of SUBMITTED IF.

    // Display the cart if it's not empty...
    if (!empty($_SESSION['cart'])) {

        // Retrieve all of the information for the prints in the cart:
        require ('../../mysqli_connect.php'); // Connect to the database.
     $q = "SELECT title, price FROM movies, categories WHERE movies.category_id = categories.id IN (";
        foreach ($_SESSION['cart'] as $pid => $value) {
            $q .= $pid . ',';
        }
        $q = substr($q, 0, -1) . ') ORDER BY title ASC';
        $r = mysqli_query ($dbc, $q);
       
        // Create a form and a table:
        echo '<form action="index.php" method="post">
        <table border="0" width="90%" cellspacing="3" cellpadding="3" align="center">
        <tr>
            <td align="left" width="30%"><b>Title</b></td>
            <td align="left" width="30%"><b>Price</b></td>
            <td align="center" width="10%"><b>Qty</b></td>
            <td align="right" width="10%"><b>Total Price</b></td>
        </tr>
        ';

        // Print each item...
        $total = 0; // Total cost of the order.

        while ($row = mysqli_fetch_array ($r, MYSQLI_ASSOC)) {
     
            // Calculate the total and sub-totals.
            $subtotal = $_SESSION['cart'][$row['title']]['quantity'] * $_SESSION['cart'][$row['price']];
            $total += $subtotal;

            // Print the row:
            echo "\t<tr>
            <td align=\"left\">{$row['title']}</td>
            <td align=\"left\">{$row['price']}</td>
            <td align=\"right\">\${$_SESSION['cart'][$row['title']]['price']}</td>
            <td align=\"center\"><input type=\"text\" size=\"3\" name=\"qty[{$row['title']}]\" value=\"{$_SESSION['cart'][$row['title']]['quantity']}\" /></td>
            <td align=\"right\">$" . number_format ($subtotal, 2) . "</td>
            </tr>\n";

        } // End of the WHILE loop.
        mysqli_close($dbc); // Close the database connection.

        // Print the total, close the table, and the form:
        echo '<tr>
            <td colspan="4" align="right"><b>Total:</b></td>
            <td align="right">$' . number_format ($total, 2) . '</td>
        </tr>
        </table><br />
        <div align="center"><input type="submit" name="submit" value="Update My Cart" /></div>
        </form><p align="center">Enter a quantity of 0 to remove an item.
        <br /><br /><a href="checkout.php" class="buttons2">Checkout</a></p>';
    } else {
        echo '<p>Your cart is currently empty.</p>';
    }   
    echo ("</center></html>"); 
}
echo '</div>';
echo '</div>';
include ('../includes/footer.php');
?>

While this code contains some good programming practices, it is also inconsistent (does the same meaning things in different ways), is repetitive (Don’t Repeat Yourself - DRY), cluttered with unnecessary things (Keep It Simple - KISS), and could be better organized so that troubleshooting problems would be easier and the html document would be complete and valid.

In general, the code on a page should be laid out in the following order -

  1. Initialization - define, require, create, … things your page needs, such as the session_start() statement, a database connection, configuration values, …
  2. Post method form processing code - a post method form should be used for things that create/update data on the server or perform an action such as sending an email.
  3. Get (method) business logic (get inputs may exist for a post method request) - get/create data needed to display the dynamic content on the web page.
  4. Html document/template - using simple php code or an actual template system, produce the html document, using the data produced from the above sections of code.

Here’s a laundry list of things that can be cleaned up/improved in the code, most of which will actually simplify it, perhaps to the point where you/others you ask to look at it will be able to see what’s causing the current problem -

  1. The value you store in the session variable to indicate if/who is logged in should be the user id (auto-increment integer primary index from the users table.) This will allow the user information, such as the email address to be edited, and the change will take effect on the next page request, without needing the user to log out and back in.
  2. To display the cart, it is not necessary for the user to be logged in. When you go to ‘checkout’ step, to save the items in the database as an ‘order’, the user will need to register/login.
  3. Include, require_once, and require (you are using all three, just use require everywhere for those things that your code must have for it to work) are not functions and the () you are putting around the file name are unnecessary clutter and cause php to reevaluate the expression that it is already evaluating.
  4. Likewise, echo is not a function. Don’t use () and be consistent, you have lines with and without the ().
  5. The ‘require’ statement for the header.php file should only exist once. When you organize the code as suggested, the repetition of statements like this should go away.
  6. By exit(ing) in the login check code, you are not outputting a complete html document. Again, organizing the code as suggested will make it easier to produce a complete html document.
  7. If you do have a case where you are exit(ing) inside a conditional block of code, there’s no need for an else {} branch for that conditional statement, since the code won’t execute past the exit statement if the main condition was true. This will simplify and eliminate a level of indentation in your code.
  8. Only make one database connection. By first using ‘require_once’, than ‘require’ later in the code for the database connection, you are actually making two connections. The suggested organization for the code will help to eliminate this type of problem.
  9. In general, don’t echo line after line of ‘static’ content. Only echo things which contain dynamic values.
  10. As mentioned in the suggested organization, the post method form processing code should not be inside the html document. After successfully completing the post method form processing code (no errors), you should redirect to the exact same URL of the page to cause a get request - PRG (Post, Redirect, Get.) This will prevent the browser from tying to resubmit the form data if you reload the page or browse away from and back to the page. If you want to display a one-time success message, store it in a session variable, then test, display, clear that session variable at the appropriate point in the html document.
  11. If someone submits a negative quantity to your form processing code, what will happen? What should happen in that case?
  12. Because the conditional ‘failure’ logic is often much simpler than the success logic, reversing a conditional test and putting the failure logic first will make it easier to see what code is doing.
  13. When building a list of things, it is simpler if you just implode() an array. Since the cart’s main array keys are the pid values, for the existing code, using implode(',',array_keys($_SESSION['cart'])) (which works correctly even if there’s only one element in the cart) eliminates a loop, a concatenation statement, and a substr() statement.
  14. You should always use a prepared query when supplying external, unknown, dynamic values to a query when it gets executed. While you are casting the inputs as integers when you are storing them in the cart, you don’t necessary know what changes someone may make to your code in the future. Always assume that data values can be anything and cannot be trusted. Using a prepared query actually simplifies the sql query syntax, making it easer to write error free queries.
  15. When you switch to use a prepared query, use a FIND_IN_SET() comparison in the query, since it uses a single prepared query place-holder, rather than a separate place-holder for each value in an IN() comparison.
  16. You don’t have any apparent error handling for the database statements that can fail (connection, query, prepare, and execute) and it’s likely that you are getting an sql syntax error from the current sql query. If you use exceptions for database statement errors and in most cases let php catch and handle the exception, php will use its error related settings to control what happens with the actual error information (database statement errors will ‘automatically’ get displayed/logged the same as php errors.)
  17. You should switch to the much simpler PDO extension. The mysqli extension is overly complicated and inconsistent, especially when dealing with prepared queries.
  18. When writing JOIN(ed) queries, use explicate joins with ON conditions, rather than list the join conditions in a WHERE clause. This is where the current problem likely is. You haven’t actually listed a column to use with the IN() comparison. You should also use table alias names in a join query, to simplify the sql syntax.
  19. For html5, leave the whole action=’…’ attribute out of the form tag to cause the form to submit to the same page.
  20. Use up to date html markup and use css for styling. You should also validate the resulting web pages at validator.w3.org
  21. The pid values should be the product ids (auto-increment integer primary index from the product table.) Your code is trying to use the ‘title’ column value to get the quantity from the cart. Since you are casting the pid as an integer when you update the cart, I can guarantee that the title value will never match a pid key in the cart.
  22. Your cart should not and probably doesn’t contain the price. The code getting the price value from the cart both won’t work (should be producing php errors) and using the $row['price'] in one place and $row['title'] in another as the session cart’s index makes no sense. The price you use in the sub-total calculation should just be $row['price'].
  23. When you are echoing html markup, don’t escape quotes in the markup, just use the opposite, single vs double, quote.
  24. In most cases, it is not necessary for you to close database connections, free up prepared query statements, or free up results, since php will destroy all the resources used on a page when the script ends.
  25. Your are outputting the closing </html> tag before the end of the html document. You also have a couple of </div> tags that I don’t see any opening tags for. Using the suggested organization and validating the resulting web page will help with these type of problems.
  26. You might want to use a php variable to hold the currency symbol, so that you can change it, without needing make multiple edits to the code.
  27. Any dynamic data value that you output on a web page needs to have htmlentities() applied to it to help prevent cross site scripting.

Thank you. While I appreciate this great response and it will probably make sense to me once my understanding of PHP is more developed, I did mention that a great deal of this code is provided for us for the purposes of the assignment. The assignment isn’t to re-write the provided code, it’s to modify it slightly. I’ll try to read through your response as best I can… but PHP is very new to me and I think our professor is expecting the majority of the code to remain the same for now. My understanding is that I am just missing a piece somewhere to make the data stored in Session to appear in the cart table.

While that list contains some items that are not absolutely necessary for code that will never see the light of day outside of a programming class, or be put onto a live/public server, the list contains a lot of fundamental programming practices, that will result in code that’s easy to design, write, test, and debug and will get your code to either work or it will tell (display/log) you why it doesn’t, and should have been addressed before expecting you to work on an actual application.

The one item that would probably be of the most help would be to set the mysqli error mode to exceptions, combined with having php’s error related settings set to display all php errors (which should be set in the php.ini on your development system.) To enable exceptions for mysqli errors, add the following line of code before the point where you make the database connection -

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

Here’s an additional point to add to the list - if you are not SELECTing anything from the categories table, there’s no point in using a join query. The movies table contains the title and the price you need to display the contents of the cart.

I am trying to work through the list still, and thank you for helping! The movies table does not contain the price. The category the movie is in determines the movie’s price, and that is why there is a join here.

Jumping back to the other list of suggestions, the user does need to be logged in as it would be an employee checking out a movie on behalf of a customer in the store. I apologize as I didn’t provide a lot of context to the project previously.

Doesn’t make complete sense, but in a join query, you should ALWAYS use the table.column syntax, even in the cases where it is not required for the query to work, so that it is clear to anyone reading the query what you are trying to do, without needing to know the definition of all the database tables -

SELECT m.title, c.price FROM movies m JOIN categories c ON ...

A post was split to a new topic: JOIN query

The following code shows all the points that have been made. Note: I removed all the in-line styling and the little bit of css (if code doesn’t work, it doesn’t matter what the output looks like, this example is only to show the functionality); changed some of the td tags to th tags; corrected the colspan value; uses the PDO extension; was only tested with faked data, set in the code, since I don’t have all the parts that would be needed for the session/database code to fully be used.

<?php

// 1. Initialization - define, require, create, … things your page needs, such as the session_start() statement, a database connection, configuration values, …
session_start();

// apply htmlentities to a value
// functions like this would generally be in a .php file that you require when needed
function _ent($val)
{
	return htmlentities($val,ENT_QUOTES); // this uses the current/default php character encoding setting
}

// note: all of the following code uses the PDO extension
require 'pdo_connect.php';

$currency = '$';

$errors = []; // array to hold user validation/error messages

// note: functionally, the user doesn't need to be logged in to add to, view, or update the cart.
// if you want to do this, you would qualify the cart update form processing code, the cart display code, and the user navigation based on the existence or absence of a logged in user.
// the OP has indicated an employee would be the user and would therefore need to be logged in to use the system


// 2. Post method form processing code - a post method form should be used for things that create/update data on the server or perform an action such as sending an email.
if(isset($_SESSION['user_id']) && $_SERVER['REQUEST_METHOD'] == 'POST')
{
	// Change any quantities:
	foreach ($_POST['qty'] as $pid => $qty)
	{
		// Must be integers!
		$pid = (int)$pid;
		$qty = (int)$qty;

		if ( $qty == 0 ) { // Delete.
			unset($_SESSION['cart'][$pid]);
		} elseif ( $qty > 0 ) { // Change quantity.
			$_SESSION['cart'][$pid]['quantity'] = $qty;
		}
		// what happens if someone submits a negative number? this is either a user error (you would set a message in the $errors array) or you should treat it the same as a zero and delete the item
	}
	// if there are no errors, success
	if(empty($errors))
	{
		// redirect to the exact same url of this page to cause a get request - PRG Post, Redirect, Get.
		header('Refresh:0');
		exit;
	}
}


// 3. Get (method) business logic (get inputs may exist for a post method request) - get/create data needed to display the dynamic content on the web page.
// get product data corresponding to the cart contents
$cart_data = [];
if(isset($_SESSION['user_id']) && !empty($_SESSION['cart']))
{
	$sql = "SELECT m.id, m.title, c.price
	FROM movies m
	JOIN categories c ON m.category_id = c.id
	WHERE FIND_IN_SET(m.id,?)
	ORDER BY m.title";

	$stmt = $pdo->prepare($sql);
	$stmt->execute([
		implode(',',array_keys($_SESSION['cart']))
	]);
	$cart_data = $stmt->fetchAll();
}


// 4. Html document/template - using simple php code or an actual template system, produce the html document, using the data produced from the above sections of code.
require '../includes/header.php';

// display any specific navigation for a non-logged in user
if(!isset($_SESSION['user_id'])){
?>
	<p>You are not logged in!</p>
	<a href='index.php'>Login</a>
<?php
}

// display any user error messages
if(!empty($errors))
{
	echo '<p>'.implode('<br>',$errors).'</p>';
}

// display the cart
if(isset($_SESSION['user_id']))
{
	if(empty($cart_data))
	{
		echo '<p>The cart is empty.</p>';
	}
	else
	{
		?>
		<form method="post">
			<table>
				<tr>
					<th>Title</th>
					<th>Price</th>
					<th>Qty</th>
					<th>Total Price</th>
				</tr>
				<?php
				$total = 0; // Total cost of the order.
				foreach($cart_data as $row)
				{
					// Calculate the total and sub-totals.
					$qty = (int)$_SESSION['cart'][$row['id']]['quantity'];
					$subtotal = $qty * $row['price'];
					$total += $subtotal;
					
					// apply htmlentities to dynamic values being output on the web page
					$row = array_map('_ent',$row);
					
					echo
					"<tr>
						<td>{$row['title']}</td>
						<td>{$row['price']}</td>
						<td><input type='text' size='3' name='qty[{$row['id']}]' value='$qty'></td>
						<td>".$currency.number_format($subtotal, 2)."</td>
					</tr>";
				}
					// Print the total
					echo 
					'<tr>
						<th colspan="3">Total:</th>
						<th>'.$currency.number_format($total, 2).'</th>
					</tr>';
				?>
			</table>
			<input type='submit' value='Update My Cart'>
		</form>
		<p>Enter a quantity of 0 to remove an item.</p>
		<a href='checkout.php'>Checkout</a>
		<?php
	}
}

require '../includes/footer.php';

Thank you for your effort on this. It’s all very new to me still so this is hard to read and it seems like a total change to the code I was given, which I don’t know would be acceptable for the assignment. Most of what you shared includes things I am not familiar with and I know we haven’t covered. I did test it in the hopes I could use parts of it to fill in the gaps, but I don’t think I understand this well enough to do that because I still received no output and some errors while testing.

I did make some changes to my own code, and I thought it might be helpful to share the page where the movie is added to the cart.

The movies available to rent are displayed in a list pulled from my SQL database, and then the employee can click a button to add one to the cart for rental. That is processed here:

if (isset ($_GET['id']) && filter_var($_GET['id'], FILTER_VALIDATE_INT, array('min_range' => 1))  ) { // Check for a movie ID.

    $id = $_GET['id'];

    // Check if the cart already contains one of these movies;
    // If so, increment the quantity:

    if (isset($_SESSION['cart'][$id])) {
        $_SESSION['cart'][$id]['quantity']++; // Add another.

        // Display a message:
        echo '<p>Another copy of the movie has been added to the cart.</p>';

    } else { // New product to the cart.

        // Get the movie's price from the database:
        require ('../../mysqli_connect.php'); // Connect to the database.

        $q = "SELECT title FROM movies WHERE id=$id";
        $r = mysqli_query ($dbc, $q);       

        if (mysqli_num_rows($r) == 1) { // Valid movie ID.

            // Fetch the information.
            list($price) = mysqli_fetch_array ($r, MYSQLI_NUM);

            // Add to the cart:
            $_SESSION['cart'][$id] = array ('quantity' => 1, 'title' => $title);

            // Display a message:
            echo '<p>The movie has been added to your cart.</p>';

        } else { // Not a valid movie ID.
            echo '<div align="center">This page has been accessed in error!</div>';
        }
        mysqli_close($dbc);
    } // End of isset($_SESSION['cart'][$id] conditional.
} else { // No movie ID.
    echo '<div align="center">This page has been accessed in error!</div>';
}

Then there is my (slightly updated) rental cart, still appearing but not showing anything:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

	foreach ($_POST['qty'] as $k => $v) {
		$pid = (int) $k;
		$qty = (int) $v;
		
		if ( $qty == 0 ) {
			unset ($_SESSION['cart'][$id]);
		} elseif ( $qty > 0 ) {
			$_SESSION['cart'][$id]['quantity'] = $qty;
		}			
	} 		
}

// Display the cart if it's not empty...
if (!empty($_SESSION['cart'])) {

	// Retrieve all of the information for the movies in the cart:
	require '../../mysqli_connect.php';
	$q = "SELECT m.id, m.title, c.price FROM movies m JOIN categories c on m.category_id = c.id IN (";
	foreach ($_SESSION['cart'] as $id => $value) {
		$q .= $id . ',';
	}
	$q = substr($q, 0, -1) . ') ORDER BY m.title ASC';
	$r = mysqli_query ($dbc, $q);
	
	// Create a form and a table:
	echo '<form action="index.php" method="post">
	<table>
	<tr>
		<th><b>Title</b></td>
		<th><b>Price</b></td>
		<th><b>Qty</b></td>
		<th><b>Total Price</b></td>
	</tr>';

	// Print each item...
	$currency = '$';
	$total = 0; // Total cost of the order.
	while ($row = mysqli_fetch_array ($r, MYSQLI_ASSOC)) {
	
		// Calculate the total and sub-totals.
	$subtotal = $_SESSION['cart'][$row['id']]['quantity'] * $_SESSION['cart'][$row['id']]['price'];
	$total += $subtotal;

	// Print the row:
	echo "\t<tr>
	<td align=\"left\">{$row['title']}</td>
	<td align=\"right\">\${$_SESSION['cart'][$row['id']]['price']}</td>
	<td align=\"center\"><input type=\"text\" size=\"3\" name=\"qty[{$row['id']}]\" value=\"{$_SESSION['cart'][$row['id']]['quantity']}\" /></td>
	<td align=\"right\">".$currency.number_format($subtotal, 2) . "</td>
	</tr>\n";
	
	}

	mysqli_close($dbc); 

	// Print the total, close the table, and the form:
	echo '<tr>
			<td colspan="4" align="right"><b>Total:</b></td>
			<td align="right">'.$currency.number_format($total, 2) . '</td>
		</tr>
		</table><br />		
		<div align="center">
			<input type="submit" name="submit" value="Update My Cart" />
		</div>
		</form>
		<p align="center">Enter a quantity of 0 to remove an item.<br /><br />
		<a href="checkout.php" class="buttons2">Checkout</a></p>';

} else {
	echo '<p>The cart is currently empty.</p>';
}

A lot of what you shared was really helpful and I am hoping I can make sense of this enough to make it work! If you have any suggestions based on the code I have, I’d really appreciate it! I would like to understand how the implode function would work here. I think you’re right and that’s probably the way to go, but I don’t understand how to use it in this?

The code I posted was to show the points that were made. You are free to examine, use, or ignore any or all of it.

The current issues in your code are the result of a lack of definition, of what data does/should exist in the cart and what data will be gotten via the query when displaying the cart contents, and mistakes going from one line of code to the next on what values are being used.

You should be getting php errors from the posted ‘add to cart’ code, alerting you to a problem with a variable name mismatch. Since you apparently are not, that means that php’s error related settings are not set up so that php will help you by reporting and displaying all the errors that it detects. This is a fundamental point needed when programming. Php’s error_reporting setting should always be set to E_ALL. When learning, developing, and debugging code/query(ies), you should display php errors, the display_errors setting should be set to ON. These settings should be in the php.ini on your development system. You can use a phpinfo() statement to check what the current settings are.

The problem in the add to cart code, that should be producing php errors, is that you are selecting the title column in the query, storing it in to a variable named $price, when you fetch the data, then trying to use a variable named $tile when adding the element to the session cart.

There’s two problems with this - 1) the only value you need to store in the cart is the quantity (based on the first code in this thread, the ‘update cart’ code, this is what it appeared you were doing and this was okay), and 2) by switching back and forth on what’s being selected and what the variable names are, says you are not actually ‘reading’ what the code/query is doing. You need to take ‘ownership’ of what this code/query(ies) are doing, even if someone else gave you the starting code.

For that particular query, what is its purpose, since this will determine what data to select? Given that the only value you need to store in the cart is the quantity (Keep It Simple), the purpose of that query would be to verify the existence of the summitted id value, which would indicate a programming mistake somewhere if it doesn’t exist. To query to find if data just exists, use a SELECT COUNT(*) … query. This will result in the fastest query and the least amount of code to use the result from the query.

Last point for the ‘add to cart’ code - you should use a post method form, not a link, when creating, updating, or deleting data on the server.


For the ‘display cart’ code, what debugging have you done?

  1. Have you echoed the sql query statement to see if it is correct?
  2. Do you have the line of code I posted that sets the mysqli error mode to exceptions, so that any query error will get displayed (this also requires that php’s error related settings are set up as suggested.) You currently still have the sql syntax error that I previously pointed out and was corrected in the example code I posted.
  3. If a SELECT query doesn’t match any rows of data, you should output a message stating so and then only attempt to loop over the rows of data if they exist.
  4. What is the purpose of the SELECT query in the ‘display cart’ code, as this will determine what data to select? For the SELECTed columns - m.id, m.title, and c.price, what are you going to use each one of them for? You are using $row[‘id’] to get the quantity from the cart, as the checkbox field array index value, and you are using $row[‘title’] to display the title. What are you using $row[‘price’] for, especially since your cart (all versions of the posted code), doesn’t have the price in it? Wouldn’t you use $row[‘price’] to calculate the subtotal and as the displayed unit price?

I’m using Visual Studio Code to edit my code, and I do always get these errors:

image

I Googled them a while back to figure out how to fix it, and followed the instructions I found, but they didn’t make the errors go away. I wasn’t sure if it was worth it to pursue since I’m only taking this one class briefly and the class instructions didn’t mention anything about a special setup to use Visual Studio Code.

Guessing that is why I am not seeing the errors you’re talking about?

I don’t know anything about Visual Studio Code (VSC.)

To execute php/mysql code/queries in a web environment, you need a web server, with php installed, and a database server (MySql/MariaDB.) There are all-in-one packages, such as XAMPP that you can download and install - https://www.apachefriends.org/index.html Installing one of these packages would give you the php executable that VSC is complaining about. The settings that I mentioned would be set in the php.ini that is part of the all-in-one package. There is usually a tab/link as part of the ‘control panel’ that will allow you to edit the php.ini that is being used by the system.

Since parts of your php code appear to be working, i.e. you can display and add items to the cart, I’m going to guess that you already do have a web server, php, and MySql installed on your personal computer (I hope you are not doing this on live web hosting somewhere.)

The startup errors VSC is displaying are about VSC being able to validate the PHP code, by passing it through the PHP command line interpreter. While this is a useful step, it is not how the final php code is/should be executed. The php errors I mentioned are run-time errors, that php will detect, report, and display, when you request the page through a URL on a web server, and if you setup the error_reporting/display_errors settings on that web server/php installation as I have listed.

Yes, I’ve been testing live because the class provides SQL hosting through phpMyAdmin and we’re supposed to connect with an FTP client to upload our php files. I did install XAMPP as you suggested and VSC doesn’t have those errors anymore and I do get some tips now, but I don’t know what to do with XAMPP otherwise. This isn’t mentioned in the course instructions and I have no experience hosting on my own computer at all.

But yes, parts of the code work. Something is being added to session because the table for the cart isn’t there until I click the “rent” button. It’s just that no rows for the movie data actually appear in the cart.

Does each student have their own sub-domain or folder on that server? How do you keep from overwriting the files from other students?

In any case, it is the server you are FTP’ing files to where the php error related settings should be set at. If you don’t have sufficient access to the server to make the changes to the master php.ini, you should be able to create a local php.ini within your personal sub-domain/folder and if you don’t have the ability to do that, you can put these settings into a common .php file that you require into your main .php scripts.

Since you have now installed XAMPP on your computer, you have a localhost development system, where you can (you don’t need to do this is you don’t want to) test your code on your computer, without needing to constantly upload all the files just to see the result of each change. XAMPP includes a web server, with php, a database server, and phpmyadmin (which just is a database management .php script.) You would need to create any database tables and insert the data into the localhost database server. You can do this by using phpmyadmin on the live server to export the information, than import it on the localhost system.

Each student as their own thing. I don’t see any other student files, everything is mine.

Anyway, I played around with XAMPP a bit and got into the phpMyAdmin area. When I upload my schema, exported from phpMyAdmin, it stops after one table and says the next table has malformed keys. The table it’s referencing, customers, which I’ve never had any problem using from any of the other php code I’ve written for previous assignments. If I keep getting distracted with this I think I will miss my deadline and fail the assignment, which is pressing very near to due time.

It’s too bad its an online course with no access to an instructor or tutor. They just give me assignments and I am required to kind of self-teach and then turn them in by a certain due date… but it’s a lot harder than I expected.

Thank you for your help with this, I know it’s out of scope for the original question. Hopefully I can begin to understand what I have but I don’t have any examples or experience to really work with on it and it seems so advanced for what we’ve done so far, which is why I keep thinking the solution must be something simple that I’m missing.

You can set the error settings in your code (this won’t show php syntax errors.) Ideally, add this to an existing .php script file you are already require’ing into your main php pages -

ini_set("display_errors", "1");
error_reporting(E_ALL);

There’s a chance that these statements have been disabled on the live server. If they work, you should see php errors about undefined variables in the ‘add to cart’ code. This, plus the mysqli_report(…) line of code I gave above in this thread should now display database statement errors, which will probably help with your current problem.

That the server isn’t already setup, that the importance of getting php to help you by displaying errors, and the need for error handling for database statements wasn’t some of the first things covered is concerning.

The reason no one has posted ‘fixed’ code, isn’t because we cannot determine what the problem is, it’s because there’s very little learning involved in copy/pasting things you see. Programming is an activity where you must ‘get’ what each line of code/query is doing, so that you know what it is contributing to the overall goal, and so that you be able to determine if it even belongs or where it belongs in the program.

I could not get those errors going and I assume it’s blocked on the server. However, I fixed the cart and it’s pulling my data now.

My guess as to why they aren’t really teaching proper code, local server setup, and php error handling is because this class is more about project management. It’s supposed to give us a very small taste of what our developers will be doing so we kind of understand, but the majority of the class is on using MS Project and writing up contract scopes to manage project workflow and keep developers on track for our future clients.

Thank you for your help! It’s all be very informative and insightful!

Sponsor our Newsletter | Privacy Policy | Terms of Service