PHP表单内部的PHP页面在表单完成之前执行PHP代码 [英] Php page with html form inside execute php code before form is completed

查看:112
本文介绍了PHP表单内部的PHP页面在表单完成之前执行PHP代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愚蠢的问题,但我是新来的(这是一项家庭作业^^),我找不到解决方案:)
i有一个带有html格式的.php文件加上一些PHP代码来执行一个查询并从我的数据库中插入表单中的值。它可以工作,但每次页面加载时,php代码都会被执行,并且在DB中插入一个空白行,因为显然表单尚未填充。这是代码

 < html> 
< head>
< meta charset =utf-8>
< meta name =generatorcontent =AlterVista - Editor HTML/>
< title>< / title>
< / head>
< body>

< form action =myPage.phpmethod =post>
ID:< input type =textname =id/> < br />

< input type =submitname =Submitvalue =Go/> < br />
< / form>

<?php
$ user =DB;
$ password =;
$ host =;
$ database =my_DB;
$ connessione = mysql_connect($ host,$ user,$ password);

@mysql_select_db($ database,$ connessione)或死(无法选择数据库);

$ id = $ _REQUEST ['id'];
$ query =INSERT INTO myTable(ID)VALUES('。$ id。');
mysql_close();
?>

< / body>
< / html>

只有当表单上的Go按钮被执行后,才有办法执行php代码

解决方案

试试:

c> if(isset($ _ POST ['Submit'])){
$ user =DB;
$ password =;
$ host =;
$ database =my_DB;
$ connessione = mysql_connect($ host,$ user,$ password);

@mysql_select_db($ database,$ connessione)或死(无法选择数据库);

$ id = $ _REQUEST ['id'];
$ query =INSERT INTO myTable(ID)VALUES('。$ id。');
mysql_query($ query,$ connessione);
mysql_close();
}


This might be a stupid problem but i'm new to this (this is a homework ^^) and i can't find a solution :) i have a .php file with an html form plus some php code to execute a query and insert the values from the form in my DB. And it works, but every time the page is loaded the php code is executed and this insert in the DB a "blank" line, because obviously the form was not filled yet. This is the code

<html>
<head>
  <meta charset="utf-8">
  <meta name="generator" content="AlterVista - Editor HTML"/>
  <title></title>
</head>
<body>

<form action="myPage.php" method="post"> 
ID: <input type="text" name="id" /> <br /> 

<input type="submit" name="Submit" value="Go" /> <br />
</form>

<?php
$user = "DB";
$password = "";
$host = "";
$database = "my_DB";
$connessione = mysql_connect($host, $user, $password);

@mysql_select_db($database, $connessione) or die( "Unable to select database");

$id = $_REQUEST['id'];
$query = "INSERT INTO myTable (ID) VALUES ('".$id."')";
mysql_close();
?>

</body>
</html>

Is there a way to execute the php code only once the "Go" button on the form is executed?

解决方案

Try:

if(isset($_POST['Submit']))  {
    $user = "DB";
    $password = "";
    $host = "";
    $database = "my_DB";
    $connessione = mysql_connect($host, $user, $password);

    @mysql_select_db($database, $connessione) or die( "Unable to select database");

    $id = $_REQUEST['id'];
    $query = "INSERT INTO myTable (ID) VALUES ('".$id."')";
    mysql_query($query, $connessione);
    mysql_close();
}

这篇关于PHP表单内部的PHP页面在表单完成之前执行PHP代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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