我正在使用bellow查询进行更新,但现在我尝试将其更改为pdo,但无法正常工作 如有任何帮助,将不胜感激
function updateonlinesession(){
if(isset($_SESSION['username']['id'])){
$uid = $_SESSION['username']['id'];
$page = $_SERVER['REQUEST_URI'];
$ip = $_SERVER['REMOTE_ADDR'];
$username = $_SESSION['logged'];
mysql_query("UPDATE site_user SET dateupdated = now(),ip = '$ip' WHERE
username = '".mysql_real_escape_string($_SESSION['username'])."'");
}
}
这是我尝试使用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 = '$ip' WHERE
username = '".($_SESSION['username'])."'");
$sth_update= $con->prepare($update);
$sth_update->execute();
}
}
?>
答案 0 :(得分:5)
// connetion
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// query
$sql = "UPDATE site_user SET dateupdated = NOW(), ip = ?
WHERE username = ?";
$q = $conn->prepare($sql);
$q->execute(array($ip, $_SESSION['username']);
答案 1 :(得分:5)
首先,连接bootstrap / config文件中的某个地方:
$dsn = 'mysql:dbname=test;host=localhost;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, $user, $pass, $opt);
然后,运行您的查询
function updateonlinesession(){
global $pdo;
if(isset($_SESSION['username']['id'])){
$sql = "UPDATE site_user SET dateupdated=now(),ip=? WHERE username=?";
$pdo->prepare($sql);
$pdo->execute(array($_SERVER['REMOTE_ADDR'], $_SESSION['logged']));
}
}
确保您使用的所有变量都具有正确的值(var_dump($_SESSION)
就足够了)
答案 2 :(得分:3)
$stmt = $db->prepare("UPDATE site_user SET dateupdated=now(), ip=? WHERE username=?");
$stmt->execute(array($ip, $_SESSION['username']));
$affected_rows = $stmt->rowCount();
其中$db
是您的连接
答案 3 :(得分:2)
function updateonlinesession(){
if(isset($_SESSION['username']['id'])){
$uid = $_SESSION['username']['id'];
$page = $_SERVER['REQUEST_URI'];
$ip = $_SERVER['REMOTE_ADDR'];
$username = $_SESSION['logged'];
//Establish your PDO object.
$pdo = new PDO("mysql:host=localhost;dbname=mydb", "username", "password");
//Prepare your statement.
$stmt = $pdo->prepare("UPDATE site_user SET dateupdate = now(), ip = ? WHERE username = ?");
$stmt->execute(array(
$ip,
$_SESSION['username']
));
$stmt->closeCursor();
}
}