简体   繁体   English

使用php验证大写和小写形式的现有数据

[英]validation for existing data in both upper and lower case in using php

I am working on a form which has two fields. 我正在处理具有两个字段的表单。 One is code and the other is name. 一个是代码,另一个是名称。 I have a validation of checking the existing code in a database. 我有一个检查数据库中现有代码的验证。 The query for code seems to work fine but the same does not work for name, especially in lower case. 对代码的查询似乎工作正常,但对名称的查询却无效,尤其是在小写字母下。 Can anyone help me? 谁能帮我? Here is my code: 这是我的代码:

<?php
session_start();
if (!isset($_SESSION["username"])) {
    header("Location: unauthorize_access.php");
}

require("includes/dbconnect.php");

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

    $code   = $_POST["code"];
    $name   = $_POST["name"];


 {     
        mysql_query("INSERT INTO `country`(code, `name`)
            Values
                   ('$code', '$name')") or die(mysql_error());  

        print '<script type="text/javascript">';
        print 'alert("RECORDS ADDED SUCCESSFULLY")';
        header('refresh: 1; country.php');
        PRINT '</script>';
    }
}



?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Country</title>
<link rel="stylesheet" type="text/css" href="form2/view.css" media="all">
<script type="text/javascript" src="form2/view.js"></script>
<script type="text/javascript" src="form2/calendar.js"></script>
<script type="text/javascript">

  function checkForm()
  {
   if(country.code.value == "") {
      alert("Error: Code cannot be Empty!");
      country.code.focus();
      return false;
     }


   if(country.name.value == "") {
      alert("Error: Name cannot be Empty!");
      country.name.focus();
      return false;
     }


 }

</script>
<script type="text/javascript" src="chk/jquery-1.2.6.min.js"></script>

<SCRIPT type="text/javascript">
<!--


pic1 = new Image(16, 16); 
pic1.src = "loader.gif";

$(document).ready(function(){

$("#code").change(function() { 

var code = $("#code").val();

if(code.length >= 2)
{
$("#status").html('<img src="loader.gif" align="absmiddle">&nbsp;Checking availability...');

    $.ajax({  
    type: "POST",  
    url: "check_con.php",  
    data: "code="+ code,  
    success: function(msg){  

   $("#status").ajaxComplete(function(event, request, settings){ 

    if(msg == 'OK')
    { 
        $("#code").removeClass('object_error'); // if necessary
        $("#code").addClass("object_ok");
        $(this).html('&nbsp;<img src="tick.gif" align="absmiddle">');
    }  
    else  
    {  
        $("#code").removeClass('object_ok'); // if necessary
        $("#code").addClass("object_error");
        $(this).html(msg);
    }  

   });

 } 

  }); 

}
else
    {
    $("#status").html('<font color="red">The code should have at least <strong>2</strong> characters.</font>');
    $("#code").removeClass('object_ok'); // if necessary
    $("#code").addClass("object_error");
    }

});

});

//-->
</SCRIPT>
<SCRIPT type="text/javascript">
<!--


pic1 = new Image(16, 16); 
pic1.src = "loader.gif";

$(document).ready(function(){

$("#code").change(function() { 

var code = $("#code").val();

if(code.length >= 2)
{
$("#status").html('<img src="loader.gif" align="absmiddle">&nbsp;Checking availability...');

    $.ajax({  
    type: "POST",  
    url: "check_con.php",  
    data: "code="+ code,  
    success: function(msg){  

   $("#status").ajaxComplete(function(event, request, settings){ 

    if(msg == 'OK')
    { 
        $("#code").removeClass('object_error'); // if necessary
        $("#code").addClass("object_ok");
        $(this).html('&nbsp;<img src="tick.gif" align="absmiddle">');
    }  
    else  
    {  
        $("#code").removeClass('object_ok'); // if necessary
        $("#code").addClass("object_error");
        $(this).html(msg);
    }  

   });

 } 

  }); 

}
else
    {
    $("#status").html('<font color="red">The code should have at least <strong>2</strong> characters.</font>');
    $("#code").removeClass('object_ok'); // if necessary
    $("#code").addClass("object_error");
    }

});

});

//-->
</SCRIPT><SCRIPT type="text/javascript">
<!--


pic1 = new Image(16, 16); 
pic1.src = "loader.gif";

$(document).ready(function(){

$("#name").change(function() { 

var code = $("#name").val();

if(code.length >= 0)
{
$("#stat_2").html('<img src="loader.gif" align="absmiddle">&nbsp;Checking availability...');

    $.ajax({  
    type: "POST",  
    url: "check_con.php",  
    data: "name="+ name,  
    success: function(msg){  

   $("#stat_2").ajaxComplete(function(event, request, settings){ 

    if(msg == 'OK')
    { 
        $("#name").removeClass('object_error'); // if necessary
        $("#name").addClass("object_ok");
        $(this).html('&nbsp;<img src="tick.gif" align="absmiddle">');
    }  
    else  
    {  
        $("#name").removeClass('object_ok'); // if necessary
        $("#name").addClass("object_error");
        $(this).html(msg);
    }  

   });

 } 

  }); 

}
else
    {
    $("#stat_2").html('<font color="red"><strong>The name cannot be empty</strong></font>');
    $("#name").removeClass('object_ok'); // if necessary
    $("#name").addClass("object_error");
    }

});

});

