0

I want to select query from database. if I write this code :

$selectOption = $_GET['name'];
echo $selectOption.'<br>';
$sql = "SELECT 'rpm' FROM sn WHERE power = '1s1s'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {
echo "rpm: " . $row["rpm"];
}
} else {
echo "0 results";
}

It shows me correct answer. Otherwise , if I write this :

$sql = "SELECT 'rpm' FROM 'sn' WHERE 'power' = '$selectOption'";

It shows me 0 results. any suggestion to correct above query?

Farzan Najipour
  • 2,442
  • 7
  • 42
  • 81
  • 3
    Use backticks (`) for field name not single quotes. – frz3993 Jan 01 '16 at 17:25
  • What does `$selectOption` holds? – Rajdeep Paul Jan 01 '16 at 17:27
  • better still don't use single quotes or tilde characters around field names. the single quote turns the column name into a string, the tilde or backslash is not standard sql, and is not necessary unless you've used a reserved word as a column name. Best practice in that case is to rename the column. – Niagaradad Jan 01 '16 at 17:28
  • maybe you don't have any data stored in database for the value of `$selectOption` – Anish Silwal Jan 01 '16 at 17:28
  • 2
    That second query (with the variable in it) is wide open to SQL-injection, see [How can I prevent SQL-injection in PHP?](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). You should use prepared statements, *specially* when you're bringing variables in from `$_GET` – Qirel Jan 01 '16 at 17:28
  • 1
    $sql = "SELECT `rpm` FROM `sn` WHERE `power` = '$selectOption'"; use (backticks) – Alive to die - Anant Jan 01 '16 at 17:28
  • *"It shows me correct answer"* - and using `$sql = "SELECT 'rpm' FROM sn WHERE power = '1s1s'";`? I find that rather hard to believe. Not with those quotes `'` it won't. – Funk Forty Niner Jan 01 '16 at 17:38

1 Answers1

1

You need to do two things, both are stated in comments:-

1.Use backticks(`) in your query like this:-

 $sql = "SELECT `rpm` FROM `sn` WHERE `power` = '$selectOption'";

2.Prevent your query from SQL Injection. For that use prepared statement. Link is given in comment section. For your help i put it in my answer :- How can I prevent SQL injection in PHP?

Community
  • 1
  • 1
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98