防止Mysql覆盖数据

时间:2014-10-11 06:43:27

标签: php html mysql sql web

我正在尝试向列purchased

中的现有字符串添加更多数据(加入)

我使用这个PHP代码:

 $id=$_GET["id"];    
 $username=$_SESSION['username'];
 $sql="UPDATE `users` SET `purchased` = `purchased`.' $id' WHERE `username`='$username'";
 mysql_query($sql);

如果当前用户的purchased列包含值0,那么在此查询(id = 1)之后它应该变为

0 1但是它会覆盖现有数据并成为1我如何将此(space)1加入到我的Mysql列中的现有0而不会覆盖任何内容,只需加入现有数据即可串

2 个答案:

答案 0 :(得分:0)

解决方法通过获取现有值并在PHP中加入字符串

$id = $_GET["id"];    
$username = $_SESSION['username'];
$sql = "SELECT `purchased` FROM `users` WHERE `username` = '".$_SESSION['username']."'";
$data = mysql_query($sql);
while($row = mysql_fetch_row($data)) {
    $ep = $row[0];
}
$newData = ''.$ep.' '.$id.'';
$sql="UPDATE `users` SET `purchased` = '$newData' WHERE `username`='$username'";
mysql_query($sql);

答案 1 :(得分:0)

这就是答案:

$id = $_GET["id"];    
$username = $_SESSION['username'];
try {
    $dbh = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
    $sth = $dbh->prepare('UPDATE `users` SET `purchased` = CONCAT(`purchased`,?) WHERE `username`=?');
    $sth->bindParam(1, $id, PDO::PARAM_INT);
    $sth->bindParam(2, $username, PDO::PARAM_STR);
    $sth->execute();
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}