且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 PHP/MYSQL 检查用户名是否已存在

更新时间:2023-11-28 13:48:52

MYSQL: 此扩展在 PHP 5.5.0 中已弃用,并在 PHP 7.0.0 中删除.相反,应该使用 MySQLiPDO_MySQL 扩展.

MYSQL: This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.

MYSQLI 参考:http://php.net/manual/en/mysqli.query.php

PDO 参考:http://php.net/manual/en/book.pdo.php

使用 PDO 的优势:

Advantages of using PDO:

大多数 PHP 程序员已经发现了如何使用 MySQLi 和 MySQL 扩展.但是,PHP 数据对象 (PDO) 提供了处理对象和检索准备好的语句的方法,这使工作变得更加容易.

Most PHP programmers have discovered how to use MySQLi and MySQL extensions. However, PHP Data Objects (PDO) offer ways to work with objects and retrieve prepared statements which make work much easier.

PDO 是 PHP 中的数据库访问工具,可实现跨多个数据库的统一访问.它不支持特定于数据库的语法,但允许在不同平台和数据库之间进行相对无缝的切换,只需更改连接字符串即可.

PDO is a database access tool in PHP which enables uniform access across multiple databases. It does not support syntax's specific to databases, but it permits relatively seamless switching between different platforms and databases, which can simply be done by changing the connection string.

下面是一些关于PDO的资料,主要针对还在使用MySQL和MySQLi扩展的程序员,概述前者的优越性.在接下来的几段中将研究不同的方面.

Below is a little information about PDO, mainly directed at programmers who are still using MySQL and MySQLi extensions, outlining the superiority of the former. Different aspects will be studied in the next few paragraphs.

  • 数据库支持

PDO 扩展能够访问任何已为其编写 PDO 驱动程序的数据库.有许多 PDO 驱动程序可用,其中一些包括旨在访问 Free TDS、Sybase、Microsoft SQL Server、IBM DB2、Firebird/Interbase 6、Oracle Call Interface 和 PostgreSQL 数据库等的 PDO 驱动程序.

The PDO extension has the capability to access any database which the PDO driver has been written for. There are many PDO drivers available, a few of which include PDO drivers meant to access Free TDS, Sybase, Microsoft SQL Server, IBM DB2, Firebird/Interbase 6, Oracle Call Interface and PostgreSQL databases, among many more.

并非每个系统都自动提供驱动程序,因此您必须找到可用的驱动程序并添加所需的驱动程序.

The drivers are not automatically available in every system, so you will have to find your available drivers and add the ones that you need.

  • 数据库连接

建立依赖于特定数据库的数据库连接有不同的语法.使用 PDO 时,您希望确保您的操作包含在 try/catch 块中并使用异常技术.

There are different syntax's to establish database connections which depend on specific databases. When using PDO, you want to ensure that your operations are wrapped in try/catch blocks and that you utilize the exception technique.

在正常情况下,只需要建立一个连接,通过将数据库句柄编程为空来关闭连接.您可以在各种资源站点中查找更具体的选项和语法.

In normal cases, only a single connection need be made, and connections are closed by programming the database handle as a null. You can look up more specific options and syntax's in various resource sites.

  • 错误处理

PDO 允许使用异常进行错误处理,这就是为什么建议您将 PDO 包装在 try/catch 块中的原因.这样,可以强制 PDO 进入相关的错误模式属性以产生异常.

PDO allows for the use of exceptions for error-handling, which is why you’re advised to wrap PDO in try/catch blocks. This way, PDO can be forced into the relevant error mode attribute in order to produce an exception.

共有三种——静默(默认)、警告和异常——模式.后两者在 DRY 编程中更有用.警告"错误模式对于调试很有用,异常"模式允许优雅的错误处理,同时隐藏人们可能用来利用您的系统的数据.

There are three – silent (default), warning and exception – modes. The latter two are more useful in DRY programming. ‘Warning’ error mode is useful for debugging and the ‘exception’ mode allows graceful error handling while hiding data that a person might use to exploit your system.

  • 插入和更新

PDO 将常见的插入和更新数据库操作浓缩为一个简单的两步过程:Prepare >>[绑定] >>执行.使用这种方法,您可以充分利用 PDO 的预准备语句,它可以保护您免受 SQL 注入的恶意攻击.

PDO condenses the common insert and update database operations into a simple two-step process: Prepare >> [Bind] >> Execute. With this method, you can take full advantage of PDO’s prepared statements, which offer you protection against malicious attacks through SQL injection.

准备好的语句是预先编译好的 SQL 语句,可以通过将这些数据发送到服务器来执行多次.它们的优势在于占位符中使用的数据会自动受到保护,免受 SQL 注入攻击.

Prepared statements are pre-complied SQL statements which may be executed several times by sending this data to the servers. They are advantageous in that data used within the placeholders is automatically protected from SQL injection attacks.

因此***使用 PDO,它可以避免现在流行的 SQL 注入.

Hence It is better to use PDO and it will avoid the SQL Injections that are prevailing now a days.

用于检查数据库中是否存在用户名和密码字段的 PDO 代码:

 <?php
//Connections
try {
    $handler = new PDO('mysql:host=localhost;dbname=s','root', '*');
    $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e){
    exit($e->getMessage());
}

$name = $_POST['name']; 
$username = $_POST['username']; 
$email = $_POST['email'];   
$password = $_POST['password']; 
$password1 = $_POST['passwordconf'];
$ip = $_SERVER['REMOTE_ADDR'];


//Verifcation 
if (empty($name) || empty($username) || empty($email) || empty($password) || empty($password1)){
    $error = "Complete all fields";
}

// Password match
if ($password != $password1){
    $error = "Passwords do not match";
}

// Email validation

if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
    $error = "Enter a Valid email";
}

// Password length
if (strlen($password) <= 6){
    $error = "Choose a password longer then 6 character";
}

if(!isset($error)){
//no error
$sthandler = $handler->prepare("SELECT username FROM users WHERE username = :name");
$sthandler->bindParam(':name', $username);
$sthandler->execute();

if($sthandler->rowCount() > 0){
    echo "User Already Exists.";
} else {
    //Securly insert into database
    $sql = 'INSERT INTO users (name ,username, email, password, ip) VALUES (:name,:username,:email,:password,:ip)';    
    $query = $handler->prepare($sql);

    $query->execute(array(

    ':name' => $name,
    ':username' => $username,
    ':email' => $email,
    ':password' => $password,
    ':ip' => $ip

    ));
    }
}else{
    echo "error occured: ".$error;
    exit();
}

希望此参考资料对您在以后的项目中自己开发代码有用.

Hope so this reference might be useful for you to develop the codes in the future project by yourself.