PHP on the commandline
Posted 8 years ago
- updated 8 years ago
php
commandline
<?php
line('red',"Red Text");
line('green',"Green Text");
line('white',"White Text");
$answer = question("Log");
line('white',"The answer is $answer");
clear();
try {
$db = new PDO('sqlite:dogsDb_PDO.sqlite');
view($db);
}
catch(PDOException $e)
{
print 'Exception : '.$e->getMessage();
}
/** Functions **/
function create($db)
{
//create the database
$db->exec("CREATE TABLE Dogs (Id INTEGER PRIMARY KEY, Breed TEXT, Name TEXT, Age INTEGER)");
//insert some data...
$db->exec("INSERT INTO Dogs (Breed, Name, Age) VALUES ('Labrador', 'Tank', 2);".
"INSERT INTO Dogs (Breed, Name, Age) VALUES ('Husky', 'Glacier', 7); " .
"INSERT INTO Dogs (Breed, Name, Age) VALUES ('Golden-Doodle', 'Ellie', 4);");
}
function view($db)
{
//now output the data to a simple html table...
print "<table border=1>";
print "<tr><td>Id</td><td>Breed</td><td>Name</td><td>Age</td></tr>";
$result = $db->query('SELECT * FROM Dogs');
foreach($result as $row)
{
print "<tr><td>".$row['Id']."</td>";
print "<td>".$row['Breed']."</td>";
print "<td>".$row['Name']."</td>";
print "<td>".$row['Age']."</td></tr>";
}
print "</table>";
// close the database connection
$db = NULL;
}
function line($color,$string) {
$black = "\033[30m";
$red = "\033[31m";
$green = "\033[32m";
$brown = "\033[33m";
$white = "\033[0m";
$color = $$color;
echo $color . " " . $string . "\n";
}
function question($text) {
echo $text . ": ";
$handle = fopen ("php://stdin","r");
$line = fgets($handle);
fclose($handle);
return $line;
}
function clear() {
`clear`;
}