How can I check if mysql table column even exists?

后端 未结 8 942
闹比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: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;
    } 
    

提交回复
热议问题