Skip to content

Instantly share code, notes, and snippets.

@frigginglorious
Created September 13, 2017 02:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frigginglorious/71560b82256e8981dd2b6341284e4c90 to your computer and use it in GitHub Desktop.
Save frigginglorious/71560b82256e8981dd2b6341284e4c90 to your computer and use it in GitHub Desktop.
Single page table insert / display in PHP with PDO connection to MySQL
<?php
$host = // BRADS INFO AS A STRING IN QUOTES PROBABLY "localhost"
$db = // BRADS INFO AS A STRING IN QUOTES
$user = // BRADS INFO AS A STRING IN QUOTES
$pass = // BRADS INFO AS A STRING IN QUOTES
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
// THIS IF STATEMENT IS CHECKING THESE REQUIRED FIELDS ARE FILLED IN
if(isset($_POST["title"]) && isset($_POST["description"]) && isset($_POST["type"])){
$title = $_POST["title"];
$description = $_POST["description"];
$type = $_POST["content"];
$color = (isset($_POST["color"]) ? 1 : 0);
$date = date('Y-m-d H:i:s'); //function that gets current date in that format
$sql = "INSERT INTO brads_table(title, description, type, color, date) VALUES (?, ?, ?, ?,?)";
$stmt = $pdo->prepare($sql);
if ($stmt->execute([$cat,$title,$content,$featured,$postID])) {
echo "Insert Success";
echo "Title: " . $title . "<br>";
echo "Description: " . $description . "<br>";
echo "Featured: " . $featured . "<br>";
echo "Content: " . $content . "<br>";
}else {
echo "Update Error";
}
}
?>
<form name="lister" method="post" action="" >
<input name="title"><br>
<input name="description"><br>
<select name="color">
<option value="red">red</option>
<option value="blue">blue</option>
<option value="black">black</option>
<option value="yelow">yellow</option>
</select>
<input type="radio" name="type" value="house">house<br>
<input type="radio" name="type" value="condo">condo<br>
</form>
<table>
<thead>
<td>
<tr>Title</tr><tr>Description></tr><tr>Color</tr><tr>Type</tr>
</td>
<tbody>
<?php
$sql = "SELECT * from brads_table ORDER BY date DESC"; //orders by most recent
$stmt = $pdo->prepare($sql);
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row)
{
echo "<td style='color:" . $row["color"] . "'><tr>" . $row["title"] . "</tr><tr>" . $row["description"] . "</tr></td>";
}
?>
</tbody>
</table>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment