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

时间:2018-01-22 14:35:31

标签: php mysql arrays json comparison

我有一个带有名字,姓氏和电子邮件的mysql表,我希望与具有相同表格标题(名字,姓氏,电子邮件)的谷歌电子表格数组(json)进行比较。 如果记录与彼此匹配,我想更新我的表。 例如:我在mysql表中有'John Doe',在我的google电子表格中有'John Doe':如果这是真的,我想将某个值更新到这个mysql表行。

到目前为止,我的代码所有行都得到了更新,因为有一个比较是真的。我只想要特定的行(也许是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 个答案:

答案 0 :(得分:0)

我认为您需要像这样更改for循环和if语句

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