我正在制作一个包含城市、电子邮件和提交按钮的表格,我需要帮助如何将其连接到数据库


I am making a form that includes city and email and a submit button and I need help on how I connect this to a database

我很难找到一个简单易懂的答案。。。我制作了一个网站(在dreamweaver cs5上),网站的首页有一个选择城市、所有主要城市的下拉列表和一个电子邮件文本框。我有几个问题,如下所示:

我的下一步是什么,现在我已经完成了html。。。我要把它连接到数据库吗?

我需要什么php脚本来填充两个字段(城市和电子邮件)?我在哪里输入这个php脚本?

以下是我的一些代码,以防您想知道:http://answers.yahoo.com/question/index?qid=20110611111223AAeAnrT(必须把它放在这里,因为溢出不允许我输入代码。)

这只是一个快速入门,可以让你的表单建立起来。

关于创建PHP脚本,我对Dreamweaver了解不多,但如果你的服务器上安装了PHP,你应该能够在与HTML相同的目录中创建它。所有表单元素都应该在表单标记中,并且应该指向PHP,例如前面的<form method="POST" action="dosomething.php">和后面的</form>

此外,"Please select your city..."在表单上可能很好,比如<option value="unset">Please select your city...</option>。(此外,示例中的所有选项都应具有value属性)。

我不知道你对PHP了解了多少,所以我将尝试从基础知识开始。PHP脚本将是一个扩展名为.php的纯文本文件,例如dosomething.php。在脚本内部,PHP代码需要被PHP开始和结束标记<?php?>包围。

输入到表单中的值应该可以通过PHP中的$_POST变量访问,因此在脚本中$_POST['select']将被设置为当前值。我建议将名称设置为您能记住的名称,例如selectedCityemailAddress

在我们的PHP脚本中,我们希望从表单中获取变量,并检查它们是否都已填充。然后数据将被写入数据库。我在下面创建了一个示例代码段,并对其进行了注释,但应该添加额外的安全性,并且不应该按原样使用此代码。

<?php
$city = $_POST['selectedCity'];  // Get the city the user selected from the form
$addr = $_POST['emailAddress'];  // Save the email address the user entered
if($city == "unset")
{
    // Stops user if a city hasn't been selected
    die("Please select a city.");  // Stop executing code, and tell user to go back and select a city
}
if($addr == "")
{
    // Stops user if the email address is blank (also would be good to make sure email address is correct, like user@domain.com)
    die("Please enter a valid email address");
}
if(!file_exists("../mailinglist.sqlite"))
{
    // Creates the database if it doesn't exist
    // The database should be outside the document root (meaning you can't access it through the web)
    $db = sqlite_open("../mailinglist.sqlite"); // Opens the database, creates it if non-existent (it is)
    sqlite_query("CREATE TABLE users (city, email)");  // Creates a table for users
}
else
{
    $db = sqlite_open("../mailinglist.sqlite"); // Opens the database if it exists
}
sqlite_query("INSERT INTO users (city, email) VALUES ('".sqlite_escape_string($city)."','".sqlite_escape_string($city)."')");  // Add the new user to the database
?>

(任何需要帮助的蓝色内容都可以在PHP文档中搜索)

上面的代码将从HTML表单中获取输出,检查以确保它不是空的,并将其输入到数据库中,如果它不存在,则创建一个新的数据库。同样,这只是一个开始,代码需要在上线之前进行改进。

希望这能有所帮助!