mysqi_* giving errors mysql_* didn't - php

I am new to php and I am in the process of changing a script from using mysql_* to mysqli_* functions. I am getting the following errors after switching:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in cart.php on line 115
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in cart.php on line 115
My code
<title>Cart</title>
<?php
require("../mysqli_connect.php");
?>
</head>
<body>
<?php
$product_id = $_GET[id]; //the product id from the URL
$action = $_GET[action]; //the action from the URL
//if there is an product_id and that product_id doesn't exist display an error message
if($product_id && !productExists($product_id)) {
die("Error. Product Doesn't Exist");
}
switch($action) { //decide what to do
case "add":
$_SESSION['cart'][$product_id]++; //add one to the quantity of the product with id $product_id
break;
case "remove":
$_SESSION['cart'][$product_id]--; //remove one from the quantity of the product with id $product_id
if($_SESSION['cart'][$product_id] == 0) unset($_SESSION['cart'][$product_id]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items.
break;
case "empty":
unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart.
break;
}
?>
<?php
if($_SESSION['cart']) { //if the cart isn't empty
//show the cart
echo "<table border=\"1\" padding=\"3\" width=\"40%\">"; //format the cart using a HTML table
//iterate through the cart, the $product_id is the key and $quantity is the value
foreach($_SESSION['cart'] as $product_id => $quantity) {
//get the name, description and price from the database - this will depend on your database implementation.
//use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
$sql = sprintf("SELECT name, description, price FROM products WHERE id = %d;",
$product_id);
$result = mysqli_query($dbc, $sql);
//Only display the row if there is a product (though there should always be as we have already checked)
if(mysqli_num_rows($result) > 0) {
list($name, $description, $price) = mysqli_fetch_row($result);
$line_cost = $price * $quantity; //work out the line cost
$total = $total + $line_cost; //add to the total cost
echo "<tr>";
//show this information in table cells
echo "<td align=\"center\">$name</td>";
//along with a 'remove' link next to the quantity - which links to this page, but with an action of remove, and the id of the current product
echo "<td align=\"center\">$quantity X</td>";
echo "<td align=\"center\">$line_cost</td>";
echo "</tr>";
}
}
//show the total
echo "<tr>";
echo "<td colspan=\"2\" align=\"right\">Total</td>";
echo "<td align=\"right\">$total</td>";
echo "</tr>";
//show the empty cart link - which links to this page, but with an action of empty. A simple bit of javascript in the onlick event of the link asks the user for confirmation
echo "<tr>";
echo "<td colspan=\"3\" align=\"right\">Empty Cart</td>";
echo "</tr>";
echo "</table>";
}else{
//otherwise tell the user they have no items in their cart
echo "You have no items in your shopping cart.";
}
//function to check if a product exists
function productExists($product_id) {
//use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
$sql = sprintf("SELECT * FROM products WHERE id = %d;",
$product_id);
return mysqli_num_rows(mysqli_query($dbc, $sql)) > 0; ***//this is line 15***
}
?>
Continue Shopping
<?php
/*
products table:
CREATE TABLE `products` (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 255 ) NOT NULL ,
`description` TEXT,
`price` DOUBLE DEFAULT '0.00' NOT NULL ,
PRIMARY KEY ( `id` )
);
*/
?>
</body>
</html>
And here is the products page.
<title>Products</title>
<?php
require("../mysqli_connect.php");
?>
</head>
<body>
<table border="1">
<?php
$sql = "SELECT id, name, description, price FROM products;";
$result = mysqli_query($dbc, $sql);
while(list($id, $name, $description, $price) = mysqli_fetch_row($result)) {
echo "<tr>";
echo "<td>$name</td>";
echo "<td>$description</td>";
echo "<td>$price</td>";
echo "<td>Add To Cart</td>";
echo "</tr>";
}
?>
</table>
View Cart
</body>
</html>
Database connection
DEFINE ('DB_USER', 'username');
DEFINE ('DB_PASSWORD', 'password');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'domain_user');
// Make the connection:
$dbc = #mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );
// Set the encoding...
mysqli_set_charset($dbc, 'utf8');

