请在php中比较两个变量

时间:2017-10-31 19:44:36

标签: php mysql

我想在mysql表中插入数据,但不应该在..之前插入。

我尝试比较变量总是失败。

<?PHP
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "sunil_electronics";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT p_id FROM inquirycart WHERE p_id='$pid'";
$result = $conn->query($sql);

// output data of each row
$row = $result->fetch_assoc();
$id = $row['p_id'];

if ($id == $pid) {
    header('Location: ' . $url . '&key1=' . $key . '&info=info');
} else {
    $sql1 = "INSERT INTO inquirycart (p_id,p_name, p_image)
        SELECT p_id, p_name, p_image FROM $key
        WHERE p_id = '$pid'";
    $result1 = $conn->query($sql1);

    header('Location: ' . $url . '&key1=' . $key . '&succ=succ');
}
?>

1 个答案:

答案 0 :(得分:0)

如果之前未使用p_id,则查询不会返回任何行。 $result->fetch_assoc()将返回NULL$row['p_id']将失败。

您只需检查返回的行数即可。

if ($result->num_rows > 0) {
    header('Location: ' . $url . '&key1=' . $key . '&info=info');
} else {
    ...
}