2013-02-17 51 views
-2

我有一個登錄系統,我一直在使用mysql函數,如real_escape_strings等。但現在我試圖將其轉換爲PDO,因爲它比mysql功能更現代。現在的問題是它不適用於PDO。以下是我的代碼,請告訴我我該做什麼錯了。如何將mysql函數轉換爲現代PDO

<?php 
try { 
$con = new PDO('mysql:host=localhost;dbname=tish_database;charset=utf8','root',''); 

} catch(PDOException $e){ 
echo 'Connection failed'.$e->getMessage(); 
} 

?> 
<?php 
$is_ajax = $_POST['is_ajax']; 
    if(isset($is_ajax) && $is_ajax) 

    { 
$username =(isset($_POST['username']))? trim($_POST['username']): ''; 
$Password=(isset($_POST['Password']))? $_POST['Password'] : ''; 
$redirect=(isset($_REQUEST['redirect']))? $_REQUEST['redirect'] : 
'view.php'; 
$query ='SELECT username FROM tish_user WHERE '. 
'username="'.($username,$con).'" AND ' . 
    'Password = md5("'.($Password,$con).'")'; 
    $result = $con->prepare($query); 
    $result->execute(); 
     if(count($result)>0) 
     { 
     $_SESSION['username']=$username; 
$_SESSION['logged'] = 1; 
      echo "success"; 
     } 
     else { 
//set these explicitly just to make sure 

} 
    } 

?> 
+3

'($的用戶名,$ CON)'答案 - 這是什麼? – 2013-02-17 08:09:06

+1

@你的常識你是一個偉大的人,這是唯一的問題。所以你固定感謝100%。每一個問題我得到你設法解決它再次感謝 – humphrey 2013-02-17 08:12:42

+2

請了解***現代方式***創建查詢:http://www.phptherightway.com/#databases – deceze 2013-02-17 08:14:01

回答

2

刪除所有無用的代碼

<?php 
$con = new PDO('mysql:host=localhost;dbname=tish_database;charset=utf8','root',''); 

if(!empty($_POST['is_ajax'])) 
{ 
    $sql = 'SELECT id FROM tish_user WHERE username=? AND Password = md5(?)'; 
    $stm = $con->prepare($sql); 
    $stm->execute(array($_POST['username'],$_POST['Password'])); 
    if($row = $stm->fetch()) 
    { 
     $_SESSION['id'] = $row['id']; 
    } 
} 
?> 

後,你需要太檢查字母大小寫。大寫'密碼'看起來很可疑。最好選擇一個標準(全部小寫),並按照它無處不

這是我在How prepared statements can protect from SQL injection attacks?問題解釋它是如何工作

+0

是的這很好,但我想問這個代碼是否逃脫字符串? – humphrey 2013-02-17 08:27:06

+0

是的,我沒有訪問鏈接,謝謝 – humphrey 2013-02-17 08:55:03

+0

請邀請我在谷歌談話kingmusa5 @ gmail.com – humphrey 2013-02-17 09:39:05

0
$query ='SELECT username FROM tish_user WHERE username=? AND Password = md5(?))'; 
$result = $con->prepare($query); 
$result->execute(array($username, $password)); 

這將自動跳脫字符串爲您服務。

+0

非常有幫助謝謝 – humphrey 2013-02-17 08:28:36