Your connection is not making its way into the function. A quick fix is to mark the variable GLOBAL in your function.
function productExists($product_id) {
GLOBAL $dbc;
$sql = sprintf("SELECT * FROM products WHERE id = %d;", $product_id);
return mysqli_num_rows(mysqli_query($dbc, $sql)) > 0;
}
This way $dbc is available in your function.
You MAY want to help make this a little more readable (at least to my eyes...)
function productExists($product_id) {
GLOBAL $dbc;
$sql = sprintf("SELECT * FROM products WHERE id = %d;", $product_id);
$result = mysqli_query($dbc, $sql) or die(mysqli_error($dbc));
$rows = mysqli_num_rows($result);
return $rows;
}
I've found it to be easier to read the two lines in place of nesting the functions into one.

Related

Linking result from searching in database, to another page

For a school project, I have to make a webshop with PHP and use a database to search for your products, I have the code to display the results, however, I want to make a link, so that when you click on one of the search results, you go to that product's page.
I've tried looking online but I couldn't seem to find it anywhere, that's why I'm posting this question.
$sql = "SELECT ProductID, ProductTags, ProductName FROM producttabel";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
echo '<div class="allepccskop">';
echo "Onze producten: " . "<br>";
echo '</div>';
while($row = $result->fetch_assoc()) {
echo '<div class="allepccs">';
echo $row["ProductName"]. "<br>";
echo '</div>';
}
} else {
echo "0 results";
}
I want to make a link when you click on one of the search results, you go to that product's page.
To make a link to a product page, you need to use html a tag, just wrap it around your product name like this:
echo '' . $row["ProductName"]. "<br>";
The href attribute contains your php file name (e.g. index.php) and a GET parameter id to send the product id to the php page.
Full example:
Assuming you want to extend your code to display a single product when a product id (ProductID) is provided or all products otherwise.
This is a simple example how you could extend your code, look at the comments:
<?php
// take id from the request, otherwise set default to null
$productId = isset($_GET['id']) ? intval($_GET['id']) : null;
// when we have an id in the url, then we display a product page
if (!is_null($productId)) {
$sql = 'SELECT ProductID, ProductTags, ProductName FROM producttabel WHERE ProductID = ' . $productId;
$result = $mysqli->query($sql);
if ($result && $result->num_rows == 1) {
$row = $result->fetch_assoc();
$result->free(); // free result set
// output data of each row
echo '<div class="allepccskop">';
echo "Product page: #" . $productId . "<br>";
echo '</div>';
echo '<div class="allepccs">';
echo $row["ProductName"]. "<br>";
echo '</div>';
} else {
echo "Product not found";
}
// otherwise we show All products page
} else {
// your code
$sql = 'SELECT ProductID, ProductTags, ProductName FROM producttabel';
$result = $mysqli->query($sql);
if ($result && $result->num_rows > 0) {
// output data of each row
echo '<div class="allepccskop">';
echo "Onze producten: " . "<br>";
echo '</div>';
while ($row = $result->fetch_assoc()) {
echo '<div class="allepccs">';
echo '' . $row["ProductName"]. "<br>";
echo '</div>';
}
$result->free(); // free result set
} else {
echo "0 results";
}
}

save order cart session to database

