微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我的自定义php函数出了点问题

好的,所以我尝试创建一个自定义函数,该函数将为最终用户在iframe中回显网站网址.

该脚本必须检查用户是否已经查看过该站点,如果已经看到该站点,则不再显示站点,而是从数据库获取一个站点url等.

到目前为止,这是我想出的:

function get_urls() {
    require 'config.PHP';
    global $con;
    global $currentUsername;
    $con = MysqLi_connect($hostname, $dbusername, $dbpassword, $dbname);
    $query = "SELECT site_url FROM sites WHERE site_url IS NOT NULL";
    $result = MysqLi_query($con, $query);

    // Get all the site urls into one array
        $siteUrls = array();
        $index = 0;
        while($row = MysqLi_fetch_assoc($result)) {
            $siteUrls[$index] = $row;
            $index++;
        }

    $query2 = "SELECT site_url FROM views WHERE user = '$currentUsername' AND site_url IS NOT NULL";
    $result2 = MysqLi_query($con, $query2);

    // Get urls the user has already seen into another array
        $seenUrls = array();
        $index = 0;
        while($row2 = MysqLi_fetch_assoc($result2)) {
            $seenUrls[$index] = $row2;
            $index++;
        }

    // Compare the two arrays and create yet another array of urls to actually show
    $urlsToShow = array_diff($siteUrls, $seenUrls);

    if (!empty($urlsToShow)) {
        // Echo the url to show for the iframe within browse.PHP and add an entry to the database that the user has seen this site
        foreach ($urlsToShow as $urlToShow) {
            echo $urlToShow;
            $query = "INSERT INTO views VALUES ('', '$currentUsername', '$urlToShow')";
            MysqLi_query($con, $query);
            break;
        }
    }
    // Show the allSeen file when all the ads are seen
    else {echo 'includes/allSeen.PHP';}
    MysqLi_free_result($result);
    MysqLi_close($con);
}

我目前发现了两个错误.首先$siteUrls和$seenUrls都可以,但是当我使用array_diff比较两者时,它将返回一个空数组.

其次,脚本不会将站点URL写入数据库,因为$urlToShow是一个数组而不是单个URL?

解决方法:

我认为问题出在您的代码中,您正在创建$siteUrls,$seenUrls数组. MysqLi_fetch_assoc()函数将为您提供结果行作为关联数组.因此,如果您想在while循环中更改某些代码.
修改

while($row = MysqLi_fetch_assoc($result)) {
        $siteUrls[$index] = $row;
        $index++;
}

while($row = MysqLi_fetch_assoc($result)) {
        $siteUrls[$index] = $row['site_url'];
        $index++;
    }

并且在第二个while循环中.改变这个

while($row2 = MysqLi_fetch_assoc($result2)) {
        $seenUrls[$index] = $row2;
        $index++;
}

while($row2 = MysqLi_fetch_assoc($result2)) {
        $seenUrls[$index] = $row2['site_url'];
        $index++;

}
并尝试

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