我正在使用PhP渲染动态网页,该网页接收电子邮件地址并将其存储在数据库中。如果出现错误并重新加载页面,我会使用双美元符号来维护该值,但是当我运行代码时它表示它是一个未定义的变量。
以下是我的代码的相关小节:
<?php
$email = isset($_POST["email"]) ? $_POST[ "email" ] : "";
$iserror = false;
$formerror = false;
if ( isset( $_POST["submit"] ) )
{
if($email == ""){
$iserror = true;
$formerror = true;
}
if(!$iserror)
{
$query = "INSERT INTO email (Address) values ('$email')";
if ( !( $database = mysql_connect( "localhost",
"iw3htp", "password" ) ) )
die( "<p>Could not connect to database</p>" );
// open Mailer database
if ( !mysql_select_db( "Mailer", $database ) )
die( "<p>Could not open Mailer database</p>" );
// execute query in Mailer database
if ( !( $result = mysql_query( $query, $database ) ) )
{
print( "<p>Could not execute query!</p>" );
die( mysql_error() );
} // end if
mysql_close( $database );
print( "<p>Hi! Your e-mail $email has been added to our mailing list.</p>
</body></html>" );
die();
}
}
if ( $iserror )
{
print( "<p class = 'error'>Fields with * need to be filled
in properly.</p>" );
}
print("<form method='post' action='mail.php'><label>Join our mailing list</label> <br>");
print("<input type='text' name='$email' value='" . $$email ."'>");
if($formerror == true)
{
print( "<span class = 'error'>*</span>" );
}
print("<input type='submit' name='submit' value='Join list' /></form></body></html>");
?>
答案 0 :(得分:1)
您的错误是因为双美元符号...请参阅PHP manual以了解对变量变量的更多了解
<?php
$a = 'hello';
$$a = 'world';
echo "$a ${$a}"; // outputs hello world
echo "$a $hello"; // outputs hello world But see the (dynamic) variable variable $hello
?>
答案 1 :(得分:0)
试试这个
<?php
$email = isset($_POST["email"]) ? $_POST[ "email" ] : "";
$iserror = false;
$formerror = false;
if ( isset( $_POST["submit"] ) ) {
if($email == ""){
$iserror = true;
$formerror = true;
}
$connect = mysql_connect( "localhost","iw3htp", "password" );
mysql_select_db( "Mailer" );
if(!$iserror) {
$query = "INSERT INTO email(Address) values ('".$email."')";
$result = mysql_query( $query );
if($result != '') {
print( "<p>Hi! Your e-mail ".$email." has been added to our mailing list.</p></body></html>" );
}else{
print( "<p>Could not execute query!</p>" );
}
mysql_close( $conncet );
}
}
if ( $iserror ){
print( "<p class = 'error'>Fields with * need to be filled in properly.</p>" );
}
print("<form method='post' action='mail.php'><label>Join our mailing list</label> <br>");
print("<input type='text' name='email' value='" . $email ."'>");
if($formerror == true)
{
print( "<span class = 'error'>*</span>" );
}
print("<input type='submit' name='submit' value='Join list' /></form></body></html>");
?>