· 7 years ago · Dec 16, 2018, 11:08 AM
1$con = connect(DNS,USERNAME,PASSWORD);
2//columns as arrays that i need to create if it doesn't exist
3$columnname = array("urine_re","lab_investigation","a_records","crazy_gus");
4$table='anc_hsd';
5
6//function to check if column name exist if not create it
7function columnExist($item,$table,$column){
8
9 $exists = false;
10 $sql = "SHOW COLUMNS FROM $table";
11 $result = $item->query($sql);
12 $results=$result->fetchAll(PDO::FETCH_COLUMN);
13
14
15 if(in_array($column,$results)){
16 $exists=true ;
17 }
18
19 if(!$exists){
20 $sql="ALTER TABLE $table ADD $column INT(30) NULL";
21 $item->exec($sql);
22 }
23}
24
25
26//this is where i use the function
27
28foreach($columnname as $key=>$value){
29 columnExist($con, $table, $value);
30}
31
32$sql = "SHOW COLUMNS FROM $table";
33$result = $item->query($sql);
34if ($result !== FALSE) {
35 $results=$result->fetchAll(PDO::FETCH_COLUMN);
36} else {
37 // Alternative code telling what to do when the query fails
38}
39
40$result = $item->query($sql);
41 if ($result) {
42 $results=$result->fetchAll(PDO::FETCH_COLUMN);
43 }
44 else {
45 // Handle errors
46 }