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();
Related
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.
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:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I know this question is sort of dumb but I can't find out where the problem is I checked it with the codes in documentation and similar codes in stackoverflow but I can't figure out the problem.
this is my code:
if (isset($_POST['buy'])) {
$id = (int) $_POST['id'];
$name = $_POST['name'];
$price = (int) $_POST['price'];
date_default_timezone_set("Europe/London");
$date = date("Y-m-d h:i:sa");
$insquery = "INSERT INTO `purchases` (file_id, file_name, price, date) VALUES ({$id}, '{$name}', {$price}, {$date})";
$insResult = mysqli_query($con, $insquery);
if ($insResult) {
//do sth
} else {
//do sth else
}
I have tested these:
1- the post array is not empty and returns exactly those that I assigned to variables.
2- I have a table called purchases and it configured properly because I insert data in SQL and get it back successfully.
3- I have tried on SQL statement without {} around SQL variables but no luck.
and another question is after the SQL statement done how can I use the OUTPUT Inserted.ID as a variable in PHP?
thanks in advance.
date is a keyword in MySql. So use backtick (`).
INSERT INTO purchases (`file_id`, `file_name`, `price`,
`date`) ...
Instead of using direct substitution values, you could use below methods to avoid sql injection.
Using MySQLi (for MySQL):
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
Please refer How can I prevent SQL-injection in PHP?
Use mysqli::$insert_id for last inserted ID (Docs here)
i used this code
<?php
$conn = new PDO("mysql:host=localhost;dbname=CU4726629",'CU4726629','CU4726629');
$sql="INSERT INTO review (username, movie_name, ratings) VALUES ("$_POST['username']","$_POST['moviename']","$_POST['ratings']")";
header('Location: reviews.php');
?>
but it keeps giving me this error
Parse error: syntax error, unexpected T_VARIABLE in
/home/4726629/public_html/check_login.php on line 5
Take this for an example:
<?php
// insert some data using a prepared statement
$stmt = $dbh->prepare("insert into test (name, value) values (:name, :value)");
// bind php variables to the named placeholders in the query
// they are both strings that will not be more than 64 chars long
$stmt->bindParam(':name', $name, PDO_PARAM_STR, 64);
$stmt->bindParam(':value', $value, PDO_PARAM_STR, 64);
// insert a record
$name = 'Foo';
$value = 'Bar';
$stmt->execute();
// and another
$name = 'Fu';
$value = 'Ba';
$stmt->execute();
// more if you like, but we're done
$stmt = null;
?>
You just wrote a string in your above code:
$sql="INSERT INTO review (username, movie_name, ratings) VALUES ("$_POST['username']","$_POST['moviename']","$_POST['ratings']")";
Above answers are correct, you will need to concat the strings to form a valid sql query. you can echo your $sql variable to check what is to be executed and if is valid sql query or not. you might want to look in to escaping variables you will be using in your sql queries else your app will be vulnerable to sql injections attacks.
look in to
http://php.net/manual/en/pdo.quote.php
http://www.php.net/manual/en/pdo.prepare.php
Also you will need to query you prepared sql statement.
look in to http://www.php.net/manual/en/pdo.query.php
A couple of errors:
1) you have to concat the strings!
like this:
$sql="INSERT INTO review (username, movie_name, ratings)
VALUES (".$_POST['username'].",".$_POST['moviename'].",".$_POST['ratings'].")";
2) you are not using the PDO at all:
after you create the "insert" string you must query the db itself, something like using
$conn->query($sql);
nb: it is pseudocode
3) the main problem is that this approach is wrong.
constructing the queries in this way lead to many security problems.
Eg: what if I put "moviename" as "; drop table review;" ??? It will destroy your db.
So my advice is to use prepared statement:
$sql="INSERT INTO review (username, movie_name, ratings)
VALUES (?,?,?)";
$q = $conn->prepare($sql);
$fill_array = array($_POST['username'], $_POST['moviename'], $_POST['ratings']);
$q->execute($fill_array);
You forgot dots:
$sql="INSERT INTO review (username, movie_name, ratings)
VALUES (".$_POST['username'].",".$_POST['moviename'].",".$_POST['ratings'].")";
and fot the future for now your variables are not escaped so code is not secure
String in a SQL-Statment need ', only integer or float don't need this.
$sql="INSERT INTO review (username, movie_name, ratings) VALUES ('".$_POST['username']."','".$_POST['moviename']."','".$_POST['ratings']."')";
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.