Forum Moderators: open

Message Too Old, No Replies

Checking if index exists before alter table command

         

ionchannels

3:34 am on Dec 20, 2005 (gmt 0)

10+ Year Member



I am writing a PHP script to add indexes and whatnot to my 50 or so mysql databases. The problem is that I have added some indexes manually to a few sites during testing. Is there a way to use the alter table command to only add an index if it doesn't already exist, analagous to the create table if not exists command? thanks...

ionchannels

4:20 am on Dec 20, 2005 (gmt 0)

10+ Year Member



I found a solution, but it is rather annoying. I use show keys from parse the values and check for the index name that way - here is the PHP code if you are interested...

$tablename="wordlist";
$indexname="docid";
$indexsize=10;
$indexdesc="Documentid";

$sql="SHOW KEYS FROM $tablename";
$res = mysql_query($sql, $db) or die(mysql_error());
$present="no";
while ($row = mysql_fetch_assoc($res))
{
if ($row['Column_name']=="$indexname")
{
$present="yes";
}
}
if ($present=="no")
{
$sql="ALTER TABLE $tablename ADD INDEX $indexdesc ( $indexname ( $indexsize ) ) ";
$result=mysql_query($sql,$db);
if ($result)
{
echo "<BR>Added index $indexname to table $tablename<BR>";
}
}