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)
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.
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();
I am trying to insert data into a database after the user clicks on a link from file one.php. So file two.php contains the following code:
$retrieve = "SELECT * FROM catalog WHERE id = '$_GET[id]'";
$results = mysqli_query($cnx, $retrieve);
$row = mysqli_fetch_assoc($results);
$count = mysqli_num_rows($results);
So the query above will get the information from the database using $_GET[id] as a reference.
After this is performed, I want to insert the information retrieved in a different table using this code:
$id = $row['id'];
$title = $row['title'];
$price = $row['price'];
$session = session_id();
if($count > 0) {
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
The first query $retrieve is working but the second $insert is not. Do you have an idea why this is happening? PS: I know I will need to sanitize and use PDO and prepared statements, but I want to test this first and it's not working and I have no idea why. Thanks for your help
You're not executing the query:
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
it needs to use mysqli_query() with the db connection just as you did for the SELECT and make sure you started the session using session_start(); seeing you're using sessions.
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
$results_insert = mysqli_query($cnx, $insert);
basically.
Plus...
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
If that still doesn't work, then MySQL may be complaining about something, so you will need to escape your data and check for errors.
http://php.net/manual/en/mysqli.error.php
Sidenote:
Use mysqli_affected_rows() to check if the INSERT was truly successful.
http://php.net/manual/en/mysqli.affected-rows.php
Here's an example of your query in PDO if you'req planning to use PDO in future.
$sql = $pdo->prepare("INSERT INTO table2 (id, title, price, session_id) VALUES(?, ?, ?, ?");
$sql->bindParam(1, $id);
$sql->bindParam(2, $title);
$sql->bindParam(3, $price);
$sql->bindParam(4, $session_id);
$sql->execute();
That's how we are more safe.
I'm wondering how to insert multiple values into a database.
Below is my idea, however nothing is being added to the database.
I return the variables above (email, serial, title) successfully. And i also connect to the database successfully.
The values just don't add to the database.
I get the values from an iOS device and send _POST them.
$email = $_POST['email'];
$serial = $_POST['serial'];
$title = $_POST['title'];
After i get the values by using the above code. I use echo to ensure they have values.
Now I try to add them to the database:
//Query Check
$assessorEmail = mysqli_query($connection, "SELECT ace_id,email_address FROM assessorID WHERE email_address = '$email'");
if (mysqli_num_rows($assessorEmail) == 0) {
echo " Its go time add it to the databse.";
//It is unqiue so add it to the database
mysqli_query($connection,"INSERT INTO assessorID (email_address, serial_code, title)
VALUES ('$email','$serial','$title')");
} else {
die(UnregisteredAssessor . ". Already Exists");
}
Any ideas ?
Since you're using mysqli, I'd instead do a prepared statement
if($stmt = mysqli_prepare($connection, "INSERT INTO assessorID (email_adress, serial_code, title) VALUES (?, ?, ?)"))
{
mysqli_stmt_bind_param($stmt, "sss", $email, $serial, $title);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
This is of course using procedural style as you did above. This will ensure it's a safe entry you're making as well.
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']."')";