In this example, we will take the inputs from the user and temporarily store them in variables and then finally stores them permanently in the database.
Database Code:
1 2 3 4 5 6 7 | CREATE TABLE `table1` ( `id` int(11) NOT NULL, `number1` int(11) NOT NULL, `number2` int(11) NOT NULL ); |
PHP Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | <?php //database configure $dsn = 'mysql:dbname=sample;host=127.0.0.1'; $user = 'root'; $password = ''; try { $dbh = new PDO($dsn, $user, $password); } catch (PDOException $e) { echo 'Con Err: ' . $e->getMessage(); } if(!empty($_POST)) { //get data from inputs $number1=$_POST["number1"]; $number2=$_POST["number2"]; /* Store data to database */ $sql = 'insert into table1 values(NULL,?,?)'; $sth = $dbh->prepare($sql); $sth->execute(array($number1,$number2)); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Code4Example</title> <style> label{ display:block; } </style> </head> <body> <form action="" method="post"> <label for=""> Number 1: <input type="text" name="number1"> </label> <label for=""> Number 2: <input type="text" name="number2"> </label> <button type="submit">Store in Database</button> </form> <!-- GET DATAS FROM DATABASE --> <?php $sth = $dbh->prepare('SELECT number1, number2 FROM table1'); $sth->execute(); while($result = $sth->fetch(PDO::FETCH_ASSOC)){ echo $result['number1']."+".$result['number2']. "=".($result['number1']+$result['number2']). "<br>"; } ?> </body> </html> |
Output: