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 ?

2
  • your sql is wrong. you can echo the $sql and try it on phpmyadmin to check weather its correct. Commented Oct 27, 2015 at 9: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 Commented Oct 27, 2015 at 9:58

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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)."'";

1 Comment

I feel the Dark Side of the Force! I feel sql-injection here
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'";

3 Comments

what about some sql-injection in your query?
@SergioIvanuzzo you can use mysql_real_escape_string() to overcome this.
I can, but instead I will use sprintf or PDO and prepare method :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.