每次新数据可用时,我都试图替换MYSQL数据库中的先前条目,我有以下PHP代码,但似乎每次都添加新条目。请帮助,谢谢。
我尝试过使用REPLACE但它仍然不起作用,有人能告诉我它是做错了吗?
<?php
header('Content-Type: application/json');
$data = json_decode(file_get_contents('php://input'), true);
$mysqli = new mysqli("localhost","dbuser","Pa55uu0Rd","iewdb");
if (mysqli_connect_errno())
{
echo json_encode(array('error' => 'Failed to connect to MySQL: ' . mysqli_connect_error() ));
return;
}
if(!$data)
{
echo json_encode(array('error' => 'Error input data'));
return;
}
$usernme = $data['usernme'];
$longitude = $data['longitude'];
$latitude = $data['latitude'];
$user = $mysqli->query("SELECT id FROM Users WHERE usernme = '$usernme' LIMIT 1");
$user_id = $user->fetch_object();
if(!$user_id)
{
$mysqli->query("INSERT INTO Users (usernme) VALUES ('$usernme');");
$user_id->id = $mysqli->insert_id;
}
if($longitude && $latitude)
{
$mysqli->query("REPLACE INTO Locations (User_id,Longitude, Latitude) VALUES ($user_id->id,$longitude,$latitude);");
}
$mysqli->close();
echo json_encode(array('user_id' => $user_id->id));
答案 0 :(得分:1)
逻辑:您可以删除旧条目,然后在数据库中添加新条目,以便在性能方面始终保持良好状态,而不是替换旧条目。
因此,您必须编写一个删除并仅插入查询...而不是3个查询
答案 1 :(得分:1)
使用像这样的更新查询
UPDATE MyTable
SET User_id = 'USER_ID_VALUE', Longitude='LONGITUDE_VALUE', Latitude='LATITUDE_VALUE'
WHERE SomeOtherColumn LIKE '%PATTERN%'
答案 2 :(得分:1)
这是我对问题的解决方案,它运作得很好。我决定选择UPDATE,因为我认为这是最整洁的,感谢您的帮助。
<?php
header('Content-Type: application/json');
//get parameters
$data = json_decode(file_get_contents('php://input'), true);
// Create connection
$mysqli = new mysqli("localhost","dbuser","Pa55w0rd","ewdb");
// Check connection
if (mysqli_connect_errno())
{
echo json_encode(array('error' => 'Failed to connect to MySQL: ' . mysqli_connect_error() ));
return;
}
if(!$data)
{
echo json_encode(array('error' => 'Error input data'));
return;
}
$usernme = $data['usernme'];
$longitude = $data['longitude'];
$latitude = $data['latitude'];
$user = $mysqli->query("SELECT id FROM Users WHERE usernme = '$usernme' LIMIT 1");
$user_id = $user->fetch_object();
if(!$user_id)
{
$mysqli->query("INSERT INTO Users (usernme) VALUES ('$usernme');");
$user_id->id = $mysqli->insert_id;
$mysqli->query("INSERT INTO Locations (User_id) VALUES ($user_id->id);");
}
if($longitude && $latitude)
{
$mysqli->query("UPDATE Locations SET Longitude = $longitude, Latitude = $latitude WHERE User_id = $user_id->id;");
}
/* close connection */
$mysqli->close();
echo json_encode(array('user_id' => $user_id->id));