Use RENAME TABLE to change a table name without copying its rows.
RENAME TABLE student TO student_new;
You can also rename a table with ALTER TABLE ... RENAME TO.
RENAME TABLE
student TO student_old,
student_new TO student;
Table names are SQL identifiers, so they cannot be supplied through normal PDO value placeholders. If a table name comes from application logic, validate it against an allow-list before building the statement.
<?php
require 'config.php';
$allowedTables = ['student', 'student_new'];
$oldName = 'student';
$newName = 'student_new';
if (!in_array($oldName, $allowedTables, true) ||
!in_array($newName, $allowedTables, true)) {
throw new InvalidArgumentException('Invalid table name');
}
$sql = "RENAME TABLE `$oldName` TO `$newName`";
$dbo->exec($sql);
?>
The original tutorial also demonstrated renaming many tables by adding or replacing a prefix. Keep identifier handling separate from data-value placeholders and validate every generated identifier before executing it.
$oldName = $row[0];
$newName = 'plus2net_' . $row[0];
$newName = substr($row[0], 9);
$newName = str_replace('plus2net_', 'mysite_', $row[0]);
RENAME TABLE statement until both old and new identifiers have passed a strict identifier rule or allow-list. Back up important schemas before bulk renaming.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| Edward | 11-03-2015 |
| Fatal error: Call to a member function prepare() on a non-object on line 18 Line 18: $count=$dbo->prepare("rename table MyGuests to Marker"); Thanks for trying! | |
| smo | 12-03-2015 |
| Check your config.php file for database connection, $dbo is correctly connected or not. | |