user3301042
user3301042

Reputation: 352

Doing simple math in SQL query

I have variable $page in my PHP page and in a query I want to use this like:

$query = mysqli_query($con, "SELECT * FROM third LIMIT (3*($page-1)),3");
//right here I want to this math but it gives me error.

I tried it in that way too

$query = mysqli_query($con, "SELECT * FROM third LIMIT (3*{$page-1}),3");

It gave me that message:

syntax error, unexpected '-', expecting '}'

How should do this math in SQL?

Upvotes: 2

Views: 182

Answers (2)

Andy Lester
Andy Lester

Reputation: 93636

Please note that your problem is not one of SQL, but of how PHP interpolates strings.

Your problem is that PHP will interpolate variables into strings, but not expressions.

You can do this as suggested above:

$query = mysqli_query($con, "SELECT * FROM third LIMIT " . (3*($page-1)) . ",3");

Or you could do this:

$limit = 3*($page-1);
$query = mysqli_query($con, "SELECT * FROM third LIMIT $limit,3");

Upvotes: 1

Menno
Menno

Reputation: 12621

$query = mysqli_query($con, "SELECT * FROM third LIMIT " . (3*($page-1)) . ",3");

Just calculate the value in PHP and concatenate :)

Upvotes: 5

Related Questions