PHP中header函数的使用 [英] Use of header function in PHP

查看:36
本文介绍了PHP中header函数的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 add.php 页面上的表单向我的数据库添加联系人,此表单的 INSERT 代码位于我们称为 php.php 页面的另一个页面上.在 php.php 中,我有一个标题函数,我希望将用户重定向到另一个页面 edit.php?ID=100,ID=100 是刚刚输入的联系人.我将如何执行此操作,是否需要在头函数和 INSERT 查询之前从数据库中获取数据?

I'm adding a contact to my database with a form on the page add.php, the INSERT code for this form is on another page we'll call php.php page. In php.php I have a header function which I would like to have redirect the user to another page edit.php?ID=100, ID=100 being the contact that was just entered. How would I do this, do I need to do a fetch from the db before the header function and INSERT query?

<?php

if (isset($_POST['$fname'])) {

  header("location: http://www.mydomain.com/contacts/edit/?ID=<? echo $row['ID]; ?>");

  $connect = mysql_connect (...)

  mysql_select_db ("mydb);

  $ID = $_POST['ID'];
  $fname = $_POST['fname'];
  $lname = $_POST['lname'];

  $sql = ("INSERT INTO contacts (fname, lname) VALUES ('$_POST[fname]', '$_POST[lname]')");

  mysql_query($sql,$con) or die ("Error: ".mysql_error());

  exit;
}

?>

推荐答案

我相信 mysql_insert_id 是您正在寻找的函数.它将返回刚刚插入的字段的 AUTO_INCREMENT ID.然后,您可以将其插入到您的标头重定向中.只需确保在插入联系人后进行标题重定向.它会工作得很好.

I believe mysql_insert_id is the function you're looking for. It'll return the AUTO_INCREMENT ID of the field that was just inserted. You can then plug that into your header redirect. Just make sure to do the header redirect AFTER you insert the contact. It'll work just fine.

应该可以工作的代码:

<?php

if (isset($_POST['$fname'])) {

$connect = mysql_connect (...)

mysql_select_db ("mydb");

$ID = $_POST['ID'];
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);

$sql = "INSERT INTO contacts (fname, lname) VALUES ('$fname', '$lname')";

mysql_query($sql,$connection) or die ("Error: ".mysql_error());

header("location: http://www.mydomain.com/contacts/edit/?ID=".mysql_insert_id($connection));

exit;
}

?>

你发布的代码也容易受到 MySQL 注入的影响,所以我 mysql_real_escape_string 'd 你的输入以防止这种情况发生.在将输入放入查询之前,请始终对其进行清理.我鼓励您查看 PHP 必须提供的 MySQLi 函数.

The code you posted was also susceptible to MySQL injections, so I mysql_real_escape_string'd your input to prevent that from happening. Always sanitize input before putting it into your query. I encourage you to look at the MySQLi functions that PHP has to offer.

这篇关于PHP中header函数的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