2016-10-23 4 views
0

В настоящее время мы строим проект блокировки сайта, и у меня есть только несколько вопросов о php и как phpmyadmin реагирует на определенные действия. Я использую wampserver signup.php, по-видимому, не показывает ошибок при вводе новой учетной записи, имя пользователя и пароль должны быть сохранены в базе данных. Вот он:MySQL не работает на localhost

<?php 
require_once ("functions.php"); 
require_once ('config.php'); 
require_once ('User.php'); 
require_once ('Session.php'); 

$default_label = 0; 
$error = null; 

if($session->isLoggedIn()){ 
    redirectTo("home.php"); 
} 

if(requestIsPost()) { 
    global $session; 
    $params = requiredPostParams(['username' , 'password' , 'label'] , $strict=true); 

    if($params != null){ 
     $default_label = $params['label']; 

     // put the data into data base and redirect to login 

     $ouser = User::findByUsername($params['username']); 

     if($ouser == null) { 

      try{ 
       $nuser = new User(); 
       $nuser->initialize($params['username'] , $params['password'] , $params['label']); 
       $nuser->save(); 

       // everything is set, train the recognizer 
       $faceLIb = new COM($LIB_CLSID); 
       $nextDir = $unused_face_dir."/s".(string) $default_label; 
       $nextDirDest = $face_dir."/s".(string) $default_label; 
       rename($nextDir , $nextDirDest);  // move directory into usable faces 
       $faceLIb->train($face_dir , $rec_path); 

       redirectTo("login.php"); 
      } catch (InvalidUserData $iud) { 
       $error = "Invalid user data. Try Again"; 
      } catch (DBQueryException $dbe) { 
       $error = "Application Error. Try Again"; 
      } catch (DBConnectException $dce) { 
       $error = "Application error. Try Again"; 
      } 
     } else { 
      $error = "Email alredy registered"; 
     } 
    } 
} 
?> 

<html> 
<head> 
<title>Signup</title> 
</head> 

<body> 
<?php if($error != null) echo $error; ?> 

<form action="" method="post" id = "dataform"> 
    Email: <input type="text" name="username"><br> 
    Password: <input type="password" name="password"><br> 
    <input type="hidden" name="label" id = "label" value = <?php echo '"'.$default_label.'"'; ?> > 
    <input type="button" value="Submit" id="submit_form"> 
</form> 

<!-- the video scanner --> 
<video id="video" width="640" height="480" autoplay></video> 
<button id="snap">Snap Photo</button> 
<canvas id="canvas" width="640" height="480" style = "display:none"></canvas> 

<h1 id="status"></h1> 

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

// test if the camera is available 

var video = document.getElementById('video'); 
var canvas = document.getElementById('canvas'); 
var context = canvas.getContext('2d'); 

if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { 
    navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) { 
     video.src = window.URL.createObjectURL(stream); 
     video.play(); 
    }); 
} 

// event handlers 
$("#snap").on("click" , function(){ 

    train = function(){ 
     $.ajax({ 
      type: "GET", 
      url: "train.php", 
      data: "{}", 
      dataType: 'json', 
      success: function(result){ 
        console.log(result); 
        if(result.code == 1) { 
         $("#label").val(result.label); 
         $("#status").text("Succesful"); 
        }  
        else alert("Face detection Failed! Try again"); 
       } 
     }); 
    } 

    // send an image to the server, on sucess call recursive. do it 'i' times 
    send_images = function(i){ 
     if(i === 0) { 
      $("#status").text("submitting ..."); 
      train(); 
      return; 
     } 

     $("#status").text(i); 

     // extract an image from the live camera 
     context.drawImage(video, 0, 0, 640, 480); 
     var url = canvas.toDataURL('image/png'); 

     $.ajax({ 
      type: "POST", 
      url: "upload.php", 
      //dataType: 'jsonp', 
      data: { 
       "url" : url 
      }, 
      success: function(result){ 
        send_images(i-1); 
      } 
     }); 
    } 

    $.ajax({ 
      type: "GET", 
      url: "ready.php", 
      success: function(result){ 
        console.log(result); 
      } 
     }); 

    send_images(10); 
}); 

