dongyi1982 2019-04-04 16:00 采纳率: 0%
浏览 422
已采纳

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

I should insert value to parnerCode2 if parnerCodeOwner1 already taken value;

Below code only inserts to parnerCodeOwner1 if new values comes it rewrites first one, It shouldn't rewritten, value should inserted to 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条回答 默认 最新

  • dongmu5106 2019-04-04 16:13
    关注

    You started on the right track with this code:

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

    What you actually want is to grab the row that belongs to the user, not the partner. So, your query should be:

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

    Once you get the $user row...

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

    If that is true, insert the partnerCode into partnerCode1. Else, insert it into partnerCode2.

    Also, there is no need to fetch the row to check it if there is an error. So, all of that code should come after the if statement that checks for errors.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问