MySQL RENAME TABLE

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 more than one table atomically

RENAME TABLE
    student TO student_old,
    student_new TO student;

PHP PDO example

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);
?>

Generate prefixed table names in PHP

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];

Remove a known prefix

$newName = substr($row[0], 9);

Replace a prefix

$newName = str_replace('plus2net_', 'mysite_', $row[0]);
Do not execute a generated 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.
Renaming a table can break application code, views, routines or integrations that still reference the old name. Review dependencies before running the statement.



Subscribe to our YouTube Channel here



plus2net.com
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.




SQL Video Tutorials










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer