值不存储在mysql数据库中

时间:2016-07-14 10:36:14

标签: php html mysql database

我开始学习php,但卡在某个地方。下面是我的PHP代码,以显示我做了什么。我使用add to cart storing IP address and product id部分,但值仍然没有保存数据库。如何检查代码中的错误?我还使用e cho mysqli_error($db)检查了它,但没有显示。

下面是代码:

<?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>";
        }
    }
}
?>

甚至添加数据库表的图像。

enter image description here

1 个答案:

答案 0 :(得分:1)

您需要检查几乎所有mysqli_ api电话的状态,请参阅我添加的2项检查

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>";
        }
    }
}

这可能会显示您的错误。

您可能已经使用正在使用的密钥插入行

  

顺便说一下:   您的脚本存在SQL Injection Attack的风险   看看Little Bobby Tables偶然发生了什么   if you are escaping inputs, its not safe!   使用prepared statement and parameterized statements