如何在查询语句中添加PHP变量?

时间:2015-06-03 15:38:45

标签: php sql-server

我试图把PHP变量

$EventID 

直接进入查询语句。我尝试使用a作为休息,就像你在echo语句中那样,但这不起作用。你是怎么做到的?

$EventID = $_GET['id'];
//I took the $serverName variable out for obvious reasons
$connectionOptions = array("Database"=>"Seminars", "UID"=>"sa","PWD"=>"scr0gg1ns");
$conn = sqlsrv_connect( $serverName, $connectionOptions);

$query = "SELECT * FROM Event where EventID =", $EventID;
$stmt1 = sqlsrv_query( $conn, $query); 

5 个答案:

答案 0 :(得分:1)

首先,我强烈建议您使用PDO来查询数据库。 "准备好的陈述"本教程的部分也将回答您的问题。

如果您认为这太先进而且只是想现在尝试一些简单的事情,您可以简单地执行以下操作:

$query = "SELECT * FROM Event where EventID = '$EventID'";

答案 1 :(得分:0)

只需添加$ EventID字符串即可。这个php使用. 像下面的代码

 $EventID = $_GET['id'];
 //I took the $serverName variable out for obvious reasons
 $connectionOptions = array("Database"=>"Seminars", "UID"=>"sa","PWD"=>"scr0gg1ns");
$conn = sqlsrv_connect( $serverName, $connectionOptions);

$query = "SELECT * FROM Event where EventID ="  .  $EventID;
$stmt1 = sqlsrv_query( $conn, $query); 

答案 2 :(得分:0)

在将变量用于请求以防止sql注入之前,您应该清理变量

$query = "SELECT * FROM Event where EventID ='$EventID'";

答案 3 :(得分:0)

您可以按照以下方式执行此操作:

$query = "SELECT * FROM Event where EventID = {$EventID}";

但是,这意味着黑客可以在您的网站上轻松使用SQL注入,因此您不应该这样做。使用预准备语句代替PDO或mysqli。

答案 4 :(得分:-1)

您的查询应如下所示:

$query = "SELECT * FROM Event where EventID =".$EventID;