0

I am trying to add data to a Mysql Database with this code:

$sql = mysql_query("UPDATE members SET name = '$name' WHERE id = '$_SESSION['username']' ");

but when I runn it I get the following error:

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)

What have I done wrong?

Darren
  • 13,050
  • 4
  • 41
  • 79
  • 3
    For starters **do not** use `mysql_` functions. they are not supported anymore and not safe. Use `PDO` *or* `mysqli_` instead. You are also fully open to `mysqli injection`, you could easily prevent that with using those other methods. In this case `'$_SESSION['username']'` this seems very incorrect. You should do something like this: `id = ".$_SESSION['username']);` Then again, **do NOT** use `mysql_` functions, as you *will* get hacked like this *and* your code will break over time. – Nytrix Feb 20 '17 at 07:08

2 Answers2

2

use like this:

mysqli_query($connection,"UPDATE members SET name = '.$name.' WHERE id = ".$_SESSION['username']);
Binod Bhandary
  • 422
  • 1
  • 5
  • 22
1

How to fix your current issue

In order to fix this, you have to fix this part: '$_SESSION['username']'. Because as you can see you are in a double string with ' (that's the best I can explain it). Therefor you need to change your query to something like this.

$sql = mysql_query("UPDATE members SET name = '$name' WHERE id = ".$_SESSION['username']);


WARNING:

You should not use mysql_ functions anymore! Why? read this question on SO about it, you really shouldn't use it anymore.


How to do mysql properly

Now, what should you use? Learn how to use PDO or mysqli_, you can learn PDO here and mysqli_ here

While you are at that, you should also learn what sql injection is, it's the next step to make your projects secure and better. Read all about that here, there are some great examples and explanations there.

Now at last, here is an example how to use mysqli:

$conn = new mysqli($servername, $username, $password, $dbname);

$stmt = $conn->prepare(UPDATE members SET name =? WHERE id =?);
$stmt->bind_param("ss", $name, $id);

$name = "Nytrix";
$id = $_SESSION['username'];
$stmt->execute();

$stmt->close();
$conn->close();

Preparing a statement like that, and binding the values in a later stage takes away the risk of sql injection aswell.

I hope this has helped you clearify a bit on the topic of mysql.

Community
  • 1
  • 1
Nytrix
  • 1,139
  • 11
  • 23