Jump to content
Killersites Forums

PHP Shopping Cart - MySql Videos


Chris Evans
 Share

Recommended Posts

Hello

 

I have completed the videos for the PHP shopping cart with paypal. Everythings was fine. After following the 3 follow on videos for changing from XML to MySql i keep getting "Notice: Trying to get property of non-object in C:\wamp\www\vicki_evans\functions\functions.php on line 24"

 

<?php

/* DATABASE */

$server = 'localhost';

$db = 've-products';

$mysqli = new mysqli($server, $db);

 

/* DEFINE GLOBALS */

define('PAYPAL_BUSINESS_VALUE' , 'seller_1309719804_biz@hotmail.com');

define('PAYPAL_FORM_URL','https://www.sandbox.paypal.com/cgi-bin/webscr');

 

/* DEFINE REFERENCES */

require_once 'templates.php';

 

require_once '../classes/shoppingcart.php';

 

//* FUNCTIONS */

session_start();

 

function get_products()

{

global $mysqli;

$result = $mysqli->query("SELECT * FROM products");

 

24 if ($result->num_rows > 0) Line 24

{

$row_num = 0;

while ($row = $result->fetch_object())

{

$products[$row_num]['id'] = $row->id;

$products[$row_num]['title'] = $row->title;

$products[$row_num]['description'] = $row->description;

$products[$row_num]['image'] = $row->image;

$products[$row_num]['price'] = number_format($row->price,2);

$row_num++;

}

return $products;

}

else

{

return FALSE;

}

 

}

 

I have checked back through the videos and everything seems correct, any suggestions?

Link to comment
Share on other sites

Don't you need to pass in the database username/password when creating a new mysqli object? My videos showed the creation of a $user and a $pass variable:

 

$server = 'localhost';
$user = 'root';
$pass = 'root';
$db = 'ks-shoppingcart';
$mysqli = new mysqli($server, $user, $pass, $db);

As far as I understand it, passing in the db username and password is required, and you shouldn't be able to create a valid database object that actually connects to your database without that. http://www.php.net/manual/en/mysqli.connect.php

 

Obviously, if you don't have a valid connection to your database, you won't be able to perform queries that work correctly.

Link to comment
Share on other sites

It shows creating those variables within "Using a MySQL database instead of XML - Part 1" about 7:45. Assuming you are running something like WAMP, MAMP or XAMMP on your local machine (rather than accessing a server online), they come with a default user already set up.

 

"root" is the default username/password when you are running MAMP on Mac OSX. On WAMP (Windows), "root" is the default username and a blank string "" is the default password. If you are running XAMMP, I'm not sure off the top of my head -- you might need to do some research. If you are working on a live server, these variables will obviously contain whatever the correct username/password is that you created when you created your database.

 

If you are running MAMP or WAMP, There's really no need to edit those usernames/passwords as long as the machine you are working on is not a server and you aren't giving other people access to the machine. If you are testing this on a live server, you would obviously want a more secure username/password.

Link to comment
Share on other sites

Any chance of updating the video collection so we can include a quantity item to the products, so when theyre all sold they come off!

I'm pretty busy with some other KS related stuff, but I'll add it to my "potential screencasts" list. I would think it shouldn't be too difficult to do:

 

-- You'd have to update the database to include an "inventory" column, and each item would get a specific number of items that could be sold

-- You'd need to update the various display functions to display the number of items available

-- You'd need to update the product pages to include functionality so that users could select how many items they wanted to purchase

-- You'd need to update the "add to cart" functionality so that when the user specifies the number of items they want, they can't purchase more than the number available

