Кнопка Добавить в корзину не добавляет товары в базу

Я новичок в php и пытаюсь добавить элементы в свою таблицу БД (корзину), но когда я нажимаю «добавить в корзину», ничего не происходит. Кнопка отображается через функцию getPro, которая находится ниже.

function cart(){
if(isset($_GET['add_cart'])){

global $con;

$ip = getIp();

$pro_id = $_GET['add_cart'];

$check_pro = "SELECT * FROM cart where ip_add='$ip' and p_id='$pro_id'";

$run_check = mysqli_query($con, $check_pro);

if(mysqli_num_rows($run_check)>0){
echo "";
}
else {

$insert_pro = "insert into cart(p_id,ip_add) values ('$pro_id','$ip')";

$run_pro = mysqli_query($con, $insert_pro);

echo "<script>window.open('index.php','_self')</script>";

}
}}

Кнопка «Добавить в корзину» повторяется этой функцией.

function getPro(){

global $con;

$get_pro = "select * from products order by RAND() LIMIT 0,6";

$run_pro = mysqli_query($con, $get_pro);

while ($row_brand_pro=mysqli_fetch_array($run_pro)) {

$pro_id = $row_brand_pro['product_id'];
$pro_cat = $row_brand_pro['product_cat'];
$pro_brand = $row_brand_pro['product_brand'];
$pro_title = $row_brand_pro['product_title'];
$pro_price  = $row_brand_pro['product_price'];
$pro_image = $row_brand_pro['product_image'];

echo "<a href='index.php?add_cart=$pro_id'><button style='float:right;'>Add to Cart</button></a>
</div>
";

}
}
}

1

Решение

Я не могу решить это для вас, потому что проблема может быть где угодно, но у вас есть некоторые проблемы, которые должны быть решены, надеюсь, что то, что я демонстрирую, будет полезно:

1) Если возможно, используйте вместо этого фреймворк, многое из того, что вы делаете, уже решено (надежно) бесплатными фреймворками. Если вы не уверены в этом:

2) Старайтесь избегать использования globalвместо этого вы можете добавить базу данных:

cart($con);

3) Разделите ваши функции немного больше, каждая функция делает слишком много:

# Try to make this more flexible by adding the limits as variables
# Also, you might decide that random is not a great idea, so this allows you
# to change that at each instance
# Also, if you leave the columns flexible, you will make your function that
# much more useful
function getProducts($con, $cols = '*', $page = 0, $limit = 6, $rand = true)
{
# Perhaps you don't want to limit one day
$limitSql = (!empty($page) || !empty($limit))? "LIMIT {$page}, {$limit}" : "";
# This allows you to insert an array and only select certain columns
$cols  = (is_array($cols))? implode(", ", $cols) : $cols;
# Only add the randomness if you want to (default is to randomize)
$sql   = ($rand)? "ORDER BY RAND()" : '';
# Create your dynamic statement
$stmnt = "SELECT {$cols} FROM products {$sql} {$limitSql}";
$query = mysqli_query($con, $stmnt);
# Have this just assemble the values, don't echo anything
while ($result = mysqli_fetch_array($query)) {
$row[] = $result;
}
# Send back the results
return (!empty($row))? $row : [];
}

Используя эту функцию:

# This would give you results with just the two columns with 10 results, no random
$products = getProducts($con, array("product_id", "product_title"), 0, 10, false);
# This should just return the count
$products = getProducts($con, "COUNT(*) as count", false, false, false);

Итак, теперь, когда у вас есть эта функция, вы пишете цикл в представлении:

<?php foreach(getProducts($con, 'product_id') as $row): ?>

<!-- Now you have only pulled the one column required for this use -->
<a href="index.php?add_cart=<?php echo $row['product_id'] ?>">Add to Cart</a>

<?php endforeach ?>

4) Эта функция корзины более проблематична, у нее есть несколько проблем. a) Вам необходимо связать параметры, если ваши значения от пользователя не являются числовыми, у вас есть SQL-инъекция и проблема безопасности. b) Вы должны разделить эту функцию на две, c) Вы должны оставить эхосигнал снаружи в представлении. , d) Если вы храните корзины по ip, я бы этого не сделал, более чем один компьютер может иметь один и тот же ip, если они используют VPN или в одной сети. Печенье может быть лучшим решением:

function itemExists($con, $pid, $ip)
{
$stmnt = "SELECT * FROM cart WHERE ip_add = '{$ip}' and p_id = '{$pid}'";
$query = mysqli_query($con, $stmnt);

return (mysqli_num_rows($query) > 0);
}

function addToCart($con, $pid, $qty = 1)
{
# Since you aren't binding, you need some sort of safeguard here, I am assuming
# your product id values are numeric. If not, you definitely need to bind parameters
if(!is_numeric($pid))
return false;
# Same here, you need to make sure nothing but numbers get through (or bind)
if(!is_numeric($qty))
$qty = 1;
# Pass on your connection and pid, inject the getIp() function if you choose
# to keep using it
$itemExists = itemExists($con, $pid, getIp());
# Confirm the item has no row in database
if($itemExists)
# Stop if it does
return false;
# You may want to echo here to see if this is what you expect
$stmnt = "insert into cart(p_id, ip_add) values ('{$pid}', '{$ip}')";
# I use PDO, but I am sure you can get an error back on this if the sql
# fails for whatever reason, that is a good place to start for your issue
$query = mysqli_query($con, $stmnt);
# Run this again to make sure it inserted
return itemExists($con, $pid, getIp());
}

Теперь по вашему мнению:

if(!empty($_GET['add_cart'])) {
# When you add to cart, there should be some feed back to whether it was successful
$success = addToCart($con, $_GET['add_cart']);
# If not you can echo it
if(!$success)
echo '<div class="msg error">An error occurred adding item to cart.</div>';
}

В любом случае, надеюсь, это полезно, но вы должны подумать о том, чтобы: 1) использовать каркас, а если нет, то использовать версию mysqli (или PDO) для ООП, потому что привязка параметров намного проще (я нахожу), чем функциональная библиотека mysqli.

0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector