PHP and SQL question

Discussion in 'Web Design and Development' started by noelister, Jun 4, 2006.

  1. noelister macrumors 6502

    Joined:
    Jan 15, 2005
    #1
    Hello,

    I was hoping that someone on here could help me out. I am trying to write a little program that reads a form and then writes it to a DB. However, I would like to check to see if the table exist first if so use that table if not create the table.

    kinda like

    PSEUDO CODE

    if(tableName == tableName){
    SELECT TABLE
    }else{
    CREATE TABLE
    }

    I know I would have to loop through the DB to see what tables exist. I'm just unsure of the format and syntax.

    Thanks for the help
    N
     
  2. Mitthrawnuruodo Moderator emeritus

    Mitthrawnuruodo

    Joined:
    Mar 10, 2004
    Location:
    Bergen, Norway
    #2
    What you should be able to do is use something like

    CREATE TABLE IF NOT EXISTS 'tablename' (...)

    but I've never done that from a PHP page, just when setting up new tables via phpMyAdmin (or command line mysql administrating).

    Once it's made (or not if it existed), you can make querys against it...
     
  3. noelister thread starter macrumors 6502

    Joined:
    Jan 15, 2005
    #3
    Okay,

    Is that the SQL statement to do that (CREATE TABLE IF NOT EXIST)? Like you said i usually create my DB and table with myphpadmin.
     
  4. Mitthrawnuruodo Moderator emeritus

    Mitthrawnuruodo

    Joined:
    Mar 10, 2004
    Location:
    Bergen, Norway
    #4
    Yes, that's the mysql I usually use to make new tables via phpMyAdmin:

    Code:
    -- 
    -- Table structure for table `files`
    -- 
    
    DROP TABLE IF EXISTS `files`;
    CREATE TABLE IF NOT EXISTS `files` (
      `id` int(11) NOT NULL auto_increment,
      `parent` int(11) NOT NULL default '0',
      `file` varchar(255) NOT NULL default '',
      `thumb` varchar(255) NOT NULL default '',
      `desc` varchar(255) NOT NULL default '',
      PRIMARY KEY  (`id`)
    ) TYPE=MyISAM;
    You could try something like:

    PHP:
    mysql_query("CREATE TABLE IF NOT EXISTS `files` (
      `id` int(11) NOT NULL auto_increment,
      `parent` int(11) NOT NULL default '0',
      `file` varchar(255) NOT NULL default '',
      `thumb` varchar(255) NOT NULL default '',
      `desc` varchar(255) NOT NULL default '',
      PRIMARY KEY  (`id`)
    "
    ) or die ("Something's wrong!");
     
  5. noelister thread starter macrumors 6502

    Joined:
    Jan 15, 2005

Share This Page