-- The cart would need to display the number of items the user wants to purchase, and allow them to change that number if necessary (see http://www.killersites.com/community/index.php?/topic/5761-shopping-cart for some comments on that)

-- Once items are sold, you'd need to update the total amount of inventory available

-- If the item inventory is "0", either you'd need to update the way products display so that the item doesn't display at all, or have the product display but include a "currently unavailable" message and hide the "add to cart" button.

Link to comment
Share on other sites

I will paste my code in for this feature. You will have to change a few things because i used the shopping cart videos as a guideline...so my variables arent the same as Ben's. Maybe Ben can help you out by changing them for you since he is such a nice guy :) This is update and remove functionality.

 

Add this to your ShoppingCart.php class file:

 

public function remove($pid) {

foreach ($this->GetItems() as $id) {

	if ($id == $pid) {

		unset($this->scart[$pid]);

	}

}

}

public function updQnty($pid, $qnty) {

if ($qnty != 0) {

	$this->scart[$pid] = intval($qnty);

	echo $qnty;

}
else {

	$this->remove($pid);

}

}

 

This goes in your shoppingcart_row function in the templates.php file (I think thats what its called.)

 

This is the full function:

 


function shoppingCart_Row(ShoppingCart $shopcart , $pid, $counter) {

global $db;

$db->query = "SELECT title, body, price, image, token FROM products WHERE token='$pid'";
$result = $db->sql_query($db->query);
$row = $db->fetch_object($result);

$qnty = $shopcart->getItemQnty($row->token);
$price = $row->price;
$total = number_format(($qnty * $price), 2);

return "

	<tr bgcolor='#2C2C2C' style='color: #FFFFFF;'>
		<td align='center' width='20%'>
			<img width='100' height='100' src='$row->image' alt='No Photo Available' />
		</td>
		<td style='vertical-align: top; font-size: 16px; text-decoration: bold;' align='left' width='45%'>
			$row->title
			<input type='hidden' name='item_name_$counter' value='$row->title' />
		</td>
		<td width='10%'><div class='remove'><a href='index.php?page=cart&action=remove&id=$row->token'>Remove</a></div></td>
		<td>
			<input id='$row->token' name='qnty' type='text' size='3' onblur='sendVal(this.id)' value='$qnty' />
			<input type='hidden' name='quantity_$counter' value='$qnty' />
		</td>
		<td>
			$$total
			<input type='hidden' name='amount_$counter' value='$price' />
			<input type='hidden' name='item_number_$counter' value='$row->token' />
		</td>
	</tr>

";

}


 

Instead of using the id column in the database i use token so you will need to change this.

 

This is the part you will need to add:

 

<td width='10%'><div class='remove'><a href='index.php?page=cart&action=remove&id=$row->token'>Remove</a></div></td>
<td>
<input id='$row->token' name='qnty' type='text' size='3' onblur='sendVal(this.id)' value='$qnty' />
<input type='hidden' name='quantity_$counter' value='$qnty' />
</td>

 

This is the remove code on my cart script: (forgot to add this in the original post)

 


if(isset($_GET['action']) && $_GET['action'] == "remove") {

$pid = $_GET['id'];

   if (item_exists($pid)) {

       $shopcart->remove($pid);
       setCart($shopcart);

   }
   else {
   ?>

   	<script type="text/javascript">

           alert('That item does not exist.');

           window.location = "javascript: history.go(-1)";

       </script>

   <?php
   }   

   unset($_GET['action']);
   unset($_GET['id']);

   ?>
	<script type="text/javascript">

           alert('The item was removed from the shopping cart.');

           window.location = "javascript: history.go(-1)";

       </script>

<?php    

}


 

The div class="remove" would just be some CSS for a button to click on and a color change for a mouseover. $row->token identifies each product for me but in your case it would be the $product_id so you will want to replace that. $row->token is just like pulling $row->id from the database but i did it a little differently for inserting ID into the URL...to prevent it.

 

This is the javascript you put on your page to send a request to php on another script to pass values. (Hence the onblur="sendVal(this.id)")

 

function sendVal(id) {

   var getQnty = document.getElementById(id).value;
   var token = document.getElementById(id).id;

   window.location = "index.php?page=cart&qnty=" + getQnty + "&token=" + token;

}  

 

As you see it is getting the updated quantity value from the form and passing it to Javascript then Javascript is passing it to cart.html:

 

Cart.html

 

$shopcart = getCart();

if (isset($_GET['qnty'])) {

$num = htmlentities(addslashes($_GET['qnty']));
   $token = htmlentities(addslashes($_GET['token']));

   if (item_exists($token) && item_exists_db($token) && is_numeric($num)) {

   	$shopcart->updQnty($token, $num);
	setCart($shopcart);

       ?>

   	<script type="text/javascript">

           alert('Quantity updated successfully.');

           window.location = "javascript: history.go(-1)";

       </script>

   <?php

   }
   else {
   ?>
   	<script type="text/javascript">

           alert('That item does not exist.');

           window.location = "javascript: history.go(-1)";

       </script>

   <?php
   }


}

 

As i said instead of token it would be the $product_id in your case. The unique value of the item or items since the shoppingcart_row function just outputs 1 row for each product in the shopping cart. If i have missed anything or something doesn't work please post the code and we'll get it sorted out for you. Enjoy!

 

As far as the product coming off when it has sold out you can just store the number of products in the database and everytime someone purchases that particular product just subtract -1 from the database and update the database with that number. You will want to do a check on how many of that item you have between the user clicking on the item to add it to cart and it showing up on the shopping cart list. If that number is 0 then send a message to the user. But you may want to include how many of that product you have somewhere near the product before the user even clicks to add it. Just keeps things simple.

Edited by Archadian
Link to comment
Share on other sites

In the last bit of code you will notice that I am checking to see if the item exists in the DB as well as the $_SESSION['cart']. Here is the code to check if both exists:

 

This is in my functions script, name it what you want to i believe its functions.php in the video tutorials.

 


function item_exists_db($token) {

global $db, $shopcart;

if (strlen($token) == 32) {

	$db->query = "SELECT token FROM products";
	$result = $db->sql_query($db->query);

	while($row = $db->fetch_object($result)) {

		if ($row->token == htmlentities(addslashes($token))) {

			return true;

		}

	}

	return false;

}
else {

	send_error_loc("TOKEN ERROR", "The token and/or the product doesn't exist.");

}

}

function item_exists($token) {

$shopcart = getCart();

foreach ($shopcart->GetItems() as $key) {

	if ($key == $token) {

		return true;

	}

}

return false;

}

 

Also if you want to count the number of items in the shopping cart to show the user here is that code:

 

echo "<div id=\"countItems\">";

   $shopcart = getCart();

   $count = 0;

   foreach ($shopcart->GetItems() as $key) {

     if (!empty($key)) {

         $count++;

     }

   }

   echo "<p style=\"font-size: 14px; color: black; text-align: center;\">Items In Cart: <b>" . $count . "</b></p>";

echo "</div>";

 

As i said the $token would be the id from $_SESSION['cart'] and your database. You won't need the strlen($token) == 32 because that checks to make sure the $token is 32 characters long. Maybe you can do some other check there. Good Luck! :)

Edited by Archadian
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

×
×
  • Create New...