I was wondering if anyone can help me save the shopping cart to a database? ive looked all online but havent found anything.
im trying to save an ordering form (for a mock restaurant) to the db after the user adds the items to the cart and proceeds to the pay function which already directs them to paypal screen. So basically, im trying to save the dishes the user selects and the price/qty to the database,address along with an order id.
In the database i have a table called dishes (Id,name,Description,Price and Quantity).
Many Thanks
below is the php session code.
<?php
session_start();
$page = 'ordering.php';
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db ('cart') or die (mysql_error());
if (isset($_GET['add'])) {
$quantity = mysql_query('SELECT id, quantity FROM dishes WHERE id='.mysql_real_escape_string((int)$_GET['add']));
while ($quantity_row = mysql_fetch_assoc($quantity)){
if ($quantity_row['quantity']!=$_SESSION['cart_'.(int)$_GET['add']]){
$_SESSION["cart_".(int)$_GET['add']]+='1';
}
}
header('Location: '.$page) ;
}
if (isset($_GET['remove'])) {
$_SESSION['cart_'.(int)$_GET ['remove']]--;
header('Location: '.$page) ;
}
if (isset($_GET['delete'])) {
$_SESSION['cart_'.(int)$_GET ['delete']]='0';
header('Location: '.$page) ;
}
function dishes(){
$get = mysql_query('SELECT id, name, description, price FROM dishes WHERE quantity > 0 ORDER BY id DESC');
if (mysql_num_rows($get)==0) {
echo "There are no dishes to display!";
}
else {
while ($get_row = mysql_fetch_assoc($get)) {
echo '<p>'.$get_row['name'].'<br />'.$get_row['description'].'<br />€'.number_format($get_row['price'], 2).' Add</p>';
}
}
}
function cart() {
$total = 0;
foreach($_SESSION as $name => $value) {
if ($value>0) {
if (substr ($name, 0, 5)=='cart_'){
$id = substr($name, 5, strlen ($name)-5);
$get = mysql_query('SELECT id, name, price FROM dishes WHERE id='.mysql_real_escape_string((int)$id)) ;
while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row['price']*$value;
echo $get_row['name'].' x '.$value.' # €'.number_format($get_row['price'], 2). ' = €'.number_format($sub, 2).' [-] [+] [Delete]<br />';
}
}
$total += $sub;
}
}
if ($total == 0) {
echo "no items.";
}
else {
echo 'Total: €'.number_format($total, 2).'</p>';
?>
<html>
<p>
<form action='viewcart.php' method='POST'>
<input type='submit' name='view' value='Confirm'>
</p>
<?php
}
}
?>
This is the html file to display the dishes and cart.
<div class="callout">
<aside class="sidebar">
<br />
<fieldset>
<?php cart(); ?>
</fieldset>
</div>
<br />
<?php dishes (); ?>
</body>
<?php include 'footer.html'; ?>
</html>
im trying to save it but im getting a id per item and i want a id per order and also i wanted the total price but its coming back empty
here is my code for inserting into database
function orders() {
foreach($_SESSION as $name => $value) {
if ($value !=0) {
if (substr ($name, 0, 5)=='cart_'){
//-5 so it = to the id number
$id = substr($name, 5, strlen ($name)-5);
$get = mysql_query('SELECT id, name, price FROM dishes WHERE id='.mysql_real_escape_string((int)$id));
while ($Get_row = mysql_fetch_assoc($get)) {
echo '<input type="text" name="item_name_'.$num.'" value="'.$Get_row['name'].'">';
echo '<input type="text" name="amount_'.$num.'" value="'.$Get_row['price'].'">';
echo '<input type="text" name="quantity_'.$num.'"value="'.$value.'">';
echo '<input type="text" name="total_'.$num.'"value="'.$total.'">';
if(mysql_query("INSERT INTO orders (name,quantity,price) VALUES ('$name','$value','$price')"))
echo"successfully inserted";
else
echo "failed";
}
}
}
}
}
You need an order table and an order details table, when customers place an order, you
insert an new order with customer information and new orderid ,amount paid,....
Insert every cart item, quantity,price to the details table, with the order id
Clear session content.

code to add to favourites fails silently

