function cart(){
if (isset($_GET['add_cart'])) {
global $config;
$ip=getIp();
$pro_id=$_GET['add_cart'];
// checking if user already insert that product to cart
$sql="SELECT * FROM cart WHERE ip_add='$ip' AND p_id='$pro_id' " ;
$run_check=mysqli_query($config,$sql);
if(mysqli_num_rows($run_check)>0) {
echo "";
}
else{
$insert="INSERT into cart (p_id,ip_add) VALUES('$pro_id,$ip')";
$run=mysqli_query($config,$insert);
echo "<script>window.open('index.php','_blank')</script>";
}
}
}
i am getting error on mysqli_num_rows it says mysqli_num_row expects two parameter something like that
You need to add single quote for each value. Reference
$insert="INSERT into cart (p_id,ip_add) VALUES('$pro_id','$ip')";
Related
Am trying to create a checkout table with the following cart objects. If the cart page is loaded, I want all the cart objects inserted into the checkout table and if any of the products is already in the checkout table (probaly someone toggle between the cart page and shopping page) I want to update checkout page as show below.
I will be glad if I can be put through on this. Thanks
<?php
foreach ($gs->getLists('cart') as $ps):
$cart = $gs->getGoods($ps['p_id']);
array_map(function($ps) {
$pid = $ps['p_id'];
$pu = $ps['pu'];
$pn = $ps['pn'];
$pp = $ps['pp'];
$pk = $ps['pk'];
$tp = $pp * $pk;
if (!isset($_id)) {
"INSERT INTO checkout (p_id, pu, pn, pp, pk, tp)
VALUES ('$pid','$pu','$pn','$pp','$pk','$tp')";
}else{
"UPDATE checkout SET pk=:pk, tp=:tp WHERE p_id = 'p_id'";
}
}
?>
....some html
<?php
}, $cart);
endforeach;
?>
The database connection as below
public $kuo = null;
public function __construct()
{
$this->kuo = mysqli_connect($this->host, $this->user, $this->password, $this->database);
if($this->kuo->connect_error){
echo "Fail" . $this->kuo->connect_error;
}
}
After following some answers and articles finally i came up with the function that will generate key(number) automatically when it is not exist in the database and codes works, but the problem is when the code exist the notification that "CODE EXIST" form something like a loop and print multiple notifications. Base on my codes where do i get it wrong and how can I fix it?
<?php
//HERE IS THE FUNCTION
function MyFunction($xIsConnection){
// CODE GENERATION
//$Code=(rand(10,1000));
$Code='001';
$query= "SELECT * FROM parent WHERE code='$Code'";
if($result= mysqli_query($xIsConnection,$query)){
if(mysqli_num_rows($result)>0){
echo " CODE EXIST<br>";
// CALL FUNCTION TO GENERATE NEW CODE
MyFunction($xIsConnection);
}
else{
echo "NOT EXIST <br>";
echo $Code;
}
}
else{
echo"failed";
}
}
require_once('dbConnect.php');
MyFunction($con);
mysqli_close($con);
?>
The answer is never ending recursion.
<?php
//HERE IS THE FUNCTION
function MyFunction($xIsConnection){
// CODE GENERATION
//$Code=(rand(10,1000));
$Code='001';
$query= "SELECT * FROM parent WHERE code='$Code'";
if($result= mysqli_query($xIsConnection,$query)){
if(mysqli_num_rows($result)>0){
echo " CODE EXIST<br>";
// CALL FUNCTION TO GENERATE NEW CODE
MyFunction($xIsConnection); // this line is responsible for your error. Recursion
}
else{
echo "NOT EXIST <br>";
echo $Code;
}
}
else{
echo"failed";
}
}
require_once('dbConnect.php');
MyFunction($con);
mysqli_close($con);
?>
I'm currently struggling with a page that allows a user to complete one of two options. They can either update an existing item in the SQL database or they can delete it. When the customer deletes an option everything runs perfectly well, however whenever a customer updated an item it displays the Query failed statement from the delete function before applying the update.
It seems obvious to me that the problem must be in my IF statement and that the DeleteButton function isn't exiting if the $deleteno variable isn't set. Any help would be appreciated. Excuse the horribly messy code PHP isn't a language I am familiar with. (I have not included the connect information for privacy reasons)
function DeleteButton(){
#mysqli_select_db($con , $sql_db);
//Checks if connection is successful
if(!$con){
echo"<p>Database connection failure</p>";
} else {
if(isset($_POST["deleteID"])) {
$deleteno = $_POST["deleteID"];
}
if(!isset($deleteno)) {
$sql = "delete from orders where orderID = $deleteno;";
$result = #mysqli_query($con,$sql);
if((!$result)) {
echo "<p>Query failed please enter a valid ID </p>";
} else {
echo "<p>Order $deleteno succesfully deleted</p>";
unset($deleteno);
}
}
}
}
That is the code for the delete button and the following code is for the UpdateButton minus the connection information (which works fine).
if(isset($_POST["updateID"])) {
$updateno = $_POST["updateID"];
}
if(isset($_POST["updatestatus"])) {
if($_POST["updatestatus"] == "Fulfilled") {
$updatestatus = "Fulfilled";
} elseif ($_POST["updatestatus"] == "Paid") {
$updatestatus = "Paid";
}
}
if(isset($updateno) && isset($updatestatus)) {
$sql ="update orders set orderstatus='$updatestatus' where orderID=$updateno;";
$result = #mysqli_query($con,$sql);
if(!$result) {
echo "<p>Query failed please enter a valid ID</p>";
} else {
echo "<p>Order: $updateno succesfully updated!</p>";
}
}
Once again these are incomplete functions as I have omitted the connection sections.
if(!isset($deleteno)) {
$sql = "delete from orders where orderID = $deleteno;";
Are you sure you want to execute that block if $deleteno is NOT set?
P.S. You shouldn't rely on $_POST['deleteId'] being a number. Please read about SQL injections, how to avoid them and also about using prepared statements.
I've update your code, but you need to write cleaner code ( spaces, indents, etc ) this won't only help you to learn but to find your errors easily.
<?php
function DeleteButton()
{
#mysqli_select_db($con , $sql_db);
/*
Checks if connection is successful
*/
if(!$con){
echo"<p>Database connection failure</p>";
} else {
/*
Check if $_POST["deleteID"] exists, is not empty and it is numeric.
*/
if(isset($_POST["deleteID"]) && ! empty($_POST["deleteID"]) && ctype_digit(empty($_POST["deleteID"]))
$deleteno = $_POST["deleteID"];
$sql = "delete from orders where orderID='$deleteno'";
$result = #mysqli_query($con,$sql);
if(!$result){
echo "<p>Query failed please enter a valid ID </p>"
} else {
echo "<p>Order $deleteno succesfully deleted</p>";
unset($deleteno);
}
} else {
echo "<p>Please enter a valid ID </p>" ;
}
}
}
/*
Part 2:
===========================================================================
Check if $_POST["updateID"] exists, is not empty and it is numeric.
Check if $_POST["updatestatus"] exists, is not empty and equal to Paid or Fullfilled
*/
if( isset($_POST["updateID"]) &&
! empty($_POST["updateID"]) &&
ctype_digit(empty($_POST["updateID"]) &&
isset($_POST["updatestatus"]) &&
! empty($_POST["updatestatus"]) &&
( $_POST["updatestatus"] == "Fulfilled" || $_POST["updatestatus"] == "Paid" ) )
{
$updateno = $_POST["updateID"];
$updatestatus = $_POST["updatestatus"];
$sql ="update orders set orderstatus='$updatestatus' where orderID=$updateno;";
$result = #mysqli_query($con,$sql);
if(!$result){
echo "<p>Query failed please enter a valid ID</p>";
} else {
echo "<p>Order: $updateno succesfully updated!</p>";
}
}
There is an error in MySQL Syntax
$sql = "delete from orders where orderID = $deleteno;";
$deleteno after orderID must be inside single quotes.
change it to this $sql = "delete from orders where orderID = '$deleteno';";
Im currently working on a small university project. To develop a basic e-commerce php site. We have been given code or provided code within seminars which we are then to customise/develop further to our needs.
I am trying to adapt the following code to add an additional piece of information. The cart.php code builds a shopping cart functionality, which displays the product name, quantity and then allows the user to increase/decrease the quantity.
I am attempting to add the users (selected) product size to the shopping cart. Which they can select on product.php. I have already created the database support for this within product.php I just need the users selected option to then appear over in the cart.php.
Im not entirely sure how to do this correctly. My first problem is how do I record the users selection within product.php into a variable which can be transferred over to cart.php.
The second problem is then how to modify the cart.php to do this also, you shall see in cart.php I have attempted to add the product size to the table.
I really would appreciate some guidance with this.
Product.php
<div align="center"><?php
session_start();
//Connect to Session
include "conn.php";
//Retrieve Header
include "header.php";
//Query
//Get Product ID
if (isset($_GET['id'])){
$product_id = $_GET['id'];
//Select Product Attributes Query where Product ID is the selected product ID
$q="SELECT ProductName,img,ProductID,Description,p_spec1,p_spec2,p_spec3,p_spec4,p_spec5,Price,size_1,size_2,size_3,size_4,size_5 FROM Products
WHERE ProductID=$product_id";
//Retrieve and excute query from database and save results into a variable
$result = mysqli_query($_SESSION['conn'],$q);
//Display Product
if ($row = mysqli_fetch_array($result)){ //Create Product Attribute Array
echo "<div>
<p><b>Name:</b>" .$row[0]."</p>
<p><img src=".$row[1]."></p>
<p><b>Product Code:</b>" .$row[2]."</p>
<p><b><u>Product Description:</b></u></p>
<p>".$row[3]."</p>
<p><b><u>Product Spec:</b></u>";
//Count total product specifications and adjust bullet points
for($i=4;$i<9;$i++) {
if($row[$i]!='')
echo "<li>".$row[$i]."</li>";
}
echo"
<p><b>Price: </b>£".$row[9]."</p>
<p><b>Size:</b><select>";
//Count total product sizes available and adjust drop-down menu
for($i=10;$i<15;$i++) {
if($row[$i]!='')
echo "<option>".$row[$i]."</option>";
}
echo"</select>
</p>
</p>
</div>";
}
//Add Item to basket
echo "<div><input type='submit' value='Add to Basket'</div>";
}
//Retrieve Footer
include "footer.php";
?>
</div>
I have assumed in product.php that a variable $product_size will need to be actioned over to cart.php, however how do I collect the users selection into a variable?
Cart.php
<?php
//Start Session
session_start();
include "conn.php"; //Connect to database
include "header.php"; //Retrieve Header
//View the current shopping cart session
function viewcart(){
if (isset($_SESSION['cart'])){ //if shopping cart is not empty
$cart = $_SESSION['cart']; //store the cart array into a variable then display the content
echo "<table border=\"1\"> <tr> <th>Product</th> <th>Size</th> <th>Quantity</th> <th>Action</th></tr>";
foreach ($cart as $product=>$quantity){
$q = "SELECT ProductID FROM Products WHERE ProductName = '$product' LIMIT 1";
$result = mysqli_query($_SESSION['conn'],$q);
$row = mysqli_fetch_array($result);
$product_id = $row['ProductID'];
echo "<tr><td>$product</td>
<td>$product_size</td>
<td>$quantity</td><td>
-
+ </td> </tr>";
mysqli_free_result($result);
}
echo "</table>";
subtotal($cart); //display the subtotal
} else { //if shopping cart is empty
echo "<p>Your Basket is empty.</p>";
}
}
function subtotal($cart){
$total = 0; //initialise total
if (!empty($cart)){
foreach ($cart as $product => $quantity){
$q = "SELECT Price FROM Products WHERE ProductName ='$product' LIMIT 1";
$result = mysqli_query($_SESSION['conn'],$q);
$row = mysqli_fetch_array($result);
$price = $row['Price'];
$total += $price * $quantity;
}
echo "<p>Total: £$total |
Empty cart</p>";
} else {
unset($_SESSION['cart']); //destroy empty cart
echo "<p>Your Basket is empty.</p>";
}
}
function addproduct($product_id, $product_qty){
$q = "SELECT ProductName FROM Products WHERE ProductID = $product_id LIMIT 1";
$result = mysqli_query($_SESSION['conn'],$q);
$row = mysqli_fetch_array($result);
$product_name = $row['ProductName']; //get the product name from product id because it is better to display name than id in the cart
if (isset($_SESSION['cart'])){ //if shopping cart is not empty
$cart = $_SESSION['cart'];
if (array_key_exists($product_name, $cart)){ //if the product exists, update quantity
$cart[$product_name] += $product_qty;
}
else { //otherwise, add new product-quantity pair to the array
$cart[$product_name]=$product_qty;
}
$_SESSION['cart'] = $cart; //write the updated array back to session variable
}
else { //if shopping cart is empty
$cart = array($product_name=>$product_qty); //add product and quantity to the shopping cart
$_SESSION['cart'] = $cart; //write the updated array back
}
mysqli_free_result($result);
}
function deleteproduct($product_id, $product_qty){
$q = "SELECT ProductName FROM Products WHERE ProductID = $product_id LIMIT 1";
$result = mysqli_query($_SESSION['conn'],$q);
$row = mysqli_fetch_array($result);
$product_name = $row['ProductName'];
if (isset($_SESSION['cart'])){ //if shopping cart is not empty
$cart = $_SESSION['cart'];
if (array_key_exists($product_name, $cart)){ //if product exists, update quantity
$cart[$product_name] -= $product_qty;
if ($cart[$product_name] == 0){ //if the qty 0, delete key
unset($cart[$product_name]);
}
}
else { //exception
echo "<p>Error!</p>";
}
$_SESSION['cart'] = $cart; //write array back to session variable
} else {
echo "<p>Error!</p>";
}
mysqli_free_result($result);
}
function emptycart(){
if (isset($_SESSION['cart'])){ //if shopping cart is not empty
unset($_SESSION['cart']);
}
else {
echo "<p>Error!</p>";
}
}
if (isset($_GET['action'])){
if ($_GET['action']=='view'){
viewcart();
} elseif ($_GET['action']=='add'){
if (isset($_GET['product'])){
$product_id = $_GET['product'];
$product_qty = 1; //default product value
addproduct($product_id, $product_qty);
viewcart();
} else {
echo "<p>There is an error?</p>";
}
}
elseif ($_GET['action'] == 'delete'){
if (isset($_GET['product'])){
$product_id = $_GET['product'];
$product_qty = 1; //default product value
deleteproduct($product_id, $product_qty);
viewcart();
}
else {
echo "<p>There is an error!</p>";
}
} elseif ($_GET['action']=='empty') {
emptycart();
viewcart();
}
else {
echo "<p>There is an error! </p>";
}
}
else { echo "<p>There is an error!</p>"; }
include "footer.php"; //template design part
?>
P.S I am aware of SQL injection issues.
Thank You!
I built something similar to this some time ago and faced the same (rather common) problem.
The solution requires you to create a session variable to store the selected product id's. I think I stored one or more arrays into the session and used the information to populate the checkout page.
I also stored the session data in a table so the user could access it between sessions,
but that was a more advanced feature.
Take Away: use a session variable to store an array of product id's
There are some fundamental flaws here.
To start, create valid HTML. Make sure the form is wrapped in <form></form> tags. That form should have an action: <form action="cart.php" method="POST">
Your select for "size" needs to have a name: <select name="productSize">.
I have a php file that includes two functions, one to connect to the database and one to set cookied for the cart. Here is that file:
<?php
$dbServer="localhost";
$dbName="test";
function ConnectToDb($server, $database){
$s=#mysql_connect($server);
$d=#mysql_select_db($database, $s);
if(!$s || !$d)
return false;
else
return true;
}
function GetCartId(){
if(isset($_COOKIE["cartId"])){
return $_COOKIE["cartId"];
}
else {
session_start();
setcookie("cartId", session_id(), time()+((3600*24)*30));
return session_id();
}
}
?>
The function for connecting to the database works well in another php file for this particular program. I am having a problem with it in this file:
<?php
include("db.php");
switch($_GET["action"]) {
case "add_item":
{
AddItem($_GET["id"], $_GET["qty"]);
ShowCart();
break;
}
case "update_item": {
UpdateItem($_GET["id"], $_GET["qty"]);
ShowCart();
break;
}
case "remove_item": {
RemoveItem($_GET["id"]);
ShowCart();
break;
}
default: {
ShowCart();
}
}
function AddItem($itemId, $qty) {
// Will check whether or not this item
// already exists in the cart table.
// If it does, the UpdateItem function
// will be called instead
$cxn = #ConnectToDb($dbServer, $dbName);
// Check if this item already exists in the users cart table
$result = mysql_query("select count(*) from cs368_cart where cookieID = '" . GetCartID() . "' and itemId = $itemId");
$row = mysql_fetch_row($result);
$numRows = $row[0];
if($numRows == 0) {
// This item doesn't exist in the users cart,
// we will add it with an insert query
#mysql_query("insert into cs368_cart(cookieID, itemId, qty) values('" . GetCartID() . "', $itemId, $qty)");
}
else {
// This item already exists in the users cart,
// we will update it instead
UpdateItem($itemId, $qty);
}
}
function UpdateItem($itemId, $qty) {
// Updates the quantity of an item in the users cart.
// If the qutnaity is zero, then RemoveItem will be
// called instead
$cxn = #ConnectToDb($dbServer, $dbName);
if($qty == 0) {
// Remove the item from the users cart
RemoveItem($itemId);
}
else {
mysql_query("update cs368_cart set qty = $qty where cookieID = '" . GetCartID() . "' and itemId = $itemId");
}
}
function RemoveItem($itemId) {
// Uses an SQL delete statement to remove an item from
// the users cart
$cxn = #ConnectToDb($dbServer, $dbName);
mysql_query("delete from cs368_cart where cookieID = '" . GetCartID() . "' and itemId = $itemId");
}
function ShowCart() {
// Gets each item from the cart table and display them in
// a tabulated format, as well as a final total for the cart
$cxn = #ConnectToDb($dbServer, $dbName);
$result = mysql_query("select * from cs368_cart inner join cs368_products on cart.itemId =
items.itemId where cart.cookieID = '" . GetCartID() . "' order by items.itemName asc")
or die("Query to get test in function ShowCart failed with error: ".mysql_error());
?>
What can I do the remedy this problem? Thanks!
First: lose the #, and put some proper error handling in there (those functions return false when something goes wrong, and you can use mysql_error and mysql_errno to log it).
Second: mysql_real_escape_string and intval on those $_GET parameters before someone sneaks in some extra code through the URL.
Third: you're accessing $dbServer and $dbName as variables local to the function UpdateItem, rather than global to the script. You should only connect to the database once (in the original db.php file), and let the query functions take care of the rest (since there's only one connection, they all default to that one anyway).