PDO预处理语句:如果缺少值,则使用NULL

时间:2014-10-14 17:21:46

标签: php mysql pdo prepared-statement

我有一个准备好的语句来在我的数据库中存储一些来自API的数据:

$sql = "INSERT INTO `standings` (`league_id`, `season`, `position`, `team_id`, `played`, `playedathome`, `playedaway`, `won`, `draw`, `lost`, `numberofshots`, `yellowcards`, `redcards`, `goals_for`, `goals_against`, `points`)
VALUES (:league_id, :season, :position, :team_id, :played, :playedathome, :playedaway, :won, :draw, :lost, :numberofshots, :yellowcards, :redcards, :goals_for, :goals_against, :points)
ON DUPLICATE KEY UPDATE `league_id`=:league_id, `season`=:season, `position`=:position, `team_id`=:team_id, `played`=:played, `playedathome`=:playedathome, `playedaway`=:playedaway, `won`=:won, `draw`=:draw, `lost`=:lost, `numberofshots`=:numberofshots, `yellowcards`=:yellowcards, `redcards`=:redcards, `goals_for`=:goals_for, `goals_against`=:goals_against, `points`=:points";

$prep = $pdo->prepare($sql);

$prep->bindParam(':league_id', $league_id);
$prep->bindParam(':season', $season);
$prep->bindParam(':position', $position);
$prep->bindParam(':team_id', $team_id);
$prep->bindParam(':played', $played);
$prep->bindParam(':playedathome', $playedathome);
$prep->bindParam(':playedaway', $playedaway);
$prep->bindParam(':won', $won);
$prep->bindParam(':draw', $draw);
$prep->bindParam(':lost', $lost);
$prep->bindParam(':numberofshots', $numberofshots);
$prep->bindParam(':yellowcards', $yellowcards);
$prep->bindParam(':redcards', $redcards);
$prep->bindParam(':goals_for', $goals_for);
$prep->bindParam(':goals_against', $goals_against);
$prep->bindParam(':points', $points);


foreach($result->TeamLeagueStanding as $standing){

    $team_id = $standing->Team_Id;
    $played = $standing->Played;
    $playedathome = $standing->PlayedAtHome;
    $playedaway = $standing->PlayedAway;
    $won = $standing->Won;
    $draw = $standing->Draw;
    $lost = $standing->Lost;
    $numberofshots = $standing->NumberOfShots;
    [etc...]


    $prep->execute() or print("PDO execute error: ".$prep->errorInfo()[2]);

问题是某些联盟没有提供NumberOfShots值,因此$standing->NumberOfShots是一个空字符串,导致错误:

  

PDO执行错误:错误的整数值:''对于第1行的列'numberofshots'

该行未插入。

我如何制作类似

的内容
if($numberofshot == "")
    $numberofshot = NULL;

或告诉PDO使用默认值而不是抛出错误,如果值不正确?

2 个答案:

答案 0 :(得分:1)

如果此参数需要整数值,则应将其强制转换为整数 比如使用intval()函数。

$numberofshots = intval($standing->NumberOfShots);

如果$standing->NumberOfShots中有一些字符串,则会将其转换为0

的数字

答案 1 :(得分:1)

http://php.net/manual/en/pdo.setattribute.php

尝试:

setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_EMPTY_STRING);