jeudi 5 février 2015

Insert user input into array then insert into sqlite database

Got an assignment due in three months, thought i'd make a start today learning and experimenting with PHP so forgive me if i'm sloppy. I am trying to create a simple form that takes user input and sends it to an sqlite database. i have got a version that creates and connects fine and inserts data with predefined data in my array. I'd like to remove that data and have three input fields in html named 'first name', 'last name' and 'age' that gets inputted into my array named $data which is then sent of to my sqlite database. Next i plan on adding my input fields but i am struggling to understand how they will work and how the data will be formatted in the array appropriately. Some suggestions of methods of doing this would be appreciated (ignore my second foreach loop, i just wanted to view my data onscreen). Here is my code so far:



<!DOCTYPE html>
<html>
<head>
<title>Data Input</title>
<link href="css/style.css" type="text/css" rel="stylesheet" />
</head>
<body>

<?php
try {
$dbh = new PDO('sqlite:mydb.sqlite3');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$dbh->exec("CREATE TABLE IF NOT EXISTS test (
firstName VARCHAR(30),
lastName VARCHAR(30),
age INTEGER)"
);

$data = array(
array('firstName' => 'Billy',
'lastName' => 'Bob',
'age' => '18'),
array('firstName' => 'Bill',
'lastName' => 'Bob',
'age' => '32')
);

$insert = "INSERT INTO test (firstName, lastName, age)
VALUES (:firstName, :lastName, :age)";
$stmt = $dbh->prepare($insert);

$stmt->bindParam('firstName', $firstName);
$stmt->bindParam('lastName', $lastName);
$stmt->bindParam('age', $age);

foreach ($data as $m) {
$firstName = $m['firstName'];
$lastName = $m['lastName'];
$age = $m['age'];

$stmt->execute();


}
$result = $dbh->query('SELECT * FROM test');
foreach ($result as $row) {
echo "First Name: " . $row['firstName'] . " ";
echo "Last Name: " . $row['lastName'] . " ";
echo "Age: " . $row['age'] . "<br>" . " ";
}

$dbh = null;

}
catch(PDOException $e) {
// Print PDOException message
echo $e->getMessage();
}
?>

</body>
</html>

Aucun commentaire:

Enregistrer un commentaire