如果第一行不为空,如何在第二行中插入值?数据库

时间:2019-04-04 16:00:25

标签: php mysql mysqli

如果parnerCode2已获取值,我应该在parnerCodeOwner1插入值;

下面的代码仅在出现新值时才插入到parnerCodeOwner1中,它会重写第一个值,而不应重写,应该将值插入到parnerCode2

<?php
if (isset($_POST['partnerCode'])) {
    // receive all input values from the form
    $partnerCode= mysqli_real_escape_string($db, $_POST['partnerCode']);
    if (empty($partnerCode)) { 
        array_push($errors, "CODE required"); 
    }

    $user_check_query = "SELECT * FROM refer WHERE partnerCode='$partnerCode' LIMIT 1";
    $result = mysqli_query($db, $user_check_query);
    $user = mysqli_fetch_assoc($result);

    if (count($errors) == 0) {
        $query = "update refer set partnerCodeOwner1= '" . $_SESSION['username'] . "'  where randomfield='$partnerCode'  ";
        mysqli_query($db, $query);
    }   
}
?>

ID       randomfield   parnerCode2  parnerCodeOwner1
+-------+-------------+-------------+----------------+
|   1   | uOxerUg4    |             | BuBI9vk        |
+-------+-------------+-------------+----------------+
|   2   | cZzuJlcs    |             | uOxerUg4       |
+-------+-------------+-------------+----------------+
|   3   | BuBI9vke    |             | cZzuJlcs       |
+-------+-------------+-------------+----------------+

1 个答案:

答案 0 :(得分:0)

您使用以下代码开始了正确的尝试:

$user_check_query = "SELECT * FROM refer WHERE partnerCode='$partnerCode' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$user = mysqli_fetch_assoc($result);

您真正想要的是获取属于用户而不是伙伴的行。因此,您的查询应为:

$user_check_query = "SELECT partnerCode1 FROM refer WHERE randomField='".$_SESSION['username']."' LIMIT 1";

一旦您获得$ user行...

if(empty($user['partnerCode1']))

如果是这样,请将partnerCode插入partnerCode1。否则,将其插入partnerCode2。

此外,也无需提取行来检查是否存在错误。因此,所有这些代码都应位于检查错误的if语句之后。