Created
May 15, 2020 20:21
-
-
Save AndrewStanton94/ec46a8f2d225436e0a3844a79582aa95 to your computer and use it in GitHub Desktop.
A recap of PHP for database queries, based on: https://www.w3schools.com/php/php_mysql_select.asp
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 | |
$servername = "localhost"; | |
$username = ""; | |
$password = ""; | |
$dbname = ""; | |
function drawRow($row){ | |
?> | |
<article> | |
<h2><?php echo $row["id"]. " " . $row["name"]?></h2> | |
<p>Count <?php echo $row["count"] ?></p> | |
<input type="checkbox" <?php if($row["truthy"]) { echo "checked"; } ?> > | |
</article> | |
<?php | |
} | |
// Create connection | |
$conn = new mysqli($servername, $username, $password, $dbname); | |
// Check connection | |
if ($conn->connect_error) { | |
die("Connection failed: " . $conn->connect_error); | |
} | |
$sql = "SELECT id, name, count, truthy FROM testTable"; | |
$result = $conn->query($sql); | |
if ($result->num_rows > 0) { | |
// output data of each row | |
while($row = $result->fetch_assoc()) { | |
drawRow($row); | |
} | |
} else { | |
echo "0 results"; | |
} | |
$conn->close(); | |
?> |
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 | |
$servername = "localhost"; | |
$username = ""; | |
$password = ""; | |
$dbname = ""; | |
function drawRow($row){ | |
?> | |
<article> | |
<h2><?php echo $row["id"]. " " . $row["name"]?></h2> | |
<p>Count <?php echo $row["count"] ?></p> | |
<input type="checkbox" <?php if($row["truthy"]) { echo "checked"; } ?> > | |
</article> | |
<?php | |
} | |
try { | |
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); | |
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
$stmt = $conn->prepare("SELECT id, name, count, truthy FROM testTable"); | |
$stmt->execute(); | |
// set the resulting array to associative | |
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC); | |
$data = $stmt->fetchAll(); | |
foreach($data as $k=>$v) { | |
drawRow($v); | |
} | |
} catch(PDOException $e) { | |
echo "Error: " . $e->getMessage(); | |
} | |
$conn = null; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment