How to check if a column exists using PHP, PDO, MySQL?

In my application, I have a general query that applies to multiple users. There are cases where the table structure may vary between users. I have a query that I want to apply only to users where a column exists in its 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 get an error in the code request line:

Fatal error: thrown a 'PDOException' exception with the message 'SQLSTATE [42S22]: Column not found: 1054 Unknown column' item_type 'in the' list of fields' in / item _display.php: 5

Any ideas?

+3
4

, , :

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;
}

, .

+8

SHOW COLUMNS:

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

, .

+4

You can also allow PDOs to throw exceptions and catch them to analyze MySQL errors.

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

try
{
    $pdoStatement->execute();
}
catch( PDOException $e )
{
    switch( $e->errorInfo[1] )
    {
        case 1062:
            /* A PRIMARY or UNIQUE key is already assigned */
            return false;
        case 1054:
            /* Column not found */
            return false;
        default:
            /* some other PDO-error */
            log_error($e->getMessage(), 'mysql');
            return false;
    }
}
+2
source

hope this helps. Something you can do with PHP Mysql

<?php

$link = mysql_connect($server, $username,$password);

if(!link))  
{  
    exit('could not connect');  
}

if(!mysql_select_db($database))
{  
    exit('could not select the database');  
}
$sql="SELECT * FROM myrow WHERE mycolumn='".$columname."'";
$result=mysql_query($sql);
if(!$result){
if(mysql_errno($link)==1054){
            //column does not exist
    echo "<br />available";
    }
}
elseif($nr= mysql_num_rows($result)){
    if ($nr > 0){
                    //column exist
        die('<br />name exists');
    }
}
else
{
            //column does not exist
    echo "<br />available";
}
?>
0
source

All Articles