Update Data

PHP MySQL Update Data
  • In PHP to update data to use a update query is used.
  • syntax
    UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value

MySQLi Object-Oriented

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "student";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "UPDATE student_data SET first_name='ram' WHERE id=2";

if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

$conn->close();
?>

MySQLi Procedural

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "student";

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

$sql = "UPDATE student_data SET first_name='rama' WHERE id=2";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

PDO

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "student";

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 student_data SET first_name='rama' WHERE id=2";

// 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();
}

$conn = null;
?>



Related Posts :