phadam phadam - 28 days ago 5
MySQL Question

Why is the text ignored by Mysql?

I have a problem with my php code! The problem lies in $_GET['id']. As you can see, I output the resultset of a user that matched with the user id.

The Question is, why do I get the same result (resultset of user with id 1) when I enter two different values on the url?

URL 1
URL 2

Shouldn't the text(randomtext) be taken in consideration, because the code seems to ignore it.

<?php

try {
$db = new PDO('mysql:host=127.0.0.1;dbname=ptp', 'root', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {

}
$id = $_GET['id'];
$sql = "SELECT * FROM users WHERE id = :id";

echo $id . '<br/>';

$query = $db->prepare($sql);

$query->bindParam(':id', $id);
$query->execute();


while($r = $query->fetch(PDO::FETCH_ASSOC)) {
print_r($r);
}

?>

Answer

Just like PHP, MySQL will cast the string "1random" to int 1. So if your id field is a number, the query will be seen as "SELECT * FROM users WHERE id = 1" even if there is some random text after the 1

just try this in PHP : var_dump('1dfg' == 1) it will return true. it's the same in MySQL.

However, if you try to find a user with id "dfg1", nothing will be returned because this string can't be casted as an int.