duanke3985 2015-11-10 21:43
浏览 75
已采纳

如何创建一个if语句来检查变量是否在mysql数据库中

try {
    $conn = new PDO("mysql:host=" . $_GLOBALS['servername'] . ";dbname=". $_GLOBALS['dbname'], $_GLOBALS['username'], $_GLOBALS['password']);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = "SELECT * FROM us WHERE username='$suser' and password='$shashpass'"; // SQL Query

   $conn->exec($sql);

Thats some of my code, how do I make it so if suser and shashpass are correct it can execute some code, else it executes other code

This won't work either

    <?php 
try 
{ 
    $conn = new PDO("mysql:host=" . $_GLOBALS['servername'] . ";dbname=". $_GLOBALS['dbname'], $_GLOBALS['username'], $_GLOBALS['password']); 
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    $query = $con->prepare("SELECT * FROM us WHERE username=:user and password=:password"); $query->bindParam(':user',$suser); 
    $query->bindParam(':password',$shashpass); $query->execute(); $result = $query->fetch(PDO::FETCH_ASSOC); 
    if(!empty($result)){ } else { } } 
catch(PDOException $e) {
    echo $sql . $e->getMessage(); 
} 
  • 写回答

4条回答 默认 最新

  • duanditang2916 2015-11-10 21:49
    关注

    you are using PDO in wrong way , you need to use prepared statements in PDO to be secure from mysql injections, try to use the code below:

     try {
        $conn = new PDO("mysql:host=" . $_GLOBALS['servername'] . ";dbname=". $_GLOBALS['dbname'], $_GLOBALS['username'], $_GLOBALS['password']);
        // set the PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
        $query = $con->prepare("SELECT * FROM us WHERE username=:user and password=:password");
        $query->bindParam(':user',$suser);
        $query->bindParam(':password',$shashpass);
        $query->execute();
        $result = $query->fetch(PDO::FETCH_ASSOC);
        if(!empty($result)){
         // user is in database
        } else {
    
        // user is not there 
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?