PHP Knowledge Base
sprintf
Simple Examples
echo sprintf("<p>\$php__username = $php__username</p>");
$old = "index.html"; $new = "index.php"; echo sprintf('%s was renamed to %s',$old,$new);
$num = 5; $location = 'tree'; $format = 'There are %d monkeys in the %s'; echo sprintf($format, $num, $location);
Argument Swapping
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$mysql__dataset_name = $row['dataset_name'];
$i++;
$input_id = "radio".$i;
$html__input = '<input type="radio" id="%2$s" name="form__dataset" value="%1$s"><label for="%2$s">%1$s</label>'."\n";
echo sprintf($html__input, $mysql__dataset_name, $input_id);
PDO Select Query
Connection, Query, While Loop, and Table Header
$conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT title, year, genre, rt_score FROM $whichTable";
$stmt = $conn->query($sql);
echo "<table class=\"center\">\n<tr><th>Title</th><th>Year</th><th>Genre</th><th>RT</th></tr>\n";
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
Replace:
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>\n<td>" . $row['title'] . "</td>\n<td>" . $row['year'] . "</td>\n<td>" . $row['genre'] . "</td>\n<td>" . $row['rt_score'] . "</td>\n</tr>\n";
}
echo "</table>"
With:
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$title = $row['title'];
$year = $row['year'];
$genre = $row['genre'];
$rt_score = $row['rt_score'];
$html_row = "<tr>\n<td>%s</td>\n<td>%s</td>\n<td>%s</td>\n<td>%s</td>\n</tr>\n";
echo sprintf($html_row, $title, $year, $genre, $rt_score);
}
echo "</table>";
NULL