I'm trying to work with PDO to make my scripts more secure. I have a demo and so I set the variable to this $STH->bindParam(':ip', $ip);
, then call it like this
$DATA = $con->prepare("INSERT INTO users (ip) VALUES (':ip')");
The problem is for some reason its not entering into the database. Here's a my full code:
<?php
$host = "localhost";
$dbname = "users";
$user = "root";
$pass = "root";
try{
$con = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
catch(PDOException $e){
echo $e->getMessage();
}
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
$ip = generateRandomString().sha1($_SERVER['SERVER_ADDR']).generateRandomString();
$STH->bindParam(':ip', $ip);
$DATA = $con->prepare("INSERT INTO users (ip) VALUES (':ip')");
$DATA->execute();
?>
And yes I understand that that's not how to get the IP an so fourth, I'm just playing around with PDO and MYSQL.
you have to binfd parameter after the query not before
$DATA = $con->prepare("INSERT INTO users (ip) VALUES ( :ip )");
$DATA->bindValue(':ip', $ip , PDO::PARAM_STR); // if ip column is string
$DATA->execute();
You can bind parameters only after preparing the query, otherwise what are you binding?
$ip= generateRandomString().sha1($_SERVER['SERVER_ADDR']).generateRandomString();
$stmt= $con->prepare("INSERT INTO users (ip) VALUES (:ip)");
$stmt->bindParam(':ip', $ip);
$stmt->execute();
Unlike bindValue
, bindParam
allows you to bind before or after the variable is initialize because it uses the variable reference not the value, so you are allowed to put create $ip
after binding.
$stmt= $con->prepare("INSERT INTO users (ip) VALUES (:ip)");
$stmt->bindParam(':ip', $ip);
$ip= generateRandomString().sha1($_SERVER['SERVER_ADDR']).generateRandomString();
$stmt->execute();
both would work in this case.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.