你如何在php中引用html标签?

时间:2013-08-28 17:19:20

标签: php html conditional-statements

我想在下面的代码中放入一个条件语句,以防止在没有选择“branches”单选按钮的情况下运行PHP Post。

我找不到正确执行此操作的语法。

我不确定如何在条件语句中引用HTML标记。

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("Data has been submitted!");
}
</script>
</head>
<body>

<h1>Reference Stats Input</h1>
<form  method="post">
<h2>Select Branch</h2>
<label><input type="radio" name="branches" value="AR">AR</label><br>
<label><input type="radio" name="branches" value="BK">BK</label><br>
<label><input type="radio" name="branches" value="BR">BR</label><br>
<label><input type="radio" name="branches" value="EM">EM</label><br>
<label><input type="radio" name="branches" value="MD">MD</label><br>
<label><input type="radio" name="branches" value="PT">PT</label><br>
<label><input type="radio" name="branches" value="UR">UR</label><br>
<label><input type="radio" name="branches" value="WA">WA</label><br>
<br>
<br>
<br>

Type of Reference question:<select name="refquestion" <br><br>
<option value="ADULT">ADULT</option>
<option value="CHILD">CHILD</option>
<option value="JUVENILE">JUVENILE</option>
</select><br><br>

<input name="Submit" type="submit" onclick="myFunction()" value="INPUT">

<?php
if(!empty("branches"){
$con = mysql_connect("localhost","root","REDACTED");

if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("refstats", $con);
$sql="INSERT INTO reftable (branch, statcat)
VALUES
('$_POST[branches]','$_POST[refquestion]')";

if (!mysql_query($sql,$con))

  {

  die('Error: ' . mysql_error());

  }

mysql_close($con)
}
?>

</form>
</body>
</html>

2 个答案:

答案 0 :(得分:3)

你无法用php执行此操作,php是服务器端,只有在发布后才知道选择。

你必须在javascript中使用eventhandler执行此操作。我将给你一个jQuery示例来说明它,我会看看我是否可以将它恢复到本机JS:

// jQuery style (and therefor requires jQuery to work)
$('form').on('submit', function(e){
    if( $('[name="branches"]:selected').length === 0){
        e.preventDefault();
        alert('please select a branch');
    }
});

// Or native Javascript (this isn't tested 100%, but something like this):
document.getElementById("form").onsubmit=function(){
    // get all options
    var options = document.getElementsByName("branches");
    var itemChecked = false; // start with false, se to true if there is a selected option
    for (var i = 0; i < options.length; i++) {
        if (options[i].checked) { // if one option is found
            itemChecked  = true; // set to true
            break; // no need to continue the loop
        }
    }
    return itemChecked
};

您可以随时选择默认选项:) 重要:永远不要相信javascript !!始终双重检查客户端信息服务器端。客户信息应该总是被认为是邪恶的,你应该确保它不是。

答案 1 :(得分:0)

您可以采取以下措施:

if(!isset($_POST['branches']) { 
// do something
}

elseif(isset($_POST['branches']) { 
$con = mysql_connect("localhost","root","REDACTED");
// continue with rest of code