0

I am trying to format a date string i rip from the web the date comes in as m/d/y and I need to insert it into MYSQL currently I get an error PHP Fatal error: Call to a member function format() on a non-object

Code:

<?php
include 'ganon.php';
$id = array(8573, 53816, 7746, 80748, 7714);

for($l=0; $l<sizeof($id); $l++) {
$html = file_get_dom("http://pregame.com/pregamepros/pro-bettor/picks.aspx?id=" . $id[$l]);

$picks = $html('div[class="div-table-col"]');

$array = array();
$j =0;
for($i=0; $i<sizeof($picks); $i+=8) {
    $array[$j] = array("date" => trim($picks[$i]->getPlainText()), 
            "sport" => trim($picks[$i+1]->getPlainText()),
            "pick" => trim($picks[$i+2]->getPlainText()),
            "score" => trim($picks[$i+3]->getPlainText()),
            "odds" => trim($picks[$i+4]->getPlainText()),
            "size" => preg_replace('/\$/', "", $picks[$i+5]->getPlainText()),
            "winloss" => trim($picks[$i+6]->getPlainText()),
            "money" => (int)preg_replace('/\$/', "", $picks[$i+7]->getPlainText()));
    $j++;
} 

//enter picks into database
//make sure we do not add picks we already have
$mysqli = new mysqli("host", "user", "pass", "db");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    exit();
}
if($id[$l] == 8573) {
//$query = "SELECT `date` FROM `db`.`vegasrunner` where date=" . date('Y-m-d');
for($i=0; $i<sizeof($array); $i++) {
$query = "SELECT `date`,`pick` FROM `db`.`vegasrunner` where date=" . "'" . $array[$i]["date"] . "'" . " AND pick=" . "'" . $array[$i]["pick"] . "'";
$result = $mysqli->query($query);
$row = $result->fetch_row();
if(sizeof($row) < 1) {
    $result->close();
    $date = new DateTime();
    $date = DateTime::createFromFormat('m/d/y', $array[$i]["date"]);
    //$date = $array[$i]["date"];
    $sport = $array[$i]["sport"];
    $pick = $array[$i]["pick"];
    $score = $array[$i]["score"];
    $odds = $array[$i]["odds"];
    $size = $array[$i]["size"];
    $winloss = $array[$i]["winloss"];
    $money = $array[$i]["money"];

    echo $date->format('Y-m-d');

    $query = "INSERT INTO `db`.`vegasrunner` (`date`, `sport`, `pick`, `score`, `odds`, `size`, `winloss`, `money`) VALUES (" . "'" . $date->format('Y-m-d') . "'" . ", '$sport', '$pick', '$score', '$odds', '$size', '$winloss', '$money')";

    $mysqli->query($query);
}
    } }  
4

2 回答 2

1

我能看到的唯一合理的解释是如果createFromFormat()失败,如果输入日期不是您期望的格式,则可能会发生这种情况。

检查输入字符串是否采用您认为的格式,并更改您的代码以在createFromFormat()调用时检查失败。

于 2013-07-12T21:19:09.093 回答
0

我最终编写了自己的函数来解析日期。原来在月之前有一个隐藏的空间。

function formatDate($date) {
    //date = 07/12/13
    $date = explode('/', $date);
    //for some reason in ubuntu month had a space had to get last 2 characters
    $month = substr($date[0], -2);
    $day = trim($date[1]);
    $year = date('y') == $date[2] ? date('Y') : date('Y');

    return $year . "-" . $month . "-" . $day;
}
于 2013-07-17T16:28:24.820 回答