ffritz
ffritz

Reputation: 2261

Insert POST Variable into Mysql depending on SESSION Variable

I'm trying to implement this:

$sql = "INSERT INTO users (location) WHERE social_id='".$_SESSION["FBID"]."' VALUES ('".$_POST["location"]."')";

So the Location value comes from a form, however, the WHERE is needed obviously because it needs to go into the correct row for the user. This doesn't work, maybe someone knows if hyphens are misplaced?

Upvotes: 1

Views: 139

Answers (3)

Neil Yoga Crypto
Neil Yoga Crypto

Reputation: 1035

Please always prepare your query, never use a $_POST or any other user input value directly in your query to prevent SQL injection.

SQL Injection is more dangerous then you think

If you insert $_POST["location"] = "'' -- " into @Frank Provost's code, then you will UPDATE all the rows instead of the one with the FBID session key.

Multiple queries with SQL Injection

If you have multi query enabled then you can insert $_POST["location"] = "''; DROP TABLE users -- " into @Frank Provost's code, then you will DROP the table users.

Always use prepared statements

You can take a look at my PDO implementation example on GitHub: https://github.com/maartensch/database-pdo-mysql-class-php

Example code:

$sql = "INSERT INTO yourTablename(id,name) VALUES(:id,:name)";
$userInputId = 'yourUnescapedValue';
$userInputName = 'yourUnescapedValue';
$preparedStatements = array(':id'=>$userInputId,':name'=>$userInputName);
Db::getDb()->query($sql,$preparedStatements);

Upvotes: 0

Panda
Panda

Reputation: 6896

You should escape the string before inserting it into the database to prevent MySQL injection. Assigning it to a variable would be easier.

Also, I think you are trying to update the row, use UPDATE query instead of INSERT.

$FBID = mysqli_real_escape_string($conn, $_SESSION["FBID"])
$location = mysqli_real_escape_string($conn, $_POST["location"])

$sql = "UPDATE `users` SET `location` =  '$location' WHERE `social_id`='$FBID' ";

Upvotes: 1

Frnak
Frnak

Reputation: 6802

you should have a look at this: MySQL Insert Where query

You don't want to insert, but update a record. You always insert a complete row - not a single column of an existing row. You use update for that. Therefore there is no need to use where when inserting.

Lookking at your problem it should be something like

UPDATE users SET location = $_POST["location"] where social_id = $_SESSION["FBID"]

As mentioned in the comment above you should, however still escape at least the location variable before inserting it.

Have a look at "mysql prepared statements"

Upvotes: 2

Related Questions