Marc Kupietz | ab11a14 | 2023-03-09 08:15:35 +0100 | [diff] [blame^] | 1 | <?php |
| 2 | |
| 3 | include_once "User.php"; |
| 4 | include_once "config.php"; |
| 5 | |
| 6 | use \User as User; |
| 7 | |
| 8 | function open_db() { |
| 9 | global $DB, $DB_USER, $DB_PASS; |
| 10 | try { |
| 11 | # MS SQL Server and Sybase with PDO_DBLIB |
| 12 | $DBH = new PDO($DB, $DB_USER, $DB_PASS); |
| 13 | } |
| 14 | catch(PDOException $e) { |
| 15 | echo $e->getMessage(); |
| 16 | } |
| 17 | return $DBH; |
| 18 | } |
| 19 | |
| 20 | function db_add_user(User $user) |
| 21 | { |
| 22 | $DBH = open_db(); |
| 23 | $columns = getColumnNames($DBH, "person"); |
| 24 | foreach ((array) $user as $key => $value) { |
| 25 | if (array_key_exists($key, (array) $columns)) { |
| 26 | $a[$key] = $value; |
| 27 | } |
| 28 | } |
| 29 | $keys = array_keys($a); |
| 30 | $sql = "INSERT INTO person (".implode(", ",$keys).") \n"; |
| 31 | $sql .= "VALUES ( :".implode(", :",$keys).")"; |
| 32 | $q = $DBH->prepare($sql); |
| 33 | $i=1; |
| 34 | foreach($a as $value) |
| 35 | $q->bindParam($i++, $value); |
| 36 | print $sql. "\n"; |
| 37 | return $q->execute($a); |
| 38 | } |
| 39 | |
| 40 | function getColumnNames($dbh, $table) |
| 41 | { |
| 42 | $sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = :table"; |
| 43 | try { |
| 44 | $stmt = $dbh->prepare($sql); |
| 45 | $stmt->bindValue(':table', $table, PDO::PARAM_STR); |
| 46 | $stmt->execute(); |
| 47 | $output = array(); |
| 48 | while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { |
| 49 | $output[$row['COLUMN_NAME']] = $row['COLUMN_NAME']; |
| 50 | } |
| 51 | return $output; |
| 52 | } catch (PDOException $pe) { |
| 53 | trigger_error('Could not connect to MySQL database. ' . $pe->getMessage(), E_USER_ERROR); |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | try { |
| 58 | # MS SQL Server and Sybase with PDO_DBLIB |
| 59 | $DBH = new PDO($DB, $DB_USER, $DB_PASS); |
| 60 | $table = "person"; |
| 61 | $sql = "SHOW COLUMNS FROM " . $table; |
| 62 | $stmt = $DBH->prepare($sql); |
| 63 | # $stmt->bindValue(':table', $table, PDO::PARAM_STR); |
| 64 | $stmt->execute(); |
| 65 | $output = array(); |
| 66 | while($row = $stmt->fetch(PDO::FETCH_NUM)){ |
| 67 | $output[] = $row[0]; |
| 68 | print $row[0] . "\n"; |
| 69 | } |
| 70 | } |
| 71 | catch(PDOException $e) { |
| 72 | echo $e->getMessage(); |
| 73 | } |
| 74 | |
| 75 | $user=new User(); |
| 76 | $user->username="test"; |
| 77 | print $user->to_string(); |
| 78 | db_add_user($user); |