How can I check if mysql table column even exists?

后端 未结 8 944
闹比i
闹比i 2020-12-30 08:44

How can I check if mysql table field even exists ?

The column name is \'price\' and I need to see if it exists.

Haven\'t understood really how the \'EXISTS\'

相关标签:
8条回答
  • 2020-12-30 09:13

    I just done something like this using this function for Wordpress, this for update tables that having new chnages on it

    public function alterTable() {
    
        $table_name = $this->prefix . $this->tables['name'];
    
        $select = "select * from `{$table_name}` where 0=0 limit 1;";
        $query = $this->db->get_results($select, ARRAY_A);
    
    
        if (isset($query[0]) && !key_exists('adv', $query[0])) {
            $sql = "ALTER TABLE `{$table_name}` ADD `me` INT NULL DEFAULT NULL ;";
            $this->db->query($sql);
        }
    

    }

    0 讨论(0)
  • 2020-12-30 09:18

    well here is a function to check out if a particular column exists or not.

    public function detect_column($my_db, $table, $column)
    {
        $db = mysql_select_db($my_db); //select the database
        $sql = "SHOW COLUMNS FROM $table LIKE '$column'"; //query
        $result = mysql_query($sql);                     //querying
        if(mysql_num_rows($result) == 0)        //checks the absence of column
            echo "column $column doesn't exist !";
            // write your code here! 
        else
            echo "column $column exists!";
    }
    

    well if you are designing a frame work, then this function may come to your aid. This function checks for the presence of column when $flag is set to '1' and absence of column when $flag is set to '0'.

    public function detect_column($my_db, $table, $column, $flag)
    {
        $this->select_db($my_db); //select the database
        $sql = "SHOW COLUMNS FROM $table LIKE '$column'";
        $result = mysql_query($sql);
        if(mysql_num_rows($result) == $flag)
            return true;
        else
            return false;
    } 
    
    0 讨论(0)
提交回复
热议问题