简体   繁体   English

PDO Postgres-检查列是否存在并根据关闭条件执行操作

[英]PDO Postgres - Check if Column Exist and do action based off condition

I'm trying to check to see if a column exists.. If it does, then I want to update the value, and if it doesn't, I want to alter the table and add the column with the a value. 我试图检查是否存在一列。如果存在,那么我想更新该值,如果不存在,我想更改表并为该列添加一个a值。 I'm pretty new to PDO, but I'm pretty sure my query is fine, I just don't know how to handle the output from the execute() command I guess. 我对PDO还是很陌生,但是我可以确定我的查询很好,只是我不知道如何处理execute()命令的输出。 Thanks for the help in advance! 我在这里先向您的帮助表示感谢!

$sth = $pdo->prepare(' SELECT ? FROM `?` WHERE column_name=? ');
$sth->bindParam(1, $column, PDO::PARAM_STR);
$sth->bindParam(2, $livetable, PDO::PARAM_STR);
$sth->bindParam(3, $column, PDO::PARAM_STR);
$sth->execute();

if ($sth) {
    //Row Exist - Update Value
    echo 'Row Exist';
}else{
    //Row Doesn't Exist - Create column & update with value
    echo 'row does not';
}

You cannot pass a table name as a bind parameter like this, you would need to use dynamic SQL to achieve this. 您不能像这样将表名作为绑定参数传递,您将需要使用动态SQL来实现。 But if you just want to check if a column exist in a table, don't query the table directly (what if it contains millions of records ?) ; 但是,如果您只想检查表中是否存在一列,请不要直接查询该表(如果它包含数百万条记录呢?); instead, query Postgres information schema, as follows : 而是查询Postgres信息模式,如下所示:

SELECT column_name 
FROM information_schema.columns 
WHERE
    table_name = ?
    AND  column_name = ?;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM