gpt4 book ai didi

php - SQLITE:检查列是否存在而不触发php中的错误

转载 作者:行者123 更新时间:2023-12-03 18:26:08 24 4
gpt4 key购买 nike

我的情况是这样的:


我有一个包含表的列名称的数组
我必须通过循环遍历数组,并检查表中是否存在该字段(此列名称)
如果存在,我什么也不做,否则我必须添加

$array_column = ["column1 NOT NULL","column2 NOT NULL","column3 NOT NULL","column4 NOT NULL"];

for($j = 0 ; $j < count($array_column) ; $j++){

$query = "SELECT ".$array_column[$j]." FROM my_table";
$result = $db->query($query);

$check = false;
//try{
foreach ($result as $row) { //error here
$check = true;
}
//}catch (Exception $e) {
//echo "here";
//$check = false;
//}

if(!$check){
echo "column [".$array_column[$j]."] to add <br>";
}

}



但是当我发现表中不存在的列时,php给了我错误

Warning: Invalid argument supplied for foreach ()


我也尝试了TryCatch,但是同样的错误。
我希望php在找不到列时不返回该错误

更新1:

我尝试这样做,它可以工作,但是不幸的是,当表中没有记录时,它就无法工作

$select = $db->query('SELECT * FROM mytable');

$total_column = $select->columnCount();
var_dump($total_column);

for ($counter = 0; $counter <= $total_column; $counter ++) {
$meta = $select->getColumnMeta($counter);
$column[] = $meta['name'];
}
print_r($column);


更新2:即使表中没有记录,此解决方案也能很好地工作!

$result = $db->query("PRAGMA table_info(test2)");
$result->setFetchMode(PDO::FETCH_ASSOC);
$meta = array();
foreach ($result as $row) {
array_push($meta, $row['name']);
}

最佳答案

PRAGMA table_info('table_name')将返回行列表(表中的每一列一个)
不幸的是,您不能在选择查询中使用它,但可以对其进行解析并尝试在查询表之前查找列名。
希望有帮助

关于php - SQLITE:检查列是否存在而不触发php中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24511669/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com