使用PREG_MATCH在PHP中进行表单验证

时间:2015-08-04 23:45:51

标签: php

我确定我只是在做一些愚蠢的事情,但我想我已经接近了。我试图做的是为我的提交添加验证。使用我当前的代码,无论我在串行字段中输入什么数据,它总是会出现无效序列。有什么建议吗?

<?php

$serial=$_POST['serial'];
$model=$_POST['model'];
$deviceCondition=$_POST['deviceCondition'];
$sealCondition=$_POST['sealCondition'];
$location=$_POST['location'];
$deployDate=$_POST['deployDate'];
$weight=$_POST['weight'];
$connectedTerminal=$_POST['connectedTerminal'];
$notes=$_POST['notes'];

//NEW PDO connection

$serialVal = "[a-zA-Z0-9-]+"; 
if ( preg_match( $serialVal, $serial ) ) {

try{   


$conn = new PDO("mysql:host=$sql_server;dbname=$sql_db", $sql_user, $sql_pass);

$sql = "INSERT INTO web01dev4s2.ingenicoInfo (serial, model, deviceCondition, sealCondition, location, deployDate, weight, connectedTerminal, notes) VALUES ('".$serial."', '".$model."', '".$deviceCondition."', '".$sealCondition."', '".$location."', '".$deployDate."', '".$weight."', '".$connectedTerminal."', '".$notes."')";


$q = $conn->prepare($sql);
$result_1=($sql); 

$q->execute(); 
}
catch (PDOException $pe) {
    die("Could not connect to the database" . $pe->getMessage());
}


$count = $q->rowCount();
print("Saved $count record(s).\n");
header( "refresh:2;url=devicelist.php" );

}

else { 
 echo $serial . "Invalid serial number.";
} 

?>

1 个答案:

答案 0 :(得分:0)

你忘记了分隔符“/”

if(preg_match("/[a-zA-Z0-9-]+/", $serial))
        echo 'oui';
    else
        echo 'no';