//-->
</SCRIPT>
</head>
<body id="main_body" >

    <img id="top" src="form2/top.png" alt="">
    <div id="form_container">

        <h1><a>Country</a></h1>
        <form id="country" class="appnitro" enctype="multipart/form-data" method="post" onsubmit="return checkForm()">
                    <div class="form_description">
        <h2>Country</h2>

        </div>
                    <table border ="0px" width="100%">
                        <tr>
                            <td><label class="description" for="element_1">Code</label></td><td><input id="code" name="code"  type="text" maxlength="6"  Placeholder="Please enter a code" value=""/></td><td width="400" align="left"><div id="status"></div></td>
                        </tr>
                        <tr>
                            <td><label class="description" for="element_1">Name</label></td><td><input id="name" name="name" size="40" type="text" maxlength="40" Placeholder="Please enter a name" value=""/></td><td width="400" align="left"><div id="stat_2"></div></td>

                        </tr>
                        <tr>
                            <td></td><td ><input type="submit" name="save" value="Save"></td>
                        </tr>
                    </table>
                </form>

Here is my php code. 这是我的PHP代码。 It works fine for the code field but doesn't work for name. 它适用于代码字段,但不适用于名称。

<?php
$dbHost     = 'localhost'; // usually localhost
$dbUsername = 'root';
$dbPassword = '';
$dbDatabase = 'pts_root';

$db = mysql_connect($dbHost, $dbUsername, $dbPassword) or die ("Unable to connect to Database Server.");
mysql_select_db ($dbDatabase, $db) or die ("Could not select database.");
if(isSet($_POST['code']))
{
$code = $_POST['code'];

$sql_check = mysql_query("SELECT * FROM country WHERE code='".$code."'") or die(mysql_error());

if(mysql_num_rows($sql_check))
{
echo '<font color="red">The code <STRONG>'.$code.'</STRONG> is already exist.</font>';
}
else
{
echo 'OK';
}

}

?>
<?php
$dbHost     = 'localhost'; // usually localhost
$dbUsername = 'root';
$dbPassword = '';
$dbDatabase = 'pts_root';

$db = mysql_connect($dbHost, $dbUsername, $dbPassword) or die ("Unable to connect to Database Server.");
mysql_select_db ($dbDatabase, $db) or die ("Could not select database.");
if(isSet($_POST['name']))
{
$name = $_POST['name'];

$sql_check = mysql_query("SELECT * FROM country WHERE UPPER(`name`)='".$name."'") or die(mysql_error());
if(mysql_num_rows($sql_check))
{
echo '<font color="red">The name <STRONG>'.$name.'</STRONG> is already exist.</font>';
}
else
{
echo 'OK';
}

}

?>

Change 更改

$name = $_POST['name'];

to

$name = strtoupper($_POST['name']);

so you are comparing the capitalised input with the capitalised field. 因此,您正在将大写输入与大写字段进行比较。

I'm looking at this particular section: 我正在看这个特殊的部分:

$sql_check = mysql_query("SELECT * FROM country WHERE UPPER(`name`)='".$name."'") or die(mysql_error());
if(mysql_num_rows($sql_check))

Without reading through all of the rest of your code, and trying to figure out your test case, it might be helpful for you to know that MySQL can use a "case insensitive" collation. 在不阅读所有其余代码并试图弄清测试用例的情况下,了解MySQL可以使用“不区分大小写”的排序规则可能对您有所帮助。

The UPPER function will convert the value stored to uppercase, but that doesn't really affect the comparison if the collation is case insensitive. UPPER函数会将存储的值转换为大写形式,但是如果排序规则不区分大小写,那实际上并不会影响比较。

You may want to consider using the BINARY operator. 您可能要考虑使用BINARY运算符。

SELECT * FROM country WHERE BINARY UPPER(`name`)= 'FOO'

http://dev.mysql.com/doc/refman/5.5/en/charset-binary-op.html http://dev.mysql.com/doc/refman/5.5/en/charset-binary-op.html

One quick way to check the collation in MySQL is: 在MySQL中检查归类的一种快速方法是:

SHOW VARIABLES LIKE 'collation%'

You may see values like this: 您可能会看到类似以下的值:

utf8_general_ci
latin1_swedish_ci  

That _ci at the end of the collation name identify this as a "case insensitive" collation, which basically means 'ABC' = 'abc' evaluates as TRUE. 排序规则名称末尾的_ci将其标识为“不区分大小写”的排序规则,这基本上意味着'ABC'='abc'的计算结果为TRUE。

Collation can be specified at the individual table and column level as well. 排序规则也可以在单个表和列级别指定。

For more information, see the MySQL Reference http://dev.mysql.com/doc/refman/5.5/en/charset.html 有关更多信息,请参见MySQL参考http://dev.mysql.com/doc/refman/5.5/en/charset.html

NOTE: With php 5 and mysqli, do not use a SET names query, rather use the mysqli_set_charset . 注意:对于php 5和mysqli,不要使用SET names查询,而要使用mysqli_set_charset

http://php.net/manual/en/mysqli.set-charset.php http://php.net/manual/zh/mysqli.set-charset.php

You can also do it using like 您也可以使用它like

SELECT * FROM country WHERE `name` like '$name'

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM