我是PHP新手。如果数据存在,我需要帮助制作一个PHP代码来更新MySQL中的数据,如果还没有,那么在MySQL中插入数据..我已经制作了PHP代码但是数据已存在时插入数据..在MySQL中..请帮忙
$con = mysql_connect('localhost','root','root');
$db = mysql_select_db('gamingtracker',$con);
$query = "SELECT * FROM servers WHERE sgame='$game_insert'";
$result = mysql_query($query, $con);
While($row = mysql_fetch_array($result)) {
$id = @$row['id'];
$sname = @$row['sname'];
$sgame = @$row['sgame'];
$minplayers = @$row['minplayers'];
$maxplayers = @$row['maxplayers'];
$ip = @$row['ip'];
$port = @$row['port'];
$map = @$row['map'];
}
$sname1= html_entity_decode("{$server['s']['name']}");
if(@$sname=="{$server['s']['name']}"
AND @$sgame=="{$server['s']['game']}"
AND @$minplayers=="{$server['s']['players']}"
AND @$maxplayers=="{$server['s']['playersmax']}"
AND @$ip=="{$server['b']['ip']}"
AND @$port=="{$server['b']['c_port']}"
AND @$map=="{$server['s']['map']}" )
{
$query1 = "UPDATE servers
SET sname='$sname1', sgame='{$server['s']['game']}', minplayers='{$server['s']['players']}', maxplayers='{$server['s']['playersmax']}', ip='{$server['b']['ip']}', port='{$server['b']['port']}', map='{$server['s']['map']}'
WHERE ip='{$server['b']['ip']}', port='{$server['b']['port']}', sgame='{$server['s']['game']}'";
$result1 = mysql_query($query1, $con);
}
else {
$query1 = "INSERT INTO servers (id,sname,sgame,maxplayers,minplayers,ip,port,map) VALUES ('','$sname1','{$server['s']['game']}','{$server['s']['players']}','{$server['s']['playersmax']}','{$server['b']['ip']}','{$server['b']['c_port']}','{$server['s']['map']}')";
$result1 = mysql_query($query1, $con);
}
答案 0 :(得分:0)
所以你只需要为ip,port和sgame的每个独特组合输入一个条目?最简单的方法是让mysql处理这个。
首先,在表格上为这些字段创建唯一索引。在mysql中运行以下命令:
CREATE UNIQUE INDEX ip_port_sgame ON servers (ip, port, sgame);
然后,使用REPLACE而不是运行INSERT查询。所以只需在php中更改这一行:
UPDATE servers
到
REPLACE INTO servers