如何将更新查询从mysql转换为PDO?

时间:2013-03-02 10:49:25

标签: php mysql pdo

我想将此查询转换为pdo:欢迎任何可以提供帮助的人

function updateonlinesession(){         
if(isset($_SESSION['username']['id'])){
$uid = $_SESSION['username']['id'];
$page = $_SERVER['REQUEST_URI'];
$ip = $_SERVER['REMOTE_ADDR'];
$username = $_SESSION['logged'];

("UPDATE site_user SET dateupdated  = now(),ip = '$ip' WHERE 
username = '".mysql_real_escape_string($_SESSION['username'])."'"); 
}

}
This is What I have tried 
<?php 

function updateonlinesession(){         
if(isset($_SESSION['username']['id'])){
$uid = $_SESSION['username']['id'];
$page = $_SERVER['REQUEST_URI'];
$ip = $_SERVER['REMOTE_ADDR'];
$username = $_SESSION['logged'];

$update =("UPDATE site_user SET dateupdated  = now(),ip = '$ip' WHERE 
username = '"($_SESSION['username'])."'");  
$updated_once= $con->($update);
$updated_once->execute();
}

}
?>

1 个答案:

答案 0 :(得分:2)

PDO可以具有与参数绑定的值。像这样:

function updateonlinesession(){         
  if(isset($_SESSION['username']['id'])){
    $uid = $_SESSION['username']['id'];
    $page = $_SERVER['REQUEST_URI'];
    $ip = $_SERVER['REMOTE_ADDR'];
    $username = $_SESSION['logged'];
    $update = "UPDATE site_user SET dateupdated  = now(), ip = ? WHERE username = ?");  
    $updated_once = $con->prepare($update);
    $updated_once->bindParam(1, $ip, PDO::PARAM_STR );
    $updated_once->bindParam(2, $username, PDO::PARAM_STR );
    $updated_once->execute();
  }
}