代码:

#!/usr/bin/php
<?php
error_reporting(E_ALL);
while(true){
    // Check how many API calls remain
    $rate_limit = json_decode(file_get_contents('http://api.twitter.com/1/account/rate_limit_status.json'),true);
    // Array containing all the Twitter handles
    $handles = array('le4ky');

    if($rate_limit['remaining_hits']<count($handles)){
        file_put_contents('tweet_gremlin.log', date('r') . ' Rate limit reached');
        sleep(30);
    }else{
        // Establish the database connection
        if(!$mysqli = mysqli_connect('localhost','twitterd','password','twitterd')){
            die('Cannot connect to database');
            file_put_contents('tweet_gremlin.log', date('r') . ' Cannot connect to the database');
        }


        // This is the big one.  Loop through the $handles values, make an API call, and insert the tweets.
        foreach($handles as $value){
            // Get the handle's timeline and put it into $user_data
            $user_data = json_decode(file_get_contents('http://search.twitter.com/search.json?q=from:' . $value . '&rpp=100'),true);
            // Put only the results index (tweets) into into $user_data
            $user_data = $user_data['results'];

            for($i=0;$i<count($user_data);$i++){

                // Lazy method for sanitizing variables
                $id = mysqli_real_escape_string($mysqli,$user_data[$i]['id']);
                $created_at = mysqli_real_escape_string($mysqli,$user_data[$i]['created_at']);
                $from_user_id = mysqli_real_escape_string($mysqli,$user_data[$i]['from_user_id']);
                $profile_image_url = mysqli_real_escape_string($mysqli,$user_data[$i]['profile_image_url']);
                $from_user = mysqli_real_escape_string($mysqli,$user_data[$i]['from_user']);
                $from_user_name = mysqli_real_escape_string($mysqli,$user_data[$i]['from_user_name']);
                $text = mysqli_real_escape_string($mysqli,$user_data[$i]['text']);

                $insert_tweets = "INSERT INTO tweets ('id','created_at','from_user_id','profile_image','from_user','from_user_name',`text`) VALUES ({$id},{$created_at},{$from_user_id},{$profile_image_url},{$from_user},{$from_user_name},{$text});";
                $result = mysqli_query($mysqli,$insert_tweets);
            }
        }
        sleep(30);
    }
}
?>


基本上,这只是要成为一种“守护程序”,用于检索数据并将其插入数据库。为了我的一生,我无法弄清楚为什么没有将数据插入数据库中。 Twitterd用户对数据库具有选择和插入权限,并且可以从任何主机进行连接。

最佳答案

您需要在SQL查询中的字符串值两边加上引号:

$insert_tweets = "
    INSERT INTO tweets
        (`id`,`created_at`,`from_user_id`,`profile_image`,`from_user`,`from_user_name`,`text`)
    VALUES
        ('{$id}','{$created_at}','{$from_user_id}','{$profile_image_url}','{$from_user}','{$from_user_name}','{$text}')
";


我将它们添加到所有值,您可以在已知为数字的值上删除它们(并使用intval()floatval()或其他一些数字验证功能进行验证)。

我还用列名中的反引号替换了单引号。

关于php - MySQLi INSERT不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11697340/

10-13 08:49