I have a myList.php which should list all products added to my favourites and compute the total price of products.
here is the code:
<?php
include 'navigation.php'
?>
<div class='sectionContents'>
<?php
if (isset($_GET['action']) && $_GET['action'] == 'removed') {
echo "<div>" . $_GET['prod_name'] . " was removed from favourites.</div>";
}
if (isset($_SESSION['fav'])) {
$ids = "";
foreach($_SESSION['fav'] as $prod_id) {
$ids = $ids . $prod_id . ",";
}
// remove the last comma
$ids = rtrim($ids, ',');
include "db_connect.php";
$query = mysql_query("SELECT prod_id, prod_name, prod_price FROM tbl_product WHERE prod_id IN ('$ids')") or die(mysql_error());
$num = mysql_num_rows($query);
if ($num > 0) {
echo "<table border='0'>"; //start table
// our table heading
echo "<tr>";
echo "<th class='textAlignLeft'>Product Name</th>";
echo "<th>Price (MUR)</th>";
echo "<th>Action</th>";
echo "</tr>";
//also compute for total price
$totalPrice = 0;
while ($row = mysql_fetch_assoc($query)) {
extract($row);
$totalPrice += $prod_price;
//creating new table row per record
echo "<tr>";
echo "<td>{$prod_name}</td>";
echo "<td class='textAlignRight'>{$prod_price}</td>";
echo "<td class='textAlignCenter'>";
echo "<a href='remove_favourite.php?prod_id= {$prod_id}&prod_name={$prod_name}' class='customButton'>";
echo "<img src='shopping-cart-in-php/images/remove-from- cart.png' title='Remove from favourite' />";
echo "</a>";
echo "</td>";
echo "</tr>";
}
echo "<tr>";
echo "<th class='textAlignCenter'>Total Price</th>";
echo "<th class='textAlignRight'>{$totalPrice}</th>";
echo "<th></th>";
echo "</tr>";
echo "</table>";
echo "<br /><div><a href='#' class='customButton'>Home</a></div>";
} else {
echo "<div>No products found in your favourites. :(</div>";
}
} else {
echo "<div>No products in favourites yet.</div>";
}
?>
I use the add_to_fav.php below to add the products to my favourites:
<?php
session_start();
// get the product id
$prod_id = $_GET['prod_id'];
$prod_name = $_GET['prod_name'];
/*
* check if the 'fav' session array was created
* if it is NOT, create the 'fav' session array
*/
if (!isset($_SESSION['fav'])) {
$_SESSION['fav'] = array();
}
// check if the item is in the array, if it is, do not add
if (in_array($prod_id, $_SESSION['fav'])) {
// redirect to product list and tell the user it was added to favourites
header('Location: prod_list.php?action=exists&prod_id' . $prod_id . '&prod_name=' . $prod_name);
}
// else, add the item to the array
else {
array_push($_SESSION['fav'], $prod_id);
// redirect to product list and tell the user it was added to cart
header('Location: prod_list.php?action=add&prod_id' . $prod_id . '&prod_name=' . $prod_name);
}
?>
I am having "No products found in your favourites. :(" when i try to view the favourites
I have a counter like thing which shows the number of products in my favourites as well and it stays to 0.
Have I erred somewhere? Which mistake should I correct?
There are a few things that could be happening.
1) You are not starting the session before loading the favorites:
<div class='sectionContents'>
<?php
if(isset($_GET['action']) && $_GET['action']=='removed'){
echo "<div>" . $_GET['prod_name'] . " was removed from favourites.</div>";
}
session_start()
if(isset($_SESSION['fav'])){
2) Your SQL query in fact is not finding any product ids. You might want to debug the SQL and run it in phpmyadmin or your mysql interface to see if it in fact does return any results.
include "db_connect.php";
$query = "SELECT prod_id, prod_name, prod_price FROM tbl_product WHERE prod_id IN ('$ids')";
echo $query; // Print query for debugging
$result = mysql_query($query) or die(mysql_error());
$num = mysql_num_rows($result);
My guess is that this query is incorrect because of the single quotes around $ids
It should be:
$query = "SELECT prod_id, prod_name, prod_price FROM tbl_product WHERE prod_id IN ($ids)";
Also this can be simplified from:
$ids = "";
foreach($_SESSION['fav'] as $prod_id){
$ids = $ids . $prod_id . ",";
}
// remove the last comma
$ids = rtrim($ids, ',');
To:
$ids = implode(",", $_SESSION['fav']);

How to pass multiple values using onChange to update a database in a php table

