首頁 >後端開發 >php教程 >printf和sprintf的應用

printf和sprintf的應用

WBOY
WBOY原創
2016-08-08 09:20:44955瀏覽

<?php
printf('b: %b <br>c: %c <br>d: %d <bf>f: %f', 80,80, 80, 80);
echo '<br />';
printf('%0.2f <br>%+d <br>%0.2f <br>', 8, 8, 1235.456);

printf('the cost of %d %s at $%0.2f each is $%0.2f.', 4, 'brooms', 8.50, (4*8.50));

echo '<br>';
$tax = 30;
printf('The tax rate is %0.2f%%', $tax);
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Sorting Multidimensional Arrays</title>
</head>
<body>
<?php
$db = mysqli_connect('192.168.31.172', 'root', 'root', 'phpadvanced');
mysqli_query($db, "set names utf8");

if(!empty($_POST['task'])) {
    $parent_id = 0;
    if(isset($_POST['parent_id']) && filter_var($_POST['parent_id'], FILTER_VALIDATE_INT, ['min_range' => 1])) {
        $parent_id = $_POST['parent_id'];
    }

    $q = sprintf("INSERT INTO tasks (parent_id, task) VALUES (%d, '%s')", $parent_id, mysqli_real_escape_string($db, strip_tags($_POST['task'])));
    $r = mysqli_query($db, $q);

    if(mysqli_affected_rows($db) == 1) {
        echo '<p>任务添加成功</p>';
    } else {
        echo '<p>任务添加失败</p>';
    }
}
?>
    <form action="add_task.php" method="post">
        <fieldset>
            <legend>添加一个任务</legend>
            <p>任务: <input name="task" type="text" size="60" maxlength="100" required> </p>
            <p>上级任务: <select name="parent_id">
                    <option value="0">无上级</option>

                    <?php
                    $q = 'SELECT task_id, parent_id, task FROM tasks WHERE date_completed="0000-00-00 00:00:00" ORDER BY date_added ASC';
                    $r = mysqli_query($db, $q);
                    $tasks = [];
                    while(list($task_id, $parent_id, $task) = mysqli_fetch_array($r, MYSQLI_NUM)) {
                        echo "<option value=\"$task_id\">$task</option>";
                        $tasks[] = ['task_id' => $task_id, 'parent_id' => $parent_id, 'task' => $task];
                    }
                    ?>
                </select></p>
            <input name="submit" type="submit" value="添加这个任务" />
        </fieldset>
    </form>

<?php
    // 对任务的父id进行排序
    function parent_sort($x, $y) {
        return ($x['parent_id'] > $y['parent_id']);
    }
    usort($tasks, 'parent_sort');
    echo '<h2>当前的任务列表</h2><ul>';
    foreach ($tasks as $task) {
        echo "<li>{$task['task']}</li>\n";
    }
echo '</ul>';
?>
</body>
</html>

以上就介紹了printf和sprintf的應用,包括了方面的內容,希望對PHP教程有興趣的朋友有幫助。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn