This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 8 years ago.
I want to ask if I can prevent sql injection with this code?
<?php
$mysqli = new mysqli("localhost", "root", "", "lists");
if (isset($_POST['main'])) {
if (isset($_POST['sub'])) {
$main = $mysqli->real_escape_string($_POST["main"]);
$sub = $mysqli->real_escape_string($_POST["sub"]);
query . . . .
}
}
?>
Duplicate of: How can I prevent SQL injection in PHP?
Use prepared statements and parameterized queries.
You can do it like this:
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name=? and age=?');
$stmt->bind_param('si', $_POST['name'], $_POST['age']);
$stmt->execute();
The 'si' means string and integer, each letter to every param corresponding to every '?'.
Further info can be found here: http://www.php.net/manual/en/mysqli-stmt.bind-param.php
$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);
Regards.
Related
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 3 years ago.
I'm attempting to setup a query through php to a MySQL database. Within the query string I have placed functions and thus have used the dot (.) operator with string closures as seen below. The issue is that my query is not going through and try as i might I can't seem to make out the error. Thanks for any help in advance. :)
$query = "INSERT INTO `foo` (`ip`, `time`, `date`, `reason`) VALUES ('".strval(getUserIpAddr())."', '".$time."', '".$date."', '".$reason."')";
As you should already be aware, your code has security issues so not going to get into that. I don't see any error handling in your code, so can only assume that is why you are not seeing an error. In order to use PDO, you need the driver loaded on the server so keep that in mind. I will reiterate that you should be using prepared statements, here's an example.
$dsn = 'mysql:host=localhost;dbname=testdb';
$username = 'username';
$password = 'password';
$options = array(
// options that apply to your configuration
);
try {
$db = new PDO($dsn, $username, $password, $options);
$sql = "INSERT INTO foo (`ip`, `time`, `date`, `reason`)
VALUES (:ip, :time, :date, :reason)";
$stmt = $db->prepare($sql);
$stmt->bindValue(':ip', strval(getUserIpAddr()), PDO::PARAM_STR);
$stmt->bindValue(':time', $time, PDO::PARAM_STR);
$stmt->bindValue(':date', $date, PDO::PARAM_STR);
$stmt->bindValue(':reason', $reason, PDO::PARAM_STR);
$stmt->execute();
} catch (PDOException $e) {
echo "Exception: " . $e->getMessage();
}
This question already has answers here:
MySQLi prepared statements error reporting [duplicate]
(3 answers)
Closed 4 years ago.
I had a false redirect. But the system won't let me delete the question
I have a website with a register page. In the backend is a SQL database, but while UPDATE and SELECT work, INSERT doesn't. IT also doesn't give me any errors.
The code which makes the INSERT statement looks as follows:
$username = "peter";
$pwhash = password_hash($password, PASSWORD_DEFAULT);
$role = "publisher";
$locked = "false";
//Prepare SQL Query
$sql = "insert into user(username, password, role, locked)";
$sql .= " VALUES (?, ?, ?, ?);";
//Reuire SQL Connection
require "db_inc.php";
//Prepare stmt
$stmt = mysqli_prepare($con, $sql);
//Bind Parameters
mysqli_stmt_bind_param($stmt, 'ssss',
$username,
$pwhash,
$role,
$locked);
//Execute SQL
mysqli_stmt_execute($stmt);
mysqli_close($con);
The SQL database looks like this:
What am I doing wrong? The $con connection is correct, as it workes on the SELECT and UPDATE querys.
Have you tried capitalizing 'insert'? And try changing '$locked = "false";' to'$locked = 0';
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 5 years ago.
I'm trying to prevent sql injection in my code. so how can i rewrite this code using prepared statement.
This is my first code that work fine but open to sql injection
<?php
if(isset($_SESSION['em'])){
$eml = $_SESSION['em'];
$query = ("select id,fst,las,uid,pass,email,sts,ocp from Users where id !=0");
$res = mysqli_query($conn,$query);
if(mysqli_num_rows($res) > 0){
while($row = mysqli_fetch_assoc($res)){
$_SESSION['ids'] = $row['id'];
echo $row['fst'];
echo $row['ocp'];
echo $row['las'];
}
}
}
?>
how can i use prepared statement for the same code please
If you don't use any values in your queries you don't need prepared statements. Only if you insert some values in your where clause for example you should use it.
https://secure.php.net/manual/en/mysqli.quickstart.prepared-statements.php
here is a complete tutorial how to use it. It's not that much complicated. You have to replace your values with placeholders and then bind your param to your query. For example:
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
$stmt->execute();
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 5 years ago.
SELECT * FROM Users WHERE UserId = " + txtUserId
How do I prevent data injection?
The following code is appropriate?
$username = mysqli_real_escape_string( $GET['username'] );
mysql_query( "SELECT * FROM tbl_members WHERE username = '".$username."'");
PDO will protect you from injections http://php.net/manual/en/book.pdo.php
Use prepared statements http://php.net/manual/en/pdo.prepared-statements.php
For example:
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
$stmt->execute();
This is a secure code
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 9 years ago.
This is the error I am getting.
"Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in on line 188"
What I am trying to do is connect to the database and insert data into the table, but i can't figure out this error.
$tableName = "customer";
$nullStr = "NULL";
$SQLstring = "INSERT INTO $tableName VALUES
('".$nullstr."','".$fname."', '".$lname."','".$address."','".$state."','".$zip."', '".$phone"','".$email"')";
$result = $mysqli->query($SQLstring);
You're missing the string concatenation operator . in a couple of places.
Replace
$SQLstring = "INSERT INTO $tableName VALUES
('".$nullstr."','".$fname."', ".$lname."','".$address."','".$state."','".$zip."','".$phone"','".$email"')";
with
$SQLstring = "INSERT INTO $tableName VALUES
('".$nullStr."','".$fname."', '".$lname."','".$address."','".$state."','".$zip."','".$phone."','".$email."')";
BTW, variable names are case-sensitive. You define $nullStr then try to use $nullstr. I fixed it in the above code.
Use a prepared statement with parameter binding instead. Not only does it make this a lot cleaner, it also avoids SQL injection.
$query = "INSERT INTO $tableName VALUES (NULL, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('sssssss', $fname, $lname, $address, $state,
$zip, $phone, $email);
$stmt->execute();
You are missing some periods. Try this...
$SQLstring = "INSERT INTO $tableName VALUES ('".$nullstr."','".$fname."','".$lname."','".$address."','".$state."','".$zip."','".$phone."','".$email."')";