- Comprehensive Guide to Updating Data in a MySQL Database using PHP
- Understanding the PHP MySQL Update Syntax
- Connecting to a MySQL Database using PHP
- Updating Data in a MySQL Database using PHP
- Update data in mysql php
- Объектно-ориентированный стиль
- Список пользователей
- Обновление пользователя
- Процедурный стиль
- Список пользователей
- Обновление пользователя
- PHP MySQL Update Data
- Example (MySQLi Object-oriented)
- Example (MySQLi Procedural)
- Example (PDO)
- PHP MySQL Update Data
- The Basics
- How to Use the Update Statement
- Conclusion
- About the author
- John Otieno
Comprehensive Guide to Updating Data in a MySQL Database using PHP
Updating data in a database is an essential operation for web applications that deal with dynamic data. This article will provide you with a step-by-step guide to update data in a MySQL database using PHP.
Understanding the PHP MySQL Update Syntax
The basic syntax of updating data in a MySQL database using PHP is as follows:
$sql = "UPDATE table_name SET column1 = value1, column2 = value2, . WHERE some_column = some_value";
In this syntax, table_name is the name of the table that you want to update, column1 and column2 are the names of the columns that you want to change, value1 and value2 are the new values that you want to assign to the columns, and some_column and some_value are the conditions for updating the data.
Connecting to a MySQL Database using PHP
Before updating data in a MySQL database, you need to connect to the database using PHP. The following code demonstrates how to connect to a MySQL database using PHP:
$servername = "localhost"; $username = "username"; $password = "password"; $dbname = "database_name"; // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) < die("Connection failed: " . mysqli_connect_error()); > echo "Connected successfully"; ?>
In this code, $servername , $username , $password , and $dbname are the details of your MySQL database, and mysqli_connect() is the function used to connect to the database.
Updating Data in a MySQL Database using PHP
Once you have connected to the database, you can start updating data in the database using PHP. The following code demonstrates how to update data in a MySQL database using PHP:
$servername = "localhost"; $username = "username"; $password = "password"; $dbname = "database_name"; // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) < die("Connection failed: " . mysqli_connect_error()); > $sql = "UPDATE table_name SET column1 = value1, column2 = value2, . WHERE some_column = some_value"; if (mysqli_query($conn, $sql)) < echo "Record updated successfully"; > else < echo "Error updating record: " . mysqli_error($conn); > mysqli_close($conn); ?>
In this code, mysqli_query() is the function used to execute the update query and check if the update was successful. If the update was successful, the function will return true , and the message «Record updated successfully» will be displayed. If the update was not successful, the function will return false , and the error message will be displayed.
Update data in mysql php
В MySQL для обновления применяется sql-команда UPDATE :
UPDATE Таблица SET столбец1 = значение1, столбец2 = значение2. WHERE столбец = значение
Для примера возьмем использованную в прошлых темах таблицу Users со следующим определением:
CREATE TABLE Users (id INTEGER AUTO_INCREMENT PRIMARY KEY, name VARCHAR(30), age INTEGER)
Объектно-ориентированный стиль
Сначала определим файл index.php , который будет выводить список пользователей с ссылками на их обновление:
Список пользователей
connect_error)< die("Ошибка: " . $conn->connect_error); > $sql = "SELECT * FROM Users"; if($result = $conn->query($sql))< echo "
Имя | Возраст | |
---|---|---|
" . $row["name"] . " | "; echo "" . $row["age"] . " | "; echo "Изменить | "; echo "
Здесь используется команда SELECT, которая получает всех пользователей из таблицы Users. В таблице третий столбец хранит ссылку на скрипт update.php, который мы далее создадим и которому передается параметр id с идентификатором пользователя, которого надо изменить.
Для обновления данных определим скрипт update.php :
connect_error)< die("Ошибка: " . $conn->connect_error); > ?> real_escape_string($_GET["id"]); $sql = "SELECT * FROM Users WHERE "; if($result = $conn->query($sql))< if($result->num_rows > 0) < foreach($result as $row)< $username = $row["name"]; $userage = $row["age"]; >echo "Обновление пользователя
Имя:
Возраст:
"; > else< echo "Пользователь не найден"; > $result->free(); > else< echo "Ошибка: " . $conn->error; > > elseif (isset($_POST["id"]) && isset($_POST["name"]) && isset($_POST["age"])) < $userid = $conn->real_escape_string($_POST["id"]); $username = $conn->real_escape_string($_POST["name"]); $userage = $conn->real_escape_string($_POST["age"]); $sql = "UPDATE Users SET name = '$username', age = '$userage' WHERE "; if($result = $conn->query($sql)) < header("Location: index.php"); >else< echo "Ошибка: " . $conn->error; > > else < echo "Некорректные данные"; >$conn->close(); ?>
Весь код обновления структурно делится на две части. В первой части мы обрабатываем запрос GET. Когда пользователь нажимает на ссылку «Обновить» на странице index.php , то отправляется запрос GET, в котором передается id редактируемого пользователя.
if($_SERVER["REQUEST_METHOD"] === "GET" && isset($_GET["id"]))
И если это запрос GET, то нам надо вывести данные редактируемого пользователя в поля формы. Для этого получаем из базы данных объект по переданному id
$userid = $conn->real_escape_string($_GET["id"]); $sql = "SELECT * FROM Users WHERE "; if($result = $conn->query($sql))Далее получаем полученные данные и, если они имеются, выводим их в поля формы. Таким образом, пользователь увидит на форме данные обновляемого объекта.
Вторая часть скрипта представляет обработку POST-запроса - когда пользователь нажимает на кнопку на форме, то будет отправляться POST-запрос с отправленными данными. Мы получаем эти данные и отправляем базе данных команду UPDATE с этими данными, используя при этом параметризацию запроса:
$userid = $conn->real_escape_string($_POST["id"]); $username = $conn->real_escape_string($_POST["name"]); $userage = $conn->real_escape_string($_POST["age"]); $sql = "UPDATE Users SET name = '$username', age = '$userage' WHERE "; if($result = $conn->query($sql))После выполнения запроса к БД перенаправляем пользователя на скрипт index.php с помощью функции
Таким образом, пользователь обращается к скрипту index.php , видит таблицу с данными и нажимает на ссылку "Обновить" в одной из строк.
После нажатия его перебрасывает на скрипт update.php , который выводит данные редактируемого объекта. Пользователь изменяет данные и нажимает на кнопку.
Данные в запросе POST отправляются этому же скрипту update.php , который сохраняет данные и перенаправляет пользователя обратно на index.php .
Процедурный стиль
Список пользователей
$sql = "SELECT * FROM Users"; if($result = mysqli_query($conn, $sql))< echo "
Имя | Возраст | |
---|---|---|
" . $row["name"] . " | "; echo "" . $row["age"] . " | "; echo "Изменить | "; echo "
?> 0) < foreach($result as $row)< $username = $row["name"]; $userage = $row["age"]; >echo "Обновление пользователя
Имя:
Возраст:
"; > else< echo "Пользователь не найден"; > mysqli_free_result($result); > else < echo "Ошибка: " . mysqli_error($conn); >> elseif (isset($_POST["id"]) && isset($_POST["name"]) && isset($_POST["age"])) < $userid = mysqli_real_escape_string($conn, $_POST["id"]); $username = mysqli_real_escape_string($conn, $_POST["name"]); $userage = mysqli_real_escape_string($conn, $_POST["age"]); $sql = "UPDATE Users SET name = '$username', age = '$userage' WHERE "; if($result = mysqli_query($conn, $sql))< header("Location: index.php"); >else < echo "Ошибка: " . mysqli_error($conn); >> else < echo "Некорректные данные"; >mysqli_close($conn); ?>
PHP MySQL Update Data
The UPDATE statement is used to update existing records in a table:
Notice the WHERE clause in the UPDATE syntax: The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated!
To learn more about SQL, please visit our SQL tutorial.
Let's look at the "MyGuests" table:
id | firstname | lastname | reg_date | |
---|---|---|---|---|
1 | John | Doe | john@example.com | 2014-10-22 14:26:15 |
2 | Mary | Moe | mary@example.com | 2014-10-23 10:22:30 |
The following examples update the record with in the "MyGuests" table:
Example (MySQLi Object-oriented)
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);
>
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE ($conn->query($sql) === TRUE) echo "Record updated successfully";
> else echo "Error updating record: " . $conn->error;
>
Example (MySQLi Procedural)
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
?php
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) die("Connection failed: " . mysqli_connect_error());
>
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE (mysqli_query($conn, $sql)) echo "Record updated successfully";
> else echo "Error updating record: " . mysqli_error($conn);
>
Example (PDO)
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
?php
try $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE // Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
> catch(PDOException $e) echo $sql . "
" . $e->getMessage();
>
After the record is updated, the table will look like this:
id | firstname | lastname | reg_date | |
---|---|---|---|---|
1 | John | Doe | john@example.com | 2014-10-22 14:26:15 |
2 | Mary | Doe | mary@example.com | 2014-10-23 10:22:30 |
PHP MySQL Update Data
The PHP update statement allows you to update existing records in the database’s table. The Update clause is mainly used in combination with the WHERE clause to perform modifications and updates to the records selectively.
In this guide, you will learn how to use the Update statement to perform modifications to a MySQL table.
The Basics
The update statement is straightforward and provides a simple and easy to use syntax, as shown below:
The statement takes the table on which to perform the modifications. Next, specify the columns and the values to update. You can also include the WHERE clause only to apply the changes in the columns that match a specified condition.
If you do not specify the WHERE clause, the changes will be applied in all the columns specified.
How to Use the Update Statement
Let us illustrate how to use the Update statement on a Database using PHP. We will do this by first defining an SQL query using the UPDATE statement. Finally, we will run the query using the mysqli_query() function.
Suppose we have a table containing simple information as shown below:
If we want to update the email of one of the customers in the database, we can use an example PHP code as shown below:
$SERVERNAME = "localhost" ;
$USERNAME = "root" ;
$PASS = "mysql" ;
$DB = "sakila" ;
$conn = mysqli_connect ( $SERVERNAME , $USERNAME , $PASS , $DB ) ;
if ( $conn -> connect_error ) {
die ( "Connection to server failed: " . $conn -> connect_error ) ;
}
$query = "UPDATE customer SET email='MARY.SMITH@sakila.org' WHERE customer_id=1" ;
if ( $conn -> query ( $query ) == TRUE ) {
echo "Specified Records updated. [OK]" , " \n " ;
}
else {
echo "Record Update Fail. [Error]" , " \n " ;
}
$conn -> close ( ) ;
?>?php>
The above code starts by creating a connection to the MySQL database using the specified credentials.
We then specify an UPDATE query to change the email of the customer with an id of 1.
Once we run the query, we should see an output indicating the records have been updated successfully.
To verify the changes have been made to the database, you can query the database as shown:
As you can see from the result, the value of the email column where the was changed.
Conclusion
This guide taught you how to update records in a database’s table using PHP and the update statement. Stay tuned for more tutorials.
About the author
John Otieno
My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list