2015-11-04 44 views
4

如何從MYSQL切換到MYSQLI?因爲我嘗試過,但返回一個空值。謝謝你提前!Mysqli的Mysql

MySQL代碼:

if(isset($_POST["username"])&& isset($_POST["password"])){ 

    $manager = preg_replace('#[^A-Za-z0-9]#i','',$_POST["username"]); 
    $password = preg_replace('#[^A-Za-z0-9]#i','',$_POST["password"]); 
    include "includes/connect_db.php"; 
    $sql = mysql_query("SELECT id FROM admin WHERE username='$manager' 
     AND password=$password' LIMIT 1"); 

    $existCount = mysql_num_rows($sql);//count the row nums 
    if($existCount == 1){//evaluate the count 
     while($row=mysql_fetch_array($sql)){ 
      $id=$row["id"]; 
     } 
     $_SESSION["id"] = $id; 
     $_SESSION["manager"]=$manager; 
     $_SESSION["password"]=$password; 
     header("location:index.php"); 
     exit(); 

    }else{ 
     echo 'That information is incorrect, try again <a href="index.php">Click Here</a>'; 
     exit(); 
    } 

這是我以前試過,但告訴我一個消息,mysqli_num_rows有布爾結果。

的mysqli代碼:

if(isset($_POST["username"])&& isset($_POST["password"])){ 

    $manager = preg_replace('#[^A-Za-z0-9]#i','',$_POST["username"]); 
    $password = preg_replace('#[^A-Za-z0-9]#i','',$_POST["password"]); 
    include("includes/insert_db.php"); // i change the database connection 
    $sql = "SELECT * FROM admin WHERE username='$manager' 
    AND password=$password'"; 

    $result = mysqli_query($con, $sql); 

    $existCount = mysql_num_rows($result);//count the row nums 
    if($existCount == 1){//evaluate the count 
    while($row=mysqli_fetch_array($result)){ 
    $id=$row["id"]; 
    } 
    $_SESSION["id"] = $id; 
    $_SESSION["manager"]=$manager; 
    $_SESSION["password"]=$password; 
    header("location:index.php"); 
    exit(); 

    }else{ 
    echo 'That information is incorrect, try again <a href="index.php">Click Here</a>'; 
    exit(); 
    } 
} 
+2

我們不知道你有connect_db.php ... – fico7489

+2

告訴我們,你試圖寫的MySQLi代碼。這是MySQL代碼。 –

+1

http://stackoverflow.com/questions/31178092/switching-on-mysqli-over-mysql –

回答

5

嘗試改變這一點:

$sql = mysql_query("SELECT id FROM admin WHERE username='$manager' 
AND password=$password' LIMIT 1"); 

這樣:

$sql = "SELECT id FROM admin WHERE username='$manager' AND password='$password' LIMIT 1"; 

$result = mysqli_query($conn, $sql); 

或本:

$sql = "SELECT id FROM admin WHERE username='$manager' AND password='$password' LIMIT 1"; 
$result = $conn->query($sql); 

($ conn是連接變量,如果它不同,則更改它。) 希望這有助於解決問題。

也改變mysql_fetch_array($sql)mysqli_fetch_array($sql)

+0

我嘗試它,但它說:mysql_num_rows()期望參數1是資源,布爾給出 –

+0

對不起,我沒有看到這一點,當我發佈awnser,但查詢是這樣的 '「SELECT id FROM admin WHERE username ='$ manager 'AND password = $ password'LIMIT 1'' 將其更改爲此 ''SELECT id FROM admin WHERE username ='$ manager'AND password ='$ password'LIMIT 1「' – BRoebie

+1

使用準備好的語句而不是添加變量進入字符串。所以你可以防止注射 – inetphantom

-1

爲什麼要重新發明輪子。有一個偉大的PHP腳本,將PHP文件從mysql轉換爲mysqli,並將進行備份和完成整個目錄。我已經在不同的程序中使用了它幾次,它還沒有失敗。

https://github.com/philip/MySQLConverterTool