问题
if member logon they have url like index.php?id=5
$id = $_GET['id']
I can show the user data by doing this
$pdo = Database::connect();
$sql = 'SELECT * FROM data WHERE id_member = "5" ORDER BY tgl DESC';
foreach ($pdo->query($sql) as $row) {
echo '<td>'. $row['tgl'] . '</td>';
}
but if i change to this, nothing happen.
$pdo = Database::connect();
$q = $pdo->prepare('SELECT * FROM data WHERE id_member = $id ORDER BY tgl DESC');
$q->bindValue(':id', $id, PDO::PARAM_INT);
foreach ($pdo->query($q) as $row) {
echo '<td>'. $row['tgl'] . '</td>';
}
but i dont understand. can somebody help me please? give me right code and explain it please, iam new with PDO.
thanks
回答1:
In your statement you are using a prepared query, therefore your query should look different:
$q = $pdo->prepare('SELECT * FROM data WHERE id_member = :id ORDER BY tgl DESC');
You also have to execute your query after you bind the parameters, like so:
$q->execute();.
So doing this should fix your problem:
$pdo = Database::connect();
$q = $pdo->prepare('SELECT * FROM data WHERE id_member = :id ORDER BY tgl DESC');
$q->execute(['id'=>$id])
foreach ($q as $row) {
echo '<td>'. $row['tgl'] . '</td>';
}
It is generally better practice to use prepared statements as they prevent sql injection attacks.
回答2:
You don't use the query
function, http://php.net/manual/en/pdo.query.php, with prepare
, http://php.net/manual/en/pdo.prepare.php. Prepare
goes with execute
, http://php.net/manual/en/pdostatement.execute.php. You also need to put the binded name in the query.
$pdo = Database::connect();
$q = $pdo->prepare('SELECT * FROM data WHERE id_member = :id ORDER BY tgl DESC');
$q->bindValue(':id', $id, PDO::PARAM_INT);
$q->execute();
while($q->fetch(PDO::FETCH_ASSOC)) {
echo '<td>'. $row['tgl'] . '</td>';
}
or
$pdo = Database::connect();
$q = $pdo->prepare('SELECT * FROM data WHERE id_member = ? ORDER BY tgl DESC');
$q->execute(array($id));
while($q->fetch(PDO::FETCH_ASSOC)) {
echo '<td>'. $row['tgl'] . '</td>';
}
Both methods are prepared statements. They separate the user's data so it won't cause issues with your query.
Also, as the other answers have alluded to if you used double quotes your second query would have executed...but don't do that it opens you to injections. Here's how you could have done that but the prepared are better. Also note the casting of the $id
to an int which forces it to be a number.
$id = (int)$_GET['id'];
$pdo = Database::connect();
$sql = "SELECT * FROM data WHERE id_member = $id ORDER BY tgl DESC";
foreach ($pdo->query($sql) as $row) {
echo '<td>'. $row['tgl'] . '</td>';
}
回答3:
Single quotes treating variables as string in your code
$sql = 'SELECT * FROM data WHERE id_member = $id ORDER BY tgl DESC';
have to be
$sql = "SELECT * FROM data WHERE id_member = $id ORDER BY tgl DESC";
or you will recieve $id instead of it's value;
来源:https://stackoverflow.com/questions/30537864/pdo-displaying-data-from-database-foreach-specific-id