PHP客户的MySQL出席名单

时间:2012-10-16 19:31:43

标签: php mysql post checkbox

我正在撰写一份出席名单,我希望将其用于即将举行的活动。

当某人登录网站时,可以选择他/她和其他人是否出席活动。

if ($res && mysql_num_rows($res) >= 1)
{
     echo '<form method="post" action="guest.php">';
     echo '<table border="10">
        <tr>
            <td>Name</td>
            <td>Present</td>
        </tr>';

    while ($row = mysql_fetch_array($res))
    {
        echo '<tr>
            <td>'.$row['guestId']." ".$row['firstName'].'</td>
            <td><input type=\'checkbox\' name=\'present[]\' value='.$row['guestId'].'></td>
        </tr>';
    }

    echo '</table>';
    echo '<input type="submit" name="submit" value="submit">';

} else {
    echo 'No data found!';
}

这里我将guestId写入我用于将其写入数据库的值中:

    if( isset($_POST['present']) ) {
        foreach($_POST['present'] as $value){
            $query=mysql_query("INSERT INTO present (gastId, present) VALUES (".$value.", 1)");
            $resultadd=mysql_query($query) or die("Errore insert G: ".mysql_error());
        }
    }

有更好的方法吗?因为我无法想象这是正确的方法。

2 个答案:

答案 0 :(得分:1)

您的代码不错,有很多不同的方法可以做到这一点。

如果您要创建项目,我建议您查看MVC(模型 - 视图 - 控制器),这里有一个教程:http://www.nathandavison.com/posts/view/11/custom-php-mvc-tutorial-part-1-introduction

还有一些像codeigniter,cakePHP,YII(http://www.phpframeworks.com/top-10-php-frameworks/)这样的框架可以让你制作一个MVC应用程序,它也更有条理,更安全。

编辑:作为@MadaraUchiha推荐,这里是使用PDO的链接,它们是安全套:http://php.net/manual/en/pdo.prepared-statements.php

答案 1 :(得分:1)

您可以使用一个查询插入多行:

INSERT INTO present 
(gastId, present)
VALUES
( 1, 1 ),
( 2, 0 ),
( 3, 1 )

或者你可以使用mysqli和预备语句:

$mysqli = new mysqli(/* Connection information here */);
$stmt = $mysqli->prepare("INSERT INTO present (gastId, present) VALUES ( ?, 1 )");
$stmt->bind_param("i", $value);
foreach($_POST['present'] as $value) {
   $stmt->execute();
}
$stmt->close();
$mysqli->close();