dongzouban9871 2013-01-28 02:33
浏览 19
已采纳

PHP mySQLi更新表

Currently, I am using PHP to get some from the backend and insert into the database using mysqli. Below is the code used:

$conn = new mysqli('localhost', 'username', 'pwd', 'db');

// check connection
if (mysqli_connect_errno()) {
  exit('Connect failed: '. mysqli_connect_error());
}

$sql = "INSERT INTO `birthday` (`birthday`) VALUES ('$birthday')";

// Performs the $sql query and get the auto ID
if ($conn->query($sql) === TRUE) {
  echo 'The auto ID is: '. $conn->insert_id;
}
else {
  echo 'Error: '. $conn->error;
}

Now if I am going to fetch the information again, how to I update this value? Currently, it will create another row and insert the value again.

Thanks In Advance

  • 写回答

2条回答 默认 最新

  • douzi2778 2013-01-28 02:48
    关注

    What I typically do is something like this.

    Also, you need to make sure you have a field or something that is unique to this record. Basically, it will always INSERT the way it's written, since we're just checking one value (birthday)

    Here's an example

    $conn = new mysqli('localhost', 'username', 'pwd', 'db');
    
        // check connection
        if (mysqli_connect_errno()) {
          exit('Connect failed: '. mysqli_connect_error());
        }          
                // check to see if the value you are entering is already there      
                $result = $conn->query("SELECT * FROM birthday WHERE name='Joe'");
                if ($result->num_rows > 0){ 
                    // this person already has a b-day saved, update it
                    $conn->query("UPDATE birthday SET birthday = '$birthday' WHERE name = 'Joe'");
                }else{
                    // this person is not in the DB, create a new ecord
                    $conn->query("INSERT INTO `birthday` (`birthday`,`name`) VALUES ('$birthday','Joe')");
                }    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?