PDA

View Full Version : SQL Query - Check Existance of Data/Column before making changes.


DaNIEL MeNTED
11-20-2006, 02:19 PM
Hi Guys... I have 2 questions.

1) During an install I'm using "CREATE TABLE IF NOT EXISTS" to create tables but there's no similar option for ALTER TABLE so what is the best way to check if a column already exists in the users table?

2) During the same install I'm using INSERT INTO to populate a table... how do I check if the table is empy first?

THX!

Right now I'm just ignoring errors using $vbulletin->db->hide_errors(); but I'd rather do a proper check.

Paul M
11-20-2006, 02:24 PM
Quick answers ;

1. Use DESCRIBE table and loop through the results looking for the fieldname.

2. Use SELECT * FROM table LIMIT 1 If the number of rows returned = 1 then you have records in the table.

DaNIEL MeNTED
11-20-2006, 02:28 PM
* DaNIEL MeNTED wishes the quick answers were long. :confused:

Off to go look for code.

Hmm... found and modified this for columns. Is there a cleaner way to do it?

$query = $vbulletin->db->query("SHOW COLUMNS FROM " . TABLE_PREFIX . "table LIKE 'column'") or die(mysql_error());

if (mysql_num_rows($query) == 0) { insert column }



And for rows in a table:


$query = $vbulletin->db->query("SELECT * FROM " . TABLE_PREFIX . "table LIMIT 1") or die(mysql_error());

if (mysql_num_rows($query) == 0) { add rows }


Make sense?