0

I started to learn php but stuck in somewhere. Below is my php code to show what i did. I made add to cart part with storing IP address and product id but still the value is not saving database. How to check what's wrong in code? I also checked it using echo mysqli_error($db) but not showing.

below is code :

<?php 

$db = mysqli_connect("localhost","root","","ecommerce");


function getIp() {
    $ip = $_SERVER['REMOTE_ADDR'];

    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }

    return $ip;
}


function cart(){

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

        global $db;

        $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($db, $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($db , $insert_pro);
            echo "<script>window.open('index.php','_self')</script>";
        }
    }
}
?>

Even adding image of database table.

enter image description here

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Sagar Kodte
  • 3,723
  • 4
  • 23
  • 52

1 Answers1

1

You need to check the status of almost all mysqli_ api calls, see the 2 checks I have added

function cart(){

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

        global $db;

        $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($db, $check_pro);

        // test query worked and report error if it failed
        if ($run_check === false) {
            echo mysqli_error($db);
            exit;
        }

        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($db , $insert_pro);

            // test query worked and report error if it failed
            if ($run_pro === false) {
                echo mysqli_error($db);
                exit;
            }

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

This will likely show you your error.

It is likely you have already INSERTED a row with the key you are using

By the way: Your script is at risk of SQL Injection Attack Have a look at what happened to Little Bobby Tables Even if you are escaping inputs, its not safe! Use prepared statement and parameterized statements

Community
  • 1
  • 1
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149