表单内容为PostGre查询参数

时间:2016-01-14 18:03:52

标签: php postgresql

所以,我对网络很新。我总是摆弄HTML和SQL,但最近我开始研究一个项目。该项目基本上创建了一个包含所有员工联系人数据(姓名,电子邮件,电话号码等)的数据库,并在网上显示。设置数据库,网页正常连接到DB(我可以调用PHP并发送查询,结果显示完美)。但我不知道如何使用<form>内容(用户编写的文本)作为查询参数。我想在Enter或按下'busca'按钮时发送参数 这是表格

<form id="searchbox" >
    <label for="sectname">
    </label>
    <input id="sectname" name="sectname" type="search"      placeholder="Busca" list="setor" class="searchbox"/>
    <div style="text-align:center">
        <input id="submit" type="button" class="button" value="BUSCA"/>
    </div>
</form> 

这是带查询的PHP

$host        = "host=localhost";
$port        = "port=5432";
$dbname      = "dbname=Cards";
$creds = "user=postgres password=12345678";

$db = pg_connect( "$host $port $dbname $creds"  );
if(!$db){
  echo nl2br ("Unable to open database\n");
} 

$sql =<<<EOF
  SELECT * from Cards where nome='Diego Teste';
EOF;

$ret = pg_query($db, $sql);
if(!$ret){
  echo pg_last_error($db);
  exit;
} 
while($row = pg_fetch_assoc($ret)){
   echo "<div>";
  echo "<img src='".$row['pic']."'class='cardcontent2'/>";
   echo "<div class='carddata'>";
  echo nl2br ("\nNome: ".$row['nome'] . "\n");
  echo nl2br ("Email: ".$row['email'] . "\n");
  echo nl2br ("Ramal: ".$row['ramal'] . "\n");
  echo nl2br ("Número: ".$row['numero'] . "\n");
  echo nl2br ("Setor: ".$row['setor'] . "\n\n");
  echo "</div>";
  echo "</div>";
}

pg_close($db);

我希望'nome =“Diego Teste”'为'nome =%var%',%var%值应为用户编写的文本。

1 个答案:

答案 0 :(得分:0)

诀窍是使用准备好的陈述:(ref

$basequery =<<<EOF
    SELECT * from Cards where nome = $1;
EOF;

pg_prepare($db, "my_query", $basequery);
$results = pg_execute($db, "my_query", array($_GET["nome"]));

...

准备好的语句负责转义您将传递给SQL的任何值,因此您不必自己完成。它可以保护您免受SQL注入;有些人会填写表单字段,其中包含恶意内容,如果您只是将字段文本放在原位,那么可能会破坏您的SQL语句。

我的PHP可能有点生疏,所以如果我犯了小错误,请原谅我。