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();
}
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:
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)
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.
I keep receiving some variant of this error message:
Warning: PDO::exec(): SQLSTATE[42000]: Syntax error or access
violation: 1064 You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to
use near '#email.com",5,2)' at line 1 in
C:\xampp\htdocs\donations\index.php on line 31
The PHP it is referring to is this:
$db->exec("INSERT INTO donations(name, email, donation_amount, item_id) VALUES(\"" . $_POST['name'] . "\"," . $_POST['email'] . "\"," . $_POST['amount'] . "," . $_POST['radioButtons'] . ");");
Am I not escaping correctly or do I have too many quotes? Any help is appreciated!
You're already on a right track using PDO. Now the next step is to use it properly by utilizing prepared statements.
That being said your code might look something like this:
//TODO Check, validate, sanitize your input...
$name = $_POST['name'];
$email = $_POST['email'];
$donation_amount = $_POST['amount'];
$item_id = $_POST['radioButtons'];
try {
$db = new PDO('mysql:host=localhost;dbname=your_db_name', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
//Construct your query with placeholders
$sql = "INSERT INTO donations (name, email, donation_amount, item_id)
VALUES (?, ?, ?, ?, ?)";
//Prepare your query
$query = $db->prepare($sql);
//Execute it passing parameters
$query->execute(array($name, $email, $donation_amount, $item_id));
} catch (PDOException $e) {
echo "Exception: " . $e->getMessage(); //TODO better error handling
}
$query = null;
$db = null;
Further reading:
PDO tag wiki
A PDO tutorial
Are PDO prepared statements sufficient to prevent SQL injection?
Your problem is actually a problem with escaping quotes. If you would have used more standard single quotes for enclosing values in SQL statement you probably would have noticed this more easily, but you do not currently have an opening quote before your email value.
I would highly suggest use of prepared statements like this:
$query = 'INSERT INTO donations (name, email, donation_amount, item_id) VALUES (:name, :email, :amount, :radioButtons)';
$sth = $db->prepare($query);
$sth->execute(array(
':name' => $_POST['name'],
':email' => $_POST['email'],
':amount' => $_POST['amount'],
':radioButtons' => $_POST['radioButtons']
));
Of course this doesn't should proper error handling that you would also want to put in place along the way.
This prepared statement will protect you against SQL injection, and also has the benefit of making you SQL much more readable by eliminating the need for quotes.
I actually prefer to use the more verbose method of binding all the parameters rather than passing an array of values to execute. This allows you to specify the input type explicitly (i.e. integer, string, etc.). So based on the assumption that the last two values are integers taht might look like this:
$query = 'INSERT INTO donations (name, email, donation_amount, item_id) VALUES (:name, :email, :amount, :radioButtons)';
$sth = $db->prepare($query);
$sth->bindParam(':name', $_POST['name'], PDO::PARAM_STR);
$sth->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
$sth->bindParam(':amount', $_POST['amount'], PDO::PARAM_INT);
$sth->bindParam(':radioButtons', $_POST['radioButtons'], PDO::PARAM_INT);
$sth->execute();
I didn't write it this way initially, as I think that, for whatever reason, the PHP community largely gravitates towards passing the value via array to execute(). They also more commonly tend to use ? placeholders rather than named placeholders, but, to me, this is just being lazy. I mean are you really saving that much time in writing a few extra characters to sacrifice clarity of the code?
Add spaces between the field/table names and parantheses
INSERT INTO donations (name...) VALUES (...)
Also, use single quotes ' ' around values.
VALUES ( '" . $_POST['name'] . "' )
Also, never inject $POST data directly into your SQL queries. This is begging for SQL Injection. And by all means, go learn PDO/Prepared Statements and stop using mysql functionality. Its dead.
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."')";