Purpose: To update an inventory database by using the onchange function by modifying the data displayed in a PHP table.
I am pulling my data from a database and displaying it in a table. I have the data displayed in text fields so they are editable. Once the data is edited my function uses the data provided by POST, preferably the item ID and the value, will be used to update the inventory.
Here is my 'inventory.php' code:
$db = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$inventory = mysqli_query($db, "SELECT item_id, item_name, item_quantity, item_cost, item_price FROM inventory");
$num_rows = mysqli_num_rows($inventory);
mysqli_close($db);
echo "<form id=\"update_add_inventory\" action=\"\" method=\"post\">";
echo "<table>";
echo "<tr>";
echo "<th>Item ID</th>";
echo "<th>Item Name</th>";
echo "<th>Item Quantity</th>";
echo "<th>Item Cost</th>";
echo "<th>Item Price</th>";
echo "</tr>";
$i = 1;
while($row = mysqli_fetch_array($inventory))
{
echo "<tr>";
echo "<td>".$row['item_id']."</td>";
echo "<td><input type=\"text\" name=\"item_".$i."_name\" onchange=\"updateInventory('update_inventory.php')\" value='".$row['item_name']."' /></td>";
echo "<td><input type=\"text\" name=\"item_".$i."_quantity\" onchange=\"updateInventory('update_inventory.php')\" value='".$row['item_quantity']."' /></td>";
echo "<td><input type=\"text\" name=\"item_".$i."_cost\" onchange=\"updateInventory('update_inventory.php')\" value='".$row['item_cost']."' /></td>";
echo "<td><input type=\"text\" name=\"item_".$i."_price\" onchange=\"updateInventory('update_inventory.php')\" value='".$row['item_price']."' /></td>";
echo "</td></tr>";
$i++;
}
echo "</table><br>";
echo "</form>";
Here is my 'onchange function':
function updateInventory(action)
{
document.getElementById('update_add_inventory').action = action;
document.getElementById('update_add_inventory').submit();
}
Here is my 'update_inventory.php' code:
$db = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$inventory = mysqli_query($db, "SELECT item_id, item_name, item_quantity, item_cost, item_price FROM inventory");
$num_rows = mysqli_num_rows($inventory);
$i = 1;
for ($n=1; $n<=$num_rows; $n++) {
if (isset($_POST['item_'.$i.'_name'])) {
$item_id = $_POST['item_'.$i.'_id'];
$item_name = $_POST['item_'.$i.'_name'];
$result = mysqli_query($db, "UPDATE inventory SET item_name='".$item_name."' WHERE item_id='".$item_id."'");
} else if (isset($_POST['item_'.$i.'_quantity'])) {
$item_id = $_POST['item_'.$i.'_id'];
$item_name = $_POST['item_'.$i.'_quantity'];
$result = mysqli_query($db, "UPDATE inventory SET item_quantity='".$item_quantity."' WHERE item_id='".$item_id."'");
} else if (isset($_POST['item_'.$i.'_cost'])) {
$item_id = $_POST['item_'.$i.'_id'];
$item_name = $_POST['item_'.$i.'_cost'];
$result = mysqli_query($db, "UPDATE inventory SET item_cost='".$item_cost."' WHERE item_id='".$item_id."'");
} else if (isset($_POST['item_'.$i.'_price'])) {
$item_id = $_POST['item_'.$i.'_id'];
$item_name = $_POST['item_'.$i.'_price'];
$result = mysqli_query($db, "UPDATE inventory SET item_price='".$item_price."' WHERE item_id='".$item_id."'");
}
$i++;
}
mysqli_close($db);
header('Location: inventory.php');
What I'm having trouble with is that I have been unable to find a way to pass the 'item ID' and the value being modified to the update script. I can do it by passing the data of what I need through the value and then using list and explode to separate them but by doing that I'm displaying the item ID in each text field, which is not good.
If you know of a way to pass both pieces of data to the script, using the onchange function, I'd appreciate the assistance.
You can add it as a parameter to your onChange function, then update a hidden field on your form with this value before it is submitted.
PHP
updateInventory('update_inventory.php', ".$row['item_id'].")
JavaScript
function updateInventory(action, item_id){
// update hidden form value with item_id
document.getElementById('item_id').value = item_id;
document.getElementById('update_add_inventory').action = action;
document.getElementById('update_add_inventory').submit();
}

