Last active
March 7, 2025 02:39
-
-
Save adrian-enspired/1ddd71511e01c1f609db to your computer and use it in GitHub Desktop.
how to make a simple prepared statement for MySQL with PDO
This file contains hidden or 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 | |
// let's make a query. | |
// only sql. NO DATA! put a named parameter where the data would normally go. | |
// parameters start with a ":", contain letters, numbers, and underscores only, and are not quoted. | |
const SQL_SELECT = 'SELECT foo, bar, baz FROM myTable WHERE quxx = :quxx'; | |
// that's the parameter marker ---^ | |
// prepare the statement. | |
$selectStmt = $pdo->prepare(SQL_SELECT); | |
// where did $pdo come from? look here: | |
// https://gist.github.com/adrian-enspired/385c6830ba2932bc36a2 | |
// now, MySQL _already has_ the query. let's send the data. | |
// assume the data we want is in a form submission, named 'quxx'. | |
// we use an array to map the input data to the appropriate parameter marker: | |
$input = ['quxx' => $_POST['quxx']]; | |
// ^-- param name ^-- input data | |
// execute the query with the input data. | |
$selectStmt->execute($input); | |
// note, no need to escape anything. | |
// this is because it is **separate** from the query, and so MySQL cannot possibly confuse the two. | |
// no more sql injection! | |
// now your $selectStmt holds results, and can be iterated over to fetch them. | |
// for example, maybe we want to format the results as a HTML <table> ? | |
?> | |
<table> | |
<caption>Results where quxx is "<?= htmlspecialchars($_POST['quxx']) ?>"</caption> | |
<thead> | |
<tr> | |
<th>foo</th> | |
<th>bar</th> | |
<th>baz</th> | |
</tr> | |
</thead> | |
<tbody> | |
<?php foreach ($selectStmt as $row) : ?> | |
<tr> | |
<td><?= htmlspecialchars($row['foo']) ?></td> | |
<td><?= htmlspecialchars($row['bar']) ?></td> | |
<td><?= htmlspecialchars($row['baz']) ?></td> | |
</tr> | |
<?php endforeach; ?> | |
</tbody> | |
</table> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment