inserting data from a form into your mysql database using php - php

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']."')";

Related

INSERT INTO doesn't work in php codes [duplicate]

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)

PHP/Mysqli insert : Cannot pass parameter 2 by reference

Thanks for helping me out.
I'm trying to do something simple : just 2 inserts in the database.
The first one works well:
$stmt = $db->prepare("INSERT INTO sessions(date, lieu, trainer) VALUES (?,?,?)");
$stmt->bind_param("sss", $date, $location, $trainer);
$stmt->execute();
$session = $stmt->insert_id;
$stmt->close();
Then, I try to do another insert: I have a table 'users' which has 4 columns : an Id, auto-incremented, a username (column called 'fullName'), a sessionId (an int) and a contactInfo (a varchar).
Here's my code for the second insert:
//var_dump($session); returns an int
$stmt = $db->prepare("INSERT INTO users(fullName, sessionId, contactInfo) VALUES (?,?,?)");
$stmt->bind_param("sis", "$username", "$session", "$contactinfo");
$stmt->execute();
$newId = $stmt->insert_id;
$stmt->close();
From what I could read from other posts, it seems that this issue comes when you try to pass a parameter that's not a parameter (e.g.:an int) but in my case it's a variable, I reuse "$session" from the first block ($session = $stmt->insert_id;)
Am I allowed to do that? What did I miss?
Thanks!
EDIT: removed the single quotes and put double quotes, but that doesn't seem to cut it. Tried to put them for both strings but not for session but it doesn't change the result.
EDIT2:following the good advice from serjoscha, I printed the query to have an idea of what it looks like:
echo "INSERT INTO users (fullName, sessionId, contactInfo) VALUES ($username,$session,$contactinfo)";
which gives me something like
INSERT INTO users (fullName, sessionId, contactInfo) VALUES (Paul Honour,56,Location Liège Belgium Email ph#ph.be +329999999)
The query only works if I put it like this:
INSERT INTO users (fullName, sessionId, contactInfo) VALUES ('Paul Honour',56,'Location Liège Belgium Email ph#ph.be +329999999')
Any idea what's wrong?
Your issue are the single quoted variables. Just remove the single quotes or use double quotes for the content of double quotes is partitial evaluated / parsed:
$a=3;
echo '$a'; // prints: $a
echo "$a"; // prints: 3
echo $a; // prints: 3 and this is just what you need
You do not need the quotes for variables, so just remove them:
$stmt->bind_param("sis", $username, $session, $contactinfo);
Found out the issue:
it was failing on "Liège", some problem with the accent. I made sure I had the same encoding on both sides, and I can finally insert!
My code now looks like:
$contactinfo = $db->real_escape_string($contactinfo);
$stmt = $db->prepare("INSERT INTO users (fullName, sessionId, contactInfo) VALUES (?,?,?)");
$stmt->bind_param("sis", $username, $session, $contactinfo);
$stmt->execute();
$userId = $stmt->insert_id;
$stmt->close();

I'm receiving an error when running this code in PHP

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.

Not inserting data to database from link

So when someone press this link, it should insert all the data from that text id to a new table but with the username who clicked it and the id of the text the user pressed.
The problem is, when a user clicks the link, it doesn't insert the data, what could be wrong?
The session works, so it must be something with the GET?
<?php
if(isset($_GET['collect'])) {
$perman = $_GET['collect'];
$username = $_SESSION['username'];
$query = $dbh->query("INSERT INTO collections (id, ad, user) VALUES ('', $perman, $username)");
echo 'Saving';
echo $perman;
header ('Refresh: 1; URL=http://localhost/de/collect.php');
}
?>
First, inserting '' for ID isn't very good (don't know if it works), don't use it (uses default), or insert NULL (uses default too, if NOT NULL).
Second, to insert values it's good practice to enquote it and use escape_string on it. I think that's your problem.
$query = $dbh->query("INSERT INTO collections (ad, user) VALUES ('" . $dbh->escape_string($perman) . "', '" . $dbh->escape_string($username) . "')");
You should be doing it like this...if you're using PDO
Much safer, with prepared statements
$sql = "INSERT INTO books (id,ad,user) VALUES (:id,:ad,:user)";
$q = $conn->prepare($sql);
$q->execute(array(':id'=>null,':ad'=>$perman,':user'=>$username));
You tagged your Question with "PDO". Are you using PDO? If yes, why are you not using bindParam() or bindValue()?
If $perman and $username are strings, you've to escape them:
$query = $dbh->query("INSERT INTO `collections` (`id`, `ad`, `user`) VALUES ('', '{$perman}', '{$username}')");
That query should work, but there are still security issues. You've to escape the values. With PDO it's very simple.
General: use http://php.net/manual/en/function.mysql-error.php
Your column "id" should be Integer and have an auto_increment. Of course some IDs are Strings, but if you're able to avoid it, avoid it!
You could print out the $_GET params by using
print_r($_GET);
Edit
Example with PDOStatement::bindValue():
$stmt = $dbh->prepare("INSERT INTO `collections` (`id`, `ad`, `user`) VALUES (:id, :ad, :user)");
$stmt->bindValue(":id", 123);
$stmt->bindValue(":ad", "ad");
$stmt->bindValue(":user", "username");
$stmt->execute();

Using one ? to contain several variables in PHP MySQLi prepared INSERT statement

Trying to get to grips with prepared statements for an INSERT query. This is supposed to add a new user to the database:
$statement = $mysqli->prepare("INSERT INTO users (email,passwordhash) VALUES (?)");
$statement->bind_param('s', "'$email','$passwordhash'");
$statement->execute();
Is it correct to use a single ? and fill it with two values in that way?
The way mysqli doing that you need to bind all the variables separately
$statement = $mysqli->prepare("INSERT INTO users (email,passwordhash) VALUES (?,?)");
$statement->bind_param('ss', $email,$passwordhash);
$statement->execute();
But if you want it your way (say, you have an array ready and want to insert it using one placeholder) you need a helper class which will translate a custom placeholder into correct SQL statement:
$data = array('email'=>$email, 'passwordhash'=>$passwordhash);
$db->query("INSERT INTO users SET ?u");
and it will be shorter than raw mysqli yet will do much more - error handling, profiling and such.
Also keep in mind that when you will have a variable number of fields to insert, mysqli will turned to be a nightmare.
In prepared statements, each ? is used to replace one value.
When executed, your query will be:
INSERT INTO users (email,passwordhash) VALUES ("'email','password'")
That's not what you want. You need to use 2 ?s, one for each value.
$statement = $mysqli->prepare("INSERT INTO users (email,passwordhash) VALUES (?,?)");
// Pass each variable as a separate parameter
$statement->bind_param('ss', $email, $passwordhash);
$statement->execute();
Should be like this.
$statement = $mysqli->prepare("INSERT INTO users (email,passwordhash) VALUES (?,?)");
$statement->bind_param('ss', $email,$passwordhash);
$statement->execute();

Categories