0

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 ?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
rico
  • 31
  • 1
  • your sql is wrong. you can `echo` the `$sql` and try it on phpmyadmin to check weather its correct. – Athi Krishnan Oct 27 '15 at 09:54
  • this error happened because you don't around your string variables with quotes. P.S. you can also use sprintf to avoid sql-injection. Or, better, use PDO – Sergio Ivanuzzo Oct 27 '15 at 09:58

3 Answers3

1

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)."'";
CodeLove
  • 462
  • 4
  • 14
1

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

Community
  • 1
  • 1
Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43
0

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'";
Jazi
  • 6,569
  • 13
  • 60
  • 92
sandeepsure
  • 1,113
  • 1
  • 10
  • 17