rico
rico

Reputation: 31

Php variables in for selecting in my mysql query

I try to make a selection in SQL using php variables. The code is like this:

$st=$_POST["st"] ;
$tu=$_POST["tu"] ; 
$data=$_POST["data"];
$ec= $_POST["ec"] ;

$sql="SELECT nr, '.$ec.' FROM 'report' WHERE st='.$st.' and tu='.$tu.' and dataupdate='.$data.'";

but I get 0 results.

If I change variables from the SQL query with values, it works. Also I test with

echo $st ; 
echo $tu ; 
echo $data ; 
echo $ec ;

and it returns correct value of post. Can anybody tell me what I do wrong ?

Upvotes: 0

Views: 54

Answers (3)

sandeepsure
sandeepsure

Reputation: 1115

Try this:

$st   = $_POST["st"];
$tu   = $_POST["tu"]; 
$data = $_POST["data"];
$ec   = $_POST["ec"];

$sql = "SELECT nr, $ec FROM `report` WHERE st='$st' and tu='$tu' and dataupdate='$data'";

Upvotes: 0

CodeLove
CodeLove

Reputation: 460

Your right query

$sql="SELECT nr, '".$ec."' FROM 'report' WHERE st='".mysql_escape_string($st)."' and tu='".mysql_escape_string($tu)."' and dataupdate='".mysql_escape_string($data)."'";

Upvotes: 1

Jiri Tousek
Jiri Tousek

Reputation: 12440

First, you're mixing string concatenation using . with replacing variable names directly inside a string quoted using ". You need to choose one of the approaches:

  • "SELECT '$ec' ..."
  • "SELECT '" . $ec . "' ..."

Second, your way to build the SQL query is very dangerous as it allows SQL Injection attack. Use parameterized queries instead: parameters in MySQLi

Upvotes: 1

Related Questions