David suci
David suci

Reputation: 3

How to join variable with string in query?

I don't know why it did not work. i think it should work. if i change the $page in query with 0. it worked. instead use variable. it did not work.

PHP

$page = 0;

$query = $sql = "SELECT `Id`, `Title`, `Genre`, `Images`, `Url`, `Width`, `Height` FROM `contents` LIMIT 10 OFFSET '".$page."'";

Upvotes: 0

Views: 59

Answers (3)

Jack O'Neill
Jack O'Neill

Reputation: 1081

if you are using page from an parameter, consider using prepared statements for security considerations.

PHP Prepared Statements

$page = 0;
$conn = new mysqli($servername, $username, $password, $dbname);

// prepare and bind
$stmt = $conn->prepare("SELECT `Id`, `Title`, `Genre`, `Images`, `Url`, `Width`, `Height` FROM `contents` LIMIT 10 OFFSET ?");
$stmt->bind_param("i", $page);

just write your sql statements in the prepared Statement and assign afterwards your params with $stmt->bind_param.

With this, php will automatically check if the variable holds the right datatype and will prevent your code from being vunerable by sql injection.

Upvotes: 1

Martijn
Martijn

Reputation: 16123

As other mentioned, you're using your $page as a string. Most of the times PHP is forgiving, but youyr now making a query,m those are not so flexible.

Because of your quotes, your code results in this:

OFFSET '0' // See the quotes?
OFFSET 0 // no quotes is what you're looking for

VERY simply put, you now pass it as string. You as human see number 1, but the code sees text 1, which has about the same worth as OFFSET 'a', it doesn't make sense for the interpreter.


Also, if you want the first results, you don't need the offset. Also, there is a shorthand version of waht you have:

LIMIT 10,25

This will give you 10 items, with an offset of 25.

Upvotes: 0

Dacaspex
Dacaspex

Reputation: 679

Your $page is a number, so you should do:

$sql = "SELECT `Id`, `Title`, `Genre`, `Images`, `Url`, `Width`, `Height` FROM `contents` LIMIT 10 OFFSET ". $page;

Upvotes: 1

Related Questions