简体   繁体   中英

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. 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.

The UPPER function will convert the value stored to uppercase, but that doesn't really affect the comparison if the collation is case insensitive.

You may want to consider using the BINARY operator.

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

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

One quick way to check the collation in MySQL is:

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.

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

NOTE: With php 5 and mysqli, do not use a SET names query, rather use the mysqli_set_charset .

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

You can also do it using like

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

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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