UPDATE - Modifying Database Records

This section describes how to update existing records in database.

If you want to modify existing records in the database, you should write a SQL UPDATE statement, and send it to the MySQL server for execution with the mysql_query() function. After that you can call the mysql_affected_rows() function to find out how many records were updated.

The example PHP script below shows you how to update the record of a specified ID value:

<?php 
#- MySQL-Update.php
#- Copyright (c) 2015, HerongYang.com, All Rights Reserved.
#
  $con = mysql_connect("localhost", "Herong", "TopSecret");
  $ok = mysql_select_db("HerongDB", $con);
  
  $sql = "UPDATE Comment SET Name = 'Herong Yang' WHERE ID = 1";
  if (mysql_query($sql, $con)) {
    print("Number of rows updated: ".mysql_affected_rows()."\n");
  } else {
    print("SQL statement failed.\n");
    print(mysql_errno($con).": ".mysql_error($con)."\n"); 
  }

  mysql_close($con); 
?>

The output of the script tells us that one record was updated. To know if the update was done correctly or not, you can run a query to validate.

C:\>\local\php\php MySQL-Update.php
Number of rows updated: 1

Last update: 2015.

Table of Contents

 About This Book

 PHP Installation on Windows Systems

 Integrating PHP with Apache Web Server

 charset="*" - Encodings on Chinese Web Pages

 Chinese Characters in PHP String Literals

 Multibyte String Functions in UTF-8 Encoding

 Input Text Data from Web Forms

 Input Chinese Text Data from Web Forms

 MySQL - Installation on Windows

MySQL - Connecting PHP to Database

 php_mysql.dll - Configuring PHP to Use MySQL Module

 Commonly Used MySQL Functions

 mysql_connect() - Creating MySQL Connections

 INSERT INTO - Inserting New Records

 SELECT - Running Database Queries

UPDATE - Modifying Database Records

 MySQL - Character Set and Encoding

 MySQL - Sending Non-ASCII Text to MySQL

 Retrieving Chinese Text from Database to Web Pages

 Input Chinese Text Data to MySQL Database

 References

 PDF Printing Version