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_nameis the name of the table to be altered,column_nameis the name of the new column to be added, anddatatypeis 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 write an update query in MySQL using PHP?
- How to use a MySQL union in PHP?
- How to export data from MySQL to Excel using PHP?
- How to connect to a MySQL database using PHP?
- How to set a timeout for MySQL query in PHP?
- How to create an SSL connection to MySQL using PHP?
- What port to connect to MySQL from PHP?
- How to output XML from MySQL using PHP?
- How to generate a UUID in MySQL using PHP?
- How to change database in MySQL with PHP?
See more codes...