技术开发 频道

PHP 开发经典教程(Part 8): 数据库操作

如何操作数据插入 

    因此,现在你已经知道如何执行一条SELECT查询语句来从数据库中获得结果集。然而,你也可以使用PHP的MySQL API执行哪些不返回结果集的查询语句(例如,一条INSERT或者UPDATE查询)。考虑下面的例子,该例子通过要求用户通过表单输入数据然后将数据插入到数据库中演示了上述所讲的用法。

<html> <head> <basefont face="Arial"> </head> <body> <?php if (!isset($_POST['submit'])) { // form not submitted ?> <form action="<?=$_SERVER['PHP_SELF']?>" method="post"> Country: <input type="text" name="country"> National animal: <input type="text" name="animal"> <input type="submit" name="submit"> </form> <?php } else { // form submitted // set server access variables $host = "localhost"; $user = "test"; $pass = "test"; $db = "testdb"; // get form input // check to make sure it's all there // escape input values for greater safety $country = empty($_POST['country']) ? die ("ERROR: Enter a country") : mysql_escape_string($_POST['country']); $animal = empty($_POST['animal']) ? die ("ERROR: Enter an animal") : mysql_escape_string($_POST['animal']); // open connection $connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!"); // select database mysql_select_db($db) or die ("Unable to select database!"); // create query $query = "INSERT INTO symbols (country, animal) VALUES ('$country', '$animal')"; // execute query $result = mysql_query($query) or die ("Error in query: $query. ".mysql_error()); // print message with ID of inserted record echo "New record inserted with ID ".mysql_insert_id(); // close connection mysql_close($connection); } ?> </body> </html>

 

    这里,用户首先被呈现了一个要求输入国家名称和本国动物的表单。

    一旦这个表单被提交后,表单输入在内部被用于创建INSERT查询,该查询通过使用mysql_query()方法被发送到数据库。因为mysql_query()函数返回一个指示查询是否成功的布尔值,所以检查INSERT语句是否发生以及返回一条适当的消息是可能的。

    在上述例子中有两个新函数。mysql_escape_string()函数对用户输入的特殊字符(比如引号)进行转义以使得它能够安全的输入到数据库中;而mysql_insert_id()返回上一条INSERT查询所产生的ID号(只有INSERT语句插入的表格包含一个AUTO_INCREMENT字段时才有用)。这两个函数也用于ext/mysqli中。

0
相关文章