$("#submit_form").on("click" , function(){ 
    var label = parseInt($("#label").val()); 
    if(label < 1) alert("User saved. Use Snap photo to train image."); 
    else $('form#dataform').submit(); 
}); 

</script> 
</body> 
</html> 

<?php 

require_once("config.php"); 
require_once("SQLTable.php"); 
require_once("Validator.php"); 
require_once("Texter.php"); 
require_once("exceptions.php"); 

class User extends SQLTable{ 
    /** 
    * @Overridden properties 
    */ 
    protected static $tableName = 'users'; 
    protected static $dbFields = array("id" , "name" , "password" , "label"); 
    protected $id; 

    /** 
    * @type: SQL.varchar(64) 
    * Name of the user, should not contain anything other than alpha and whitespace 
    */ 
    protected $name;   //TODO : TEST what happens while saving if some variable is not set 
    /** 
    * @type: SQL.varchar(64) 
    * Encrypted user password, Real Escaping is done after the encryption 
    */ 
    protected $password;   
    protected $label; 

    public function __construct(){ 
     parent::__construct(); 
    } 

    /** 
    * get functions 
    */ 
    public function getId(){ 
     return $this->id; 
    } 

    public function getLabel(){ 
     return $this->label; 
    } 

    /** 
    * Sets all the properties of object. 
    * Must call this function before calling save on this object, if not initialized by find* functions 
    */ 
    public function initialize($name=null , $password=null , $label= null){ 
     if(Validator::isValidEmail($name)){ 
      $this->name = $name; 
     }else { 
      throw new InvalidUserData("Username is not valid"); 
     } 
     if(Validator::isValidPassword($password)){ 
      $this->password = Texter::encryptPassword($password); 
     }else { 
      throw new InvalidUserData("Password is not valid"); 
     } 

     $this->label = $label; 
    } 

    /** 
    * @Defination: Reset saved password 
    * */ 
    public function setPassword($newPass) { 
     if(Validator::isValidPassword($newPass)){ 
      $this->password = Texter::encryptPassword($newPass); 
     }else { 
      throw new InvalidUserData("Password is not valid"); 
     } 
     return $this; 
    } 

    /** 
    * @Defination: Authenticate user by name and password 
    * @return: Object of this class if authenticated, null otherwise 
    */ 
    public static function authenticate($name = null , $password = null){ 
     if(! Validator::isValidEmail($name) || ! Validator::isValidPassword($password)) 
      return null; 
     $name = self::escapeValue($name); 
     /**TODO, find how right is next step ? */ 
     $password = Texter::encryptPassword($password); 
     $password = self::escapeValue($password); 
     $sql = "SELECT * FROM ".static::$tableName; 
     $sql .= " WHERE name = '{$name}' AND "; 
     $sql .= "password = '{$password}' "; 
     $sql .= "LIMIT 1"; 
     $resultSet = self::findBySQL($sql); 
     return !empty($resultSet) ? array_shift($resultSet) : null; 
    } 

    public static function findByUsername($name = null){ 
     if(! Validator::isValidEmail($name)) return null; 
     $name = self::escapeValue($name); 
     $sql = "SELECT * FROM ".static::$tableName ." WHERE name='{$name}' LIMIT 1"; 
     $resultSet = self::findBySQL($sql); 
     return !empty($resultSet) ? array_shift($resultSet) : null; 
    }  
} 

PS. Мне может потребоваться загрузить и другие коды, но я не уверен, что это такое.

+0

Вы просмотрели журналы ошибок? –

+0

PhpMyAdmin - это не база данных. MySQL - это база данных. –

+0

Это может быть большая проблема, чем просто PHP не работает, но убедитесь, что в XAMPP нет ошибок (что я предполагаю, что вы используете) - нам нужна дополнительная информация :-) – Jek

ответ

0

Я предполагаю, что config.php - это ваш файл базы данных. Если да, измените порядок файлов на верх, а затем попробуйте.