3

In my application I have a generic query that applies to multiple users. There are instances where the table structure may differ between users. I have a query that I only want to apply to the users where the column exists in their table.

function get_item($user_id) {

    global $dbh;

    $sth = $dbh->query ("SELECT item_type FROM items WHERE user_id = '$user_id'");

    $row = $sth->fetch();

    $item_type = $row['item_type'];

    return $item_type;

}

If the column 'item_type' does not exist in my table, I want to ignore it, and set the $item_type variable to NULL.

For these users, I am getting the error on the query line of code:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'item_type' in 'field list' in /item_display.php:5

Any ideas?

7
  • Can you not do a SELECT * on the table, and then check in the PHP to see if $row['item_type'] is set? Commented May 18, 2012 at 17:31
  • 2
    Take a look at this answer. stackoverflow.com/a/7091984/212940 Commented May 18, 2012 at 17:32
  • possible duplicate of php pdo: get the columns name of a table Commented May 18, 2012 at 17:34
  • @andrewsi if i do this, a NULL value (i.e. unanswered value) does not distinguish those from ones that do not exist in the table. Commented May 18, 2012 at 18:09
  • 1
    Ah, so it does - I didn't know that. On the other hand, $row will have a key for 'item_type', so you could check to see if that's present, instead? Commented May 18, 2012 at 18:27

4 Answers 4

13

I don't know if it helps you, but you can try this:

if (count($dbh->query("SHOW COLUMNS FROM `items` LIKE 'item_type'")->fetchAll())) {
    $sth = $dbh->query ("SELECT item_type FROM items WHERE user_id = '$user_id'");
    $row = $sth->fetch();
    $item_type = $row['item_type'];
} else {
    $item_type = null;
}

It checks if the column exists and performs the task.

Sign up to request clarification or add additional context in comments.

2 Comments

+1, but that doubles the number of queries. So it should be used with care and not in a frequent manner.
True. I was also thinking that both queries could be merged in one but can't check it at the moment.
9

Use the SHOW COLUMNS query:

SHOW COLUMNS FROM <table> WHERE Field = '<column>'

If a row is returned, the column exists.

Comments

2

You can also let PDO throw exceptions and catch those to parse the MySQL-error.

/**
 * Enable PDO exceptions.
 * @see http://php.net/pdo.setattribute.php
 */
$pdoObject->setAttribute ( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

try
{
    $pdoStatement->execute();
}
catch( PDOException $e )
{
    if ($e->errorInfo[1] == 1054)
    {
        /* Column not found */
        return false;
    } else {
        /* some other PDO-error */
        throw $e;
    }
}

Comments

-1

try this; pdo php7

function isColumnExists($column, $table) {
    try {
        
        if (empty ($table) || empty ($column)) {
            return FALSE;
        }

        $stmt = $this->db->prepare("SHOW COLUMNS FROM $table LIKE :column");
        $stmt->execute(array("column" => $column));
        $row = $stmt->fetchColumn();
        if ($row != FALSE) {
            return TRUE;
        } else {
            return FALSE;
        }

    } catch (PDOException $e) {
        return FALSE;
    }
}

1 Comment

FYI, you shouldn't return false in case of mysql error. On the contrary, you need to get that error, which will make you aware of the problem and will provide information that will let you to fix the problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.