dongxianrang9269 2018-01-22 14:35
浏览 92

PHP mysql将表行与json数组进行比较

I have a mysql table with a firstname, lastname and email which I want to compare with a google spreadsheet array (json) with the same table headers (firstname, lastname, email). If the records match to eachother I want to update my table. For example: I have 'John Doe' in mysql table and 'John Doe' in my google spreadsheet: If this is true I want to update a certain value to this mysql table row.

My code so far, all rows are getting an update because there is one comparison true. I only want the specific rows (Maybe with a foreach?):

$sql = "SELECT * FROM student WHERE form=''"; //select from db
$result = $conn->query($sql);

while($row = mysqli_fetch_array($result)) //fetch it
{       
    $firstname= $row['firstname'];
    $lastname= $row['lastname'];
    $email = $row['email'];

    $url = 'https://spreadsheets.google.com/feeds/list/*MY-KEY*/od6/public/values?alt=json'; // my spreadsheet (key is inserted with me)
    $file= file_get_contents($url);
    $json = json_decode($file);
    $ress = $json->{'feed'}->{'entry'};

    foreach($ress as $res) {

    $fname = $res->{'gsx$naam'}->{'$t'};
    $lname = $res->{'gsx$achternaam'}->{'$t'};
    $mailing = $res->{'gsx$email'}->{'$t'};  
    }       

        if ($firstname.$lastname == $fname.$lname || $email == $mailing) {
            $sql2 = "UPDATE student SET form=1";

            if ($conn->query($sql2) === TRUE) { 
             echo "inserted";
            } 
        }

}
  • 写回答

1条回答 默认 最新

  • douqiu9529 2018-01-22 15:27
    关注

    I think you need to change the for loop and the if statement like this

    foreach($ress as $res) {
    
        $fname = $res->{'gsx$naam'}->{'$t'};
        $lname = $res->{'gsx$achternaam'}->{'$t'};
        $mailing = $res->{'gsx$email'}->{'$t'};
        if ($firstname.$lastname == $fname.$lname || $email == $mailing) {
            $sql2 = "UPDATE student SET form=1";
    
            if ($conn->query($sql2) === TRUE) { 
             echo "inserted";
            }
            // to break from for loop when the record has been found
            break;
        }
    }       
    
    评论

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?