如何将MySQL字符串转换为SQL Server等价物

时间:2012-03-17 00:42:33

标签: php mysql sql

我目前在客户网站上工作,我遇到了一些问题。我正在使用一个使用MySQL字符串的同事向我显示的登录系统。我将客户端的信息插入其中并加载它并出现连接错误。梳理完代码后,我发现了一些错误,但修复它们并没有解决连接问题。在客户端的Web主机上挖掘后,我注意到他们的数据库托管在Microsoft SQL服务器而不是MySQL服务器上。现在问题出现了:

1.。)如何将MySQL字符串更改为SQL Server字符串?

2.。)我仍然可以使用PHP来操作SQL Server字符串吗?

3。)你们推荐哪些好的教程可以帮助我更好地理解这一点吗?


参考

这是我正在使用的MySQL字符串,包括由PHP操作的行:

    // Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

// Define $myusername and $mypassword 
$myusername=$_POST['myusername']; 
$mypassword=$_POST['mypassword'];

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

$sql="SELECT * FROM $tbl_name WHERE user_name='$myusername' and user_pswd='$mypassword'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row

if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
    $_SESSION['myusername'];
    $_SESSION['mypassword']; 

    header("location:Inside.php");
} else {
    echo "Wrong Username or Password";
}

任何建议都将不胜感激。提前谢谢!

3 个答案:

答案 0 :(得分:3)

由于数据库不再是MySQL,因此您必须重写一些使用MySQL函数的代码。这可以通过PDO(PHP数据对象)轻松完成,并且对于将来的更改而言更加便携。

看看这个SQL Server example

<?php

   $user = 'myUsername';
   $pass = 'myPassword';

   // Connect to mssql database
   $conn = new PDO('mssql:host=127.0.0.1; dbname=tempdb;', $user, $pass);

   $query = "SELECT * FROM table1";

   // Prepare query and run it. This is where you can use prepared statements
   // to avoid SQL injection
   $sth = $conn->prepare($query);
   $sth->execute();

   // Fetch the returned db rows and dump them as output
   $retRows = $sth->fetchAll();
   var_dump($retRows);

   // Clean up resources
   unset($sth); unset($conn);

?>

在代码中找到类似mysql_*的函数的任何地方,您都希望使用PDO查找正确的方法。

答案 1 :(得分:2)

您需要将为mysql调用的PHP函数更改为等效的Sql Server函数。

mysql_connect() =&gt; mssql_connect()

mysql_select_db() =&gt; mssql_select_db()

mysql_num_rows() =&gt; mssql_num_rows()

以下是SQL Server所有函数的列表。 http://php.net/manual/en/book.mssql.php

答案 2 :(得分:2)

其中一些很容易转换为SQL Server,但其他一些事情有点棘手。

举一个例子,让我们采取LIMIT。 SQL Server中没有LIMIT这样的东西。而GROUP BY的行为则更加不同,需要重写大量的聚合查询。

另一方面,SQL Server确实提供了一些MySQL没有提供的非常好的功能。

如果你正在努力使用LIMIT,你应该阅读TOP或ROW_NUMBER()。对于GROUP BY查询,您应该明显阅读GROUP BY,并将其与任何排名函数(如(ROW_NUMBER(),DENSE_RANK()...等)结合使用OVER(PARTITION BY col ORDER BY col)...