Maison php教程 php手册 php非空验证

php非空验证

Jun 06, 2016 pm 07:46 PM
php 方法 pratique Pas vide 验证

我想说这种方法是不是很常用的非空验证,现在的普遍使用的是javascript来验证非空,但是作为学习php的一些知识点,还是可以看看的。 先来看看commit.php中的方法 ? php $db = mysql_connect ('localhost','root','Ctrip07185419' ); mysql_select_db ('movie

  我想说这种方法是不是很常用的非空验证,现在的普遍使用的是javascript来验证非空,但是作为学习php的一些知识点,还是可以看看的。

先来看看commit.php中的方法

<span>php 
</span><span>$db</span> = <span>mysql_connect</span>('localhost','root','Ctrip07185419'<span>);
</span><span>mysql_select_db</span>('moviesite',<span>$db</span>) or <span>die</span>(<span>mysql_error</span>(<span>$db</span><span>));
</span><span>mysql_query</span>('set names "gb2312"',<span>$db</span><span>);
</span>?>
<!--
<html>
    <head></head>
    <title>Commit</title>
    <body>
-->
<span>php
</span><span>switch</span>(<span>$_GET</span>['action'<span>])
{
    </span><span>case</span> "add":<span>
    {
        </span><span>switch</span>(<span>$_GET</span>['type'<span>])
        {
            </span><span>case</span> 'movie':
                <span>$error</span> = <span>array</span><span>();
                </span><span>$movie_name</span> = <span>isset</span>(<span>$_POST</span>['movie_name']) ? <span>trim</span>(<span>$_POST</span>['movie_name']) : ''<span>;
                </span><span>if</span>(<span>empty</span>(<span>$movie_name</span><span>))
                {
                    </span><span>$error</span>[] = <span>urlencode</span>('Please enter an movie name'<span>);
                }
                
                </span><span>$movie_type</span> = <span>isset</span>(<span>$_POST</span>['movie_type']) ? <span>trim</span>(<span>$_POST</span>['movie_type']) : ''<span>;
                </span><span>if</span>(<span>empty</span>(<span>$movie_type</span><span>))
                {
                    </span><span>$error</span>[] = <span>urldecode</span>('Please enter an movie type'<span>);
                }
                
                </span><span>$movie_year</span> = <span>isset</span>(<span>$_POST</span>['movie_year']) ? <span>trim</span>(<span>$_POST</span>['movie_year']) : ''<span>;
                </span><span>if</span>(<span>empty</span>(<span>$movie_year</span><span>))
                {
                    </span><span>$error</span>[] = <span>urldecode</span>('Please enter an movie year'<span>);
                }
                
                </span><span>$movie_leadactor</span> = <span>isset</span>(<span>$_POST</span>['movie_leadactor']) ? <span>trim</span>(<span>$_POST</span>['movie_leadactor']) : ''<span>;
                </span><span>if</span>(<span>empty</span>(<span>$movie_leadactor</span><span>))
                {
                    </span><span>$error</span>[] = <span>urldecode</span>('Please enter an movie leadactor'<span>);
                }
                
                </span><span>$movie_director</span> = <span>isset</span>(<span>$_POST</span>['movie_director']) ? <span>trim</span>(<span>$_POST</span>['movie_director']) : ''<span>;
                </span><span>if</span>(<span>empty</span>(<span>$movie_director</span><span>))
                {
                    </span><span>$error</span>[] = <span>urldecode</span>('Please enter an movie director'<span>);
                }
                
                </span><span>$movie_release</span> = <span>isset</span>(<span>$_POST</span>['movie_release']) ? <span>trim</span>(<span>$_POST</span>['movie_release']) : ''<span>;
                </span><span>if</span>(<span>empty</span>(<span>$movie_release</span><span>))
                {
                    </span><span>$error</span>[] = <span>urldecode</span>('Please enter an movie release'<span>);
                }
                </span><span>else</span> <span>if</span>(!<span>preg_match</span>('|^\d{2}-\d{2}-\d{4}$|' , <span>$movie_release</span><span>))
                {
                    </span><span>$error</span>[] = <span>urlencode</span>('Please enter a date in dd-mm-yyyy format'<span>);
                }
                </span><span>else</span><span>
                {
                    </span><span>list</span>(<span>$day</span>, <span>$month</span>, <span>$year</span>) = <span>explode</span>('-', <span>$movie_release</span><span>);
                    </span><span>if</span>(!<span>checkdate</span>(<span>$month</span> , <span>$day</span> , <span>$year</span><span>))
                    {
                        </span><span>$error</span>[] =  <span>urldecode</span>('please enter a validate date'<span>);
                    }
                    </span><span>else</span><span>
                    {
                        </span><span>$movie_release</span> = <span>mktime</span>(0, 0, 0, <span>$month</span>, <span>$day</span>, <span>$year</span><span>);
                    }
                }

                </span><span>$movie_rating</span> = <span>isset</span>(<span>$_POST</span>['movie_rating']) ? <span>trim</span>(<span>$_POST</span>['movie_rating']) : ''<span>;
                </span><span>if</span>(<span>empty</span>(<span>$movie_rating</span><span>))
                {
                    </span><span>$error</span>[] = <span>urldecode</span>('Please enter an movie leadactor'<span>);
                }
                </span><span>else</span> <span>if</span>(!<span>is_numeric</span>(<span>$movie_rating</span><span>))
                {
                    </span><span>$error</span>[] = <span>urlencode</span>('Please enter a numeric rating'<span>);
                }
                </span><span>else</span> <span>if</span>(<span>$movie_rating</span> $movie_rating > 10<span>)
                {
                    </span><span>$error</span>[] = <span>urlencode</span>('Please enter a rating between 1 and 10'<span>);
                }
                
                </span><span>if</span>(<span>empty</span>(<span>$error</span><span>))
                {    
                    </span><span>//</span><span>var_dump($movie_rating);
                    //注意是movie_type不是mvioe_type,大错特错</span>
                    <span>$query</span> = '<span>insert into movie(movie_name,movie_year,movie_type,movie_leadactor,movie_director,movie_release,movie_rating) 
                    values("</span>'.<span>$movie_name</span>.'",'.<span>$movie_year</span>.','.<span>$movie_type</span>.','.<span>$movie_leadactor</span>.','.<span>$movie_director</span>.','.<span>$movie_release</span>.','.<span>$movie_rating</span>.')'<span>;
                
                    
                }
                </span><span>else</span><span>
                {
                    </span><span>//</span><span>注意是Location不是Lacotion,大错特错</span>
                    <span>header</span>('Location:movie_checkformat.php?action=add&error=' . <span>join</span>(<span>$error</span> , <span>urlencode</span>('<br>'<span>)));
                    </span><span>//</span><span>var_dump($error);    
                    //var_dump($_POST);</span>
<span>                }
            </span><span>break</span><span>;
        }
        </span><span>break</span><span>;
    }
    </span><span>case</span> 'edit':
        <span>switch</span>(<span>$_GET</span>['type'<span>])
        {
            </span><span>case</span> 'movie':<span>
            {
                </span><span>$error</span> = <span>array</span><span>();
                </span><span>$movie_name</span> = <span>isset</span>(<span>$_POST</span>['movie_name']) ? <span>trim</span>(<span>$_POST</span>['movie_name']) : ''<span>;
                </span><span>if</span>(<span>empty</span>(<span>$movie_name</span><span>))
                {
                    </span><span>$error</span>[] = <span>urlencode</span>('Please enter an movie name'<span>);
                }
                
                </span><span>$movie_type</span> = <span>isset</span>(<span>$_POST</span>['movie_type']) ? <span>trim</span>(<span>$_POST</span>['movie_type']) : ''<span>;
                </span><span>if</span>(<span>empty</span>(<span>$movie_type</span><span>))
                {
                    </span><span>$error</span>[] = <span>urldecode</span>('Please enter an movie type'<span>);
                }
                
                </span><span>$movie_year</span> = <span>isset</span>(<span>$_POST</span>['movie_year']) ? <span>trim</span>(<span>$_POST</span>['movie_year']) : ''<span>;
                </span><span>if</span>(<span>empty</span>(<span>$movie_year</span><span>))
                {
                    </span><span>$error</span>[] = <span>urldecode</span>('Please enter an movie year'<span>);
                }
                
                </span><span>$movie_leadactor</span> = <span>isset</span>(<span>$_POST</span>['movie_leadactor']) ? <span>trim</span>(<span>$_POST</span>['movie_leadactor']) : ''<span>;
                </span><span>if</span>(<span>empty</span>(<span>$movie_leadactor</span><span>))
                {
                    </span><span>$error</span>[] = <span>urldecode</span>('Please enter an movie leadactor'<span>);
                }
                
                </span><span>$movie_director</span> = <span>isset</span>(<span>$_POST</span>['movie_director']) ? <span>trim</span>(<span>$_POST</span>['movie_director']) : ''<span>;
                </span><span>if</span>(<span>empty</span>(<span>$movie_director</span><span>))
                {
                    </span><span>$error</span>[] = <span>urldecode</span>('Please enter an movie director'<span>);
                }
                
                </span><span>$movie_release</span> = <span>isset</span>(<span>$_POST</span>['movie_release']) ? <span>trim</span>(<span>$_POST</span>['movie_release']) : ''<span>;
                </span><span>if</span>(<span>empty</span>(<span>$movie_release</span><span>))
                {
                    </span><span>$error</span>[] = <span>urldecode</span>('Please enter an movie release'<span>);
                }
                </span><span>else</span> <span>if</span>(!<span>preg_match</span>('|^\d{2}-\d{2}-\d{4}$|' , <span>$movie_release</span><span>))
                {
                    </span><span>$error</span>[] = <span>urlencode</span>('Please enter a date in dd-mm-yyyy format'<span>);
                }
                </span><span>else</span><span>
                {
                    </span><span>list</span>(<span>$day</span>, <span>$month</span>, <span>$year</span>) = <span>explode</span>('-', <span>$movie_release</span><span>);
                    </span><span>if</span>(!<span>checkdate</span>(<span>$month</span> , <span>$day</span> , <span>$year</span><span>))
                    {
                        </span><span>$error</span>[] =  <span>urldecode</span>('please enter a validate date'<span>);
                    }
                    </span><span>else</span><span>
                    {
                        </span><span>$movie_release</span> = <span>mktime</span>(0, 0, 0, <span>$month</span>, <span>$day</span>, <span>$year</span><span>);
                    }
                }

                </span><span>$movie_rating</span> = <span>isset</span>(<span>$_POST</span>['movie_rating']) ? <span>trim</span>(<span>$_POST</span>['movie_rating']) : ''<span>;
                </span><span>if</span>(<span>empty</span>(<span>$movie_rating</span><span>))
                {
                    </span><span>$error</span>[] = <span>urldecode</span>('Please enter an movie leadactor'<span>);
                }
                </span><span>else</span> <span>if</span>(!<span>is_numeric</span>(<span>$movie_rating</span><span>))
                {
                    </span><span>$error</span>[] = <span>urlencode</span>('Please enter a numeric rating'<span>);
                }
                </span><span>else</span> <span>if</span>(<span>$movie_rating</span> $movie_rating > 10<span>)
                {
                    </span><span>$error</span>[] = <span>urlencode</span>('Please enter a rating between 1 and 10'<span>);
                }                
                
                </span><span>if</span>(<span>empty</span>(<span>$error</span><span>))
                {
                    </span><span>//</span><span>var_dump($_POST);</span>
                    <span>$query</span> = '<span>update movie set 
                    movie_name="</span>'.<span>$_POST</span>['movie_name'].'<span>", 
                    movie_type=</span>'.<span>$_POST</span>['movie_type'].'<span>, 
                    movie_year=</span>'.<span>$_POST</span>['movie_year'].'<span>, 
                    movie_leadactor=</span>'.<span>$_POST</span>['movie_leadactor'].'<span>, 
                    movie_director=</span>'.<span>$_POST</span>['movie_director']. '<span> 
                    movie_release=</span>'.<span>$_POST</span>['movie_release'].'<span> 
                    movie_rating=</span>'.<span>$_POST</span>['movie_rating'].'<span> 
                    where movie_id=</span>'.<span>$_POST</span>['movie_id'<span>];            
                }
                </span><span>else</span><span>
                {
                    </span><span>//</span><span>注意是Location不是Lacotion,大错特错</span>
                    <span>header</span>('Location:movie_checkformat.php?action=add&error=' . <span>join</span>(<span>$error</span> , <span>urlencode</span>('<br>'<span>)));
                }
            }
            </span><span>break</span><span>;
        }
        </span><span>break</span><span>;
    </span><span>default</span>:
    <span>break</span><span>;
}
</span><span>if</span>(<span>isset</span>(<span>$query</span><span>))
{
    </span><span>mysql_query</span>(<span>$query</span>,<span>$db</span>) or <span>die</span>(<span>mysql_error</span>(<span>$db</span><span>));
}
</span>?>

    
        <title>Commit</title>
    
    
        <p><span>Done</span>!</p>
    
Copier après la connexion

其实逻辑很简答的,看下面的代码

$movie_leadactor = isset($_POST['movie_leadactor']) ? trim($_POST['movie_leadactor']) : '';
if(empty($movie_leadactor))
{
$error[] = urldecode('Please enter an movie leadactor');
}

其实就是使用isset方法来验证输入是否为空,如果是空的话把错误信息记入到一个数组$error中,然后使用header方法跳转到填写信息的页面中,跳转的方法看上去有点糟糕,如下header('Location:movie_checkformat.php?action=add&error=' . join($error , urlencode('
')));,是将所有错误信息使用换行符来连接起来放到url中来跳转,很我觉得这个有点不合适的。

 

来看填写信息的页面movie_checkformat.php,

<span>php 
</span><span>$db</span> = <span>mysql_connect</span>('localhost','root','Ctrip07185419') or <span>die</span>('can not connect to mysql'<span>);
</span><span>mysql_select_db</span>('moviesite',<span>$db</span>) or <span>die</span>(<span>mysql_error</span>(<span>$db</span><span>));
</span><span>mysql_query</span>('set names gbk',<span>$db</span><span>);
</span><span>if</span>(<span>isset</span>(<span>$_GET</span>['action']) && <span>$_GET</span>['action'] == 'edit'<span>) 
{
    </span><span>$query</span> = 'SELECT movie_name,movie_type,movie_year,movie_leadactor,movie_director,movie_release,movie_rating FROM movie WHERE movie_id='.<span>$_GET</span>['id'<span>];
    </span><span>//</span><span>echo $query;</span>
    <span>$result</span> = <span>mysql_query</span>(<span>$query</span> , <span>$db</span>) or <span>die</span>(<span>mysql_error</span>(<span>$db</span><span>));
    </span><span>extract</span>(<span>mysql_fetch_assoc</span>(<span>$result</span><span>));
}
</span><span>else</span><span>
{
    </span><span>$movie_name</span>=''<span>;
    </span><span>$movie_type</span>=0<span>;
    </span><span>$movie_year</span>=<span>date</span>('Y'<span>);
    </span><span>$movie_leadactor</span>=0<span>;
    </span><span>$movie_director</span>=0<span>;
    </span><span>$movie_release</span>=<span>time</span><span>();
    </span><span>$movie_rating</span>=5<span>;
}
</span>?>

    
        <title>
<?php <span>echo <span>ucfirst</span>(<span>$_GET</span>['action']);?> Movie</title>
        <style type="text/css">
         <!--
            <span>#<span>error { background-color: #600; border: 1px solid #FF0; color: #FFF; text-align: center; margin: 10px; padding: 10px; }
        -->
        </style>
    
     
        <span>php 
            </span><span>if</span>(<span>isset</span>(<span>$_GET</span>['error']) && <span>$_GET</span>['error'] != ''<span>)
            {
                </span><span>echo</span> '<div id="error">'.<span>$_GET</span>['error'].'</div>'<span>;
            }
        </span>?>
        
Copier après la connexion
Movie Name
Movie Type
Movie Year
Lead actor
Director
Movie release date
(dd-mm-YYYY)
Movie rating
php if('edit' == $_GET['action']) { echo ''; } ?>

在html中的body开始的时候如果传递的error参数不为空则输出错误信息,代码如下:

if(isset($_GET['error']) && $_GET['error'] != '')
{
echo '

'.$_GET['error'].'
';
}
?>

很简单,这种写法也很糟糕,完全可以放在javascript中来实现,估计实际生产中很少会有人这么写的。

这里顺便看看一些常见的判断方法:

is_array():判断变量是否是一个数组
is_binary(): 判断变量是否是一个二进制串
is_bool():判断布尔类型变量true还是false,1还是0
is_callable(): 判断变量是否是一个可以访问的函数,估计就是判断是否是代理类型

is_int(): 判断整型
is_null(): 判断是否为空
is_numeric():判断是否是数字或者数字形式的字符串吧
is_object(): 判断变量是否是一个对象
is_resource(): 判断资源类型
is_string(): 判断是否是字符串类型
is_unicode(): 判断是否是unicode字符串

某些时候使用is_xx方法比较慢,使用ctype_xx类型的方法较快,但是它只能检验字符串类型,不能检验对象,数组,资源类型。ctype_xx方法举例如下:

ctype_alnum(): 判断变量是否是数字类型字符串
ctype_alpha(): 判断变量全是字符串
ctype_cntrl(): 判断是控制字符,就是转移字符如"\n"
ctype_digit(): 判断字符串全部是数字字符,不包含任何非数组字符"."这样的也不包含
ctype_graph(): 检查是否有任何可打印字符,除了空格(补)
ctype_lower() : 检查小写字母
ctype_print(): 检查是否都是可打印字符,就是不包含转移字符,和ctype_control()是相斥的
ctype_punct(): 检查是否有任何可打印字符而不是空格或字母数字字符
ctype_space(): 检查是否都是空白字符
ctype_upper() : 检查是否都是大写字符
ctype_xdigit(): 检查是否是16进制的字符串,只能包括 “0123456789abcdef”

 

还可以使用preg_match来检验输入,这个是用正则表达式的方式来进行检验的。

Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

AI Hentai Generator

AI Hentai Generator

Générez AI Hentai gratuitement.

Article chaud

R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
2 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Meilleurs paramètres graphiques
2 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Configuration du projet CakePHP Configuration du projet CakePHP Sep 10, 2024 pm 05:25 PM

Dans ce chapitre, nous comprendrons les variables d'environnement, la configuration générale, la configuration de la base de données et la configuration de la messagerie dans CakePHP.

Guide d'installation et de mise à niveau de PHP 8.4 pour Ubuntu et Debian Guide d'installation et de mise à niveau de PHP 8.4 pour Ubuntu et Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 apporte plusieurs nouvelles fonctionnalités, améliorations de sécurité et de performances avec une bonne quantité de dépréciations et de suppressions de fonctionnalités. Ce guide explique comment installer PHP 8.4 ou mettre à niveau vers PHP 8.4 sur Ubuntu, Debian ou leurs dérivés. Bien qu'il soit possible de compiler PHP à partir des sources, son installation à partir d'un référentiel APT comme expliqué ci-dessous est souvent plus rapide et plus sécurisée car ces référentiels fourniront les dernières corrections de bogues et mises à jour de sécurité à l'avenir.

Date et heure de CakePHP Date et heure de CakePHP Sep 10, 2024 pm 05:27 PM

Pour travailler avec la date et l'heure dans cakephp4, nous allons utiliser la classe FrozenTime disponible.

Téléchargement de fichiers CakePHP Téléchargement de fichiers CakePHP Sep 10, 2024 pm 05:27 PM

Pour travailler sur le téléchargement de fichiers, nous allons utiliser l'assistant de formulaire. Voici un exemple de téléchargement de fichiers.

Discuter de CakePHP Discuter de CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP est un framework open source pour PHP. Il vise à faciliter grandement le développement, le déploiement et la maintenance d'applications. CakePHP est basé sur une architecture de type MVC à la fois puissante et facile à appréhender. Modèles, vues et contrôleurs gu

Routage CakePHP Routage CakePHP Sep 10, 2024 pm 05:25 PM

Dans ce chapitre, nous allons apprendre les sujets suivants liés au routage ?

CakePHP travaillant avec la base de données CakePHP travaillant avec la base de données Sep 10, 2024 pm 05:25 PM

Travailler avec la base de données dans CakePHP est très simple. Nous comprendrons les opérations CRUD (Créer, Lire, Mettre à jour, Supprimer) dans ce chapitre.

CakePHP créant des validateurs CakePHP créant des validateurs Sep 10, 2024 pm 05:26 PM

Le validateur peut être créé en ajoutant les deux lignes suivantes dans le contrôleur.

See all articles