Fetching array cart php

I have a following question. I store a shopping cart in an array session like below
session_start();
$id= $_GET['id'];
if(isset($_SESSION['cart']))
{
array_push($_SESSION['cart'], $id);
}
else
$_SESSION['cart']= array($id);
header("location:cart.php");
And when I try to retrieve the cart. I get the same product id as many as I put to the cart.
<?php
if(!isset($_SESSION['cart'])) {
echo "Your cart is empty.<br /><br /><a href='products.php'>Show products</a>";
} else {
echo '<table border="0.2">';
$total_price = 0;
foreach($_SESSION['cart'] as $id) {
$the_query = "select * from products where id='$id' GROUP BY id";
$result = mysql_query($the_query) or die('Query failed: ' . mysql_error());
$the_product = mysql_fetch_array($result, MYSQL_ASSOC);
$total_price = $total_price + $the_product['price'];
$href = "show_products.php?id=".$the_product['id'];
//echo "<tr>";
echo "<tr><td><a href='$href'>";
echo "<img src='".$the_product['image_url_small']."' /></a></td>";
echo "<td><strong>".$the_product['name']."</strong></td><td><em>$".$the_product['price']."</em>";
echo "</td>";
echo "<td> <a href='do_deletecart.php?id=". $the_product['id'] ."'>Delete item </a></td></tr>";
}
echo "<tr><td colspan='2'></td></tr>";
echo "<tr><td style='text-align:center;font-size:40px;'>$</td><td><strong>Total</strong><br /><em>$".$total_price."</em></td></tr>";
echo "</table>";
echo "<br /><a href='empty_cart.php'>Empty Cart</a> <a href='showallproducts.php'>Show phones</a><br /><br />";
}
how can I make it show only one product id or name. Thank in advance
If I understand your question correctly, you are getting many results for the same product id. This is because you are storing same id values many time in the $_SESSION variable.
You could do the following to not repeat the same ids in the $_SESSION variable.
EDIT
For sake of completeness I have updated the code. Hope that helps.
index.php
<?php
session_start();
$id= isset($_GET['id']) ? $_GET['id'] : null;
if(!is_null($id)){
if(isset($_SESSION['cart']) && count($_SESSION['cart']) > 0){
// increment product quantity if already exists
// or create a new one
add_or_increment_product_to_cart($id, $_SESSION['cart']);
} else {
// initialize cart
// add the first product
$_SESSION['cart'] = array();
array_push($_SESSION['cart'], (object) array('id' => $id, 'quantity' => 1));
}
}
function add_or_increment_product_to_cart($id, $cart){
foreach ($cart as $key => $product) {
if($id == $product->id){
$product->quantity++;
return;
}
}
array_push($_SESSION['cart'], (object) array('id' => $id, 'quantity' => 1));
}
header("location:cart.php");
Cart.php
<?php
session_start();
$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : null;
if($cart) {
foreach ($cart as $key => $product) {
$the_query = "SELECT * FROM products WHERE id=" . $product->id . " LIMIT 1";
// your code to fetch the products from the database
// what you have done is fine but vulnerable
// PDO recommended
}
} else {
echo "Your cart is empty.<br /><br /><a href='products.php'>Show products</a>";
}
Also please note that mysql_connect is deprecated and PDO class is the recommended and safe way to connect to the database. Your code is vulnerable to SQL Injection like #Touki said in his comment.
I would recommend performing only one query to retrieve all of the products, and then iterate the result of the query to populate the HTML. For example;
$the_query = "select * from products where id in (". implode(',', $_SESSION['cart']) .")";
$result = mysql_query($the_query);
while (($the_product = mysql_fetch_array($result, MYSQL_ASSOC))) {
...
}
This has the added bonus that you only perform one query, and would also only select one row per product.
It's worth noting, however, that the mysql_* methods are deprecated, and it would be advisable to start using another library such as mysqli or PDO.
On a related note, this code currently is very liable to SQL injection, and the input should ideally be sanitised before being put into a query string.

Categories