如果存在,如何更新其他插入php mysql

时间:2016-12-05 05:18:48

标签: php mysql

如果ID已存在,我想更新我的数据库,如果ID不存在,我想插入。

process.php:

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "maindata";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
 die("<center>Connection failed: " . mysqli_connect_error() . "</center");
}     

$id = $_POST['id'];   
$aname = $_POST['aname'];   
$xsummary = $_POST['xsummary'];

$sql=mysql_query("SELECT * FROM info WHERE ID = $id");

if (mysql_num_rows($sql) == $id) 
{
 $sql="update info set AccountName= '$aname', ExecutiveSummary='$xsummary'";
} 
else {
 $sql="insert into AccountName= '$aname', ExecutiveSummary= '$xsummary'";
}

有人帮我解决了我的问题。

提前致谢。

2 个答案:

答案 0 :(得分:1)

请查看下面的代码。

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "maindata";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("<center>Connection failed: " . mysqli_connect_error() . "</center");
}     

$id = $_POST['id'];   
$aname = $_POST['aname'];   
$xsummary = $_POST['xsummary'];

$sql=mysqli_query($conn, "SELECT * FROM info WHERE ID = $id");

if (mysqli_num_rows($sql) > 0) 
{
    $sqlUpdate="update info set AccountName= '$aname', ExecutiveSummary= '$xsummary'";
    mysqli_query($conn,$sqlUpdate);
} else {
    $sqlInsert="insert into info set AccountName= '$aname', ExecutiveSummary= '$xsummary'";
    mysqli_query($conn,$sqlInsert);
}

您在代码中的实际问题,您是使用mysqli的连接数据库,但是使用mysql从表中获取数据。请使用此代码,并且可以正常工作。

*注意: - 插入语句中有错误,请更新,这将有效。

答案 1 :(得分:0)

一切都很好,需要更换 的

    if (mysql_num_rows() == $id) 
    {
     $sql="update info set AccountName= '$aname', ExecutiveSummary='$xsummary'";
    } 

<强>与

mysql_query($sql);
if (mysql_num_rows()>0) 
{
 $sql="update info set AccountName= '$aname', ExecutiveSummary='$xsummary' where ID= $id";
}