-1

I have mySQL tables namely q1 , q2 , q3 and so on....

now the following code is in loop with $n increasing with every step of loop.

$table = "q".$n;
$query="SELECT MAX(QNO) AS max2 FROM '$table'";
$q=mysqli_query($db,$query) or die("Error: ".mysqli_error($db));
$max2 = mysqli_fetch_array($q);

This gives me an error

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"q1"' at line 1

How to solve this problem and putting new name of table everytime in the query?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
MegaMind
  • 653
  • 6
  • 31
  • You need to quote tables & column names with backticks, not single quotes. http://stackoverflow.com/questions/11321491/when-to-use-single-quotes-double-quotes-and-backticks – Michael Berkowski Dec 31 '14 at 11:56
  • Did you try without the single quotes around the table name? – Jeroen de Lau Dec 31 '14 at 11:56
  • If the value for `$n` originates from user input, be sure to validate it before using it in `$table`. It looks like you are creating quarters `q1, q2, q3, q4` so that it is an integer, and in the range 1-4. If it is strictly created in code by literal ints, don't worry about validating it as much. – Michael Berkowski Dec 31 '14 at 11:58

2 Answers2

0

Please change

'$table'

into

`$table`

in the query:

"SELECT MAX(QNO) AS max2 FROM '$table'";

so it looks like:

"SELECT MAX(QNO) AS max2 FROM `$table`";
0

$query="SELECT MAX(QNO) AS max2 FROM $table"; is enough

Kiren S
  • 3,037
  • 7
  • 41
  • 69