PHP删除MySQL里一个表里面的行的代码

主机:localhost用户名:xauth密码:xauthpassword数据库:xauth
删除xauth数据库中session表中的第一列accountid为$id的呢一行。
之前的代码是这样的
<?php

$username = $_GET["username"];
$password = $_GET["password"];
date_default_timezone_set('Asia/Shanghai');
$con = mysql_connect('localhost', 'xauth', 'xauthpassword') or die(mysql_error());
mysql_query('set names utf8', $con);
mysql_query('use xauth', $con) or die(mysql_error());
$sql = 'select * from accounts where playername="' . $username . '"';
$res = mysql_query($sql, $con);
$row = mysql_fetch_assoc($res);
if (empty($row)) {
echo "not exist";
exit();
}
if ($row['realpw'] != $password) {
echo "password wrong";
exit();
}
$id = $row['id'];
$sql2 = 'select * from sessions where accountid=' . $id;
$res2 = mysql_query($sql2, $con);
$row2 = mysql_fetch_assoc($res2);
if (empty($row2)) {
=====要放在这,不管有没有都尝试删除accountid为$id的一行======
mysql_query('insert into sessions values ("' . $id . '","' . $_SERVER['REMOTE_ADDR'] . '","' . date('Y-m-d H:i:s') . '")');
} else {
mysql_query('update sessions set ipaddress="' . $_SERVER['REMOTE_ADDR'] . '", logintime=' . date('Y-m-d H:i:s') . '" where accountid=' . $id);
}
echo "success!";
?>

$username = $_GET["username"]; 
$password = $_GET["password"];
date_default_timezone_set('Asia/Shanghai');
$con = mysql_connect('localhost', 'xauth', 'xauthpassword') or die(mysql_error());
mysql_query('set names utf8', $con);
mysql_select_db('xauth',$con);
$sql = 'select * from accounts where playername="' . $username . '"';
$res = mysql_query($sql, $con);
$row = mysql_fetch_assoc($res);
if (empty($row)) {
    echo "not exist";
    exit();
}
if ($row['realpw'] != $password) {
    echo "password wrong";
    exit();
}
$id = $row['id'];
$sql2 = 'select * from sessions where accountid=' . $id;
$res2 = mysql_query($sql2, $con);
$row2 = mysql_fetch_assoc($res2);
if (empty($row2)) {
//=====要放在这,不管有没有都尝试删除accountid为$id的一行======
    mysql_query('delete from sessions where accountid='.$id,$con);
    mysql_query('insert into sessions values ("' . $id . '","' . $_SERVER['REMOTE_ADDR'] . '","' . date('Y-m-d H:i:s') . '")',$con);
} else {
    mysql_query('update sessions set ipaddress="' . $_SERVER['REMOTE_ADDR'] . '", logintime=' . date('Y-m-d H:i:s') . '" where accountid=' . $id,$con);
}
echo "success!";

温馨提示:内容为网友见解,仅供参考
第1个回答  2014-07-18
以下两行需要合并:
mysql_query('use xauth', $con) or die(mysql_error());
$sql = 'select * from accounts where playername="' . $username . '"';

合并为一行:
$sql = 'select * from xauth.accounts where playername="' . $username . '"';

理由:
无需选择数据库,可以把数据库加在SQL语句的表名前面既可。而且选择数据库应该使用mysql_select_db('xauth');这样的语句。本回答被网友采纳
相似回答