Deleting a column from a MySQL table can be done using the SQL ALTER TABLE statement.
This tutorial will guide you through the process of deleting a single column as well as multiple columns from a MySQL table using PHP.

Example Deleting a Single Column

To delete a single column from a MySQL table, you can use the ALTER TABLE statement with the DROP keyword.

syntax:
ALTER TABLE `table_name` DROP `column_name`;



<?php
$dbhost 
"localhost";
$dbuser "yourusername";
$dbpass "yourpassword";
$dbname "yourdatabase";

// Create connection
$conn mysqli_connect($dbhost$dbuser$dbpass$dbname);

// Check connection
if (!$conn) {
    die(
"Connection failed: " mysqli_connect_error());
}

// SQL statement to delete the "date" column
$sql "ALTER TABLE membership DROP `date`";

if (
mysqli_query($conn$sql)) {
    echo 
"Column deleted successfully";
} else {
    echo 
"Error deleting column: " mysqli_error($conn);
}

// Close connection
mysqli_close($conn);
?>



Example Deleting Multiple Columns

It is also possible to delete two or more columns in the MySQL table.
The process is similar to deleting a single column, with the main difference being the SQL query. To delete multiple columns from a MySQL table, you can list them in the ALTER TABLE statement, separated by commas.

syntax:

ALTER TABLE `table_name` DROP `column_name1`, DROP `column_name2`;

Example:



<?php
$dbhost 
"localhost";
$dbuser "yourusername";
$dbpass "yourpassword";
$dbname "yourdatabase";

// Create connection
$conn mysqli_connect($dbhost$dbuser$dbpass$dbname);

// Check connection
if (!$conn) {
    die(
"Connection failed: " mysqli_connect_error());
}

// SQL statement to delete the "lastname" and "date" columns
$sql "ALTER TABLE membership DROP `lastname`, DROP `date`";

if (
mysqli_query($conn$sql)) {
    echo 
"Columns deleted successfully";
} else {
    echo 
"Error deleting columns: " mysqli_error($conn);
}

// Close connection
mysqli_close($conn);
?>










Privacy Policy