php-mysqlHow to alter a table in a MySQL database using PHP?
Altering a table in a MySQL database using PHP is a simple process. The following example code block shows how to add a new column to an existing table:
$sql = "ALTER TABLE table_name ADD column_name datatype";
if ($conn->query($sql) === TRUE) {
echo "Column added successfully";
} else {
echo "Error adding column: " . $conn->error;
}
Output example
Column added successfully
Code explanation
-
$sql = "ALTER TABLE table_name ADD column_name datatype";
- This line of code creates a SQL query to alter the table.table_name
is the name of the table to be altered,column_name
is the name of the new column to be added, anddatatype
is the data type of the new column. -
if ($conn->query($sql) === TRUE) {
- This line of code checks if the query was successful. -
echo "Column added successfully";
- This line of code prints a success message if the query was successful. -
echo "Error adding column: " . $conn->error;
- This line of code prints an error message if the query was unsuccessful.
Helpful links
More of Php Mysql
- How to use utf8mb4_unicode_ci in MySQL with PHP?
- How to join tables with PHP and MySQL?
- How to get the version of MySQL using PHP?
- How to write an update query in MySQL using PHP?
- How to count the number of resulting rows in a MySQL database using PHP?
- How to use a MySQL union in PHP?
- How to set a timeout for MySQL query in PHP?
- How to create an SSL connection to MySQL using PHP?
- How to get the last insert ID in PHP MySQL?
- How to fetch data from MySQL in PHP?
See more codes...