Last active
April 16, 2019 15:03
-
-
Save blwsh/bf6b0bec1af0a3628f0e2f9c5b07e1ed to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function renderRow($row) { | |
echo "<tr>"; | |
array_walk($row, function($column) { echo "<td>$column</td>"; }); | |
echo "</tr>"; | |
} | |
// Variables. | |
$table = 'test'; | |
// Create PDO connection. | |
try { | |
/** @var PDO $db */ | |
($db = new PDO('mysql:dbname=magento;host=db', 'root', 'root', [])) | |
->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
} catch (PDOException $e) { | |
echo 'Failed to connect'; | |
} | |
// Execute statement that create's table called table. | |
// You shouldn't create a table via php. Don't include this section in your code. | |
try { | |
$db->exec("CREATE table $table(ID INT(11) AUTO_INCREMENT PRIMARY KEY, Prename VARCHAR(50) NOT NULL, Name VARCHAR(250) NOT NULL, StreetA VARCHAR(150) NOT NULL, StreetB VARCHAR(150) NOT NULL, StreetC VARCHAR(150) NOT NULL, County VARCHAR(100) NOT NULL, Postcode VARCHAR(50) NOT NULL, Country VARCHAR(50) NOT NULL);"); | |
echo("Created $table"); | |
} catch (PDOException $e) { | |
echo "Table already exists."; | |
} | |
// Insert some data. | |
$db->exec("INSERT INTO `magento`.`test` (`Prename`, `Name`, `StreetA`, `StreetB`, `StreetC`, `County`, `Postcode`, `Country`) VALUES ('Mr', 'Ben Watson', 'University of Huddersfield', 'Huddersfield', 'Huddersfield', 'Yorkshire', 'HD11DH', 'United Kingdom')"); | |
$db->exec("INSERT INTO `magento`.`test` (`Prename`, `Name`, `StreetA`, `StreetB`, `StreetC`, `County`, `Postcode`, `Country`) VALUES ('Mr', 'Louis Jones', 'University of Huddersfield', 'Huddersfield', 'Huddersfield', 'Yorkshire', 'HD11DH', 'United Kingdom')"); | |
$db->exec("INSERT INTO `magento`.`test` (`Prename`, `Name`, `StreetA`, `StreetB`, `StreetC`, `County`, `Postcode`, `Country`) VALUES ('Mr', 'Corrie ', 'University of Huddersfield', 'Huddersfield', 'Huddersfield', 'Yorkshire', 'HD11DH', 'United Kingdom')"); | |
// Get data from database. | |
$query = $db->query("SELECT * FROM magento.test"); | |
$query->setFetchMode(PDO::FETCH_ASSOC); | |
// Print the results. | |
$rowCount = 0; | |
echo "<table>"; | |
while ($row = $query->fetch()) { | |
if ($rowCount === 0) { | |
renderRow(array_keys($row)); | |
} | |
renderRow($row); | |
$rowCount++; | |
} | |
echo "</table>"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment