[php] An error when I add a variable to a string

I have this line of SQL:

$sql = "SELECT ID, ListStID, ListEmail, Title FROM $entry_database WHERE ID = '". $ReqBookID ."'";
$result = mysqli_query($conn, $sql);

As you can see, I am selecting an entry's ID, ListStID, ListEmail and Title Column if ID is equal to a string of numbers (or text), which is given by user in a form.

Everything is ok, and I don't get any syntax error when I write the code (I am using a code editor software. However, when I use it online, I get this error:

Error: SELECT ID, ListStID, ListEmail, Title FROM WHERE ID = '4' You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE ID = '4'' at line 1

I am very new to PHP, and I'm sure I am either adding extra ' or ", so I would really appreciate it if you could help me with this issue. I have tried the answers for similar questions, but no success yet.

This question is related to php

The answer is


You're missing your database name:

$sql = "SELECT ID, ListStID, ListEmail, Title FROM ".$entry_database." WHERE ID = ". $ReqBookID .";

And make sure that $entry_database isn't null or empty:

var_dump($entry_database);

Also notice that you don't need to have $ReqBookID in '' as if it's an Int.


This problem also arise when we don't give the single or double quotes to the database value.

Wrong way:

$query ="INSERT INTO tabel_name VALUE ($value1,$value2)";

As database inserting values must be in quotes ' '/" "

Right way:

$query ="INSERT INTO STUDENT VALUE ('$roll_no','$name','$class')";