I'm using unity to pass values to my php script with HTTP GET. I am new to php and just got my script to work, however, I would like to make sure I can protect against SQL Injection. Can someone please look this over and let me know what I need to change in order to protect it?
<?php
$servername = "localhost";
$username = "Test";
$password = "Test";
$dbname = "Test";
$userId = $_GET['userId'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT rp FROM RP where userID = '$userId'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//echo "UserID: " . $row["userID"]. " - RP: " . $row["rp"]."<br>";
echo "RP: " . $row["rp"]."<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
To prevent sql injections - use prepared statements. Here's the link: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
UPDATED
Example:
$id = 5;
$c = new mysqli($servername, $username, $password, $dbname);
$s = $c->prepare("SELECT * FROM RP WHERE id = ?");
$s->bind_param('s', $id);
$s->execute();
$r = $s->get_result();
$f = $r->fetch_assoc();
echo $f['rp'];
UPDATED
Example #2:
$id = 5;
$rp = "lalala";
$rp2 = "boomboomboom";
$c = new mysqli($servername, $username, $password, $dbname);
$s = $c->prepare("UPDATE RP SET rp = ?, rp2 = ? WHERE userID = ?");
$s->bind_param('sss', $rp, $rp2, $id);
$s->execute();
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments