0

I'm trying to run the following code:

mysql_query("INSERT INTO friend_data (UID, Name) VALUES ($friendUID, $friendName)");

where $friendUID is the user ID grabbed from Facebook, and $friendName is the name of the friend grabbed from Facebook. For some reason, $friendName just won't write to MySQL. $friendUID writes fine, and so does regular text. Does anyone have an idea why, or how to get this working? Relevant code is below:

$uid = $facebook->getUser();
$friends = $facebook->api('/me/friends');
$friendUID = $value["id"];
$friendName = $value["name"];
echo $friendName;
mysql_query("INSERT INTO friend_data (UID, Name) VALUES ($friendUID, $friendName)");

Thank you!

FinalJon
  • 365
  • 2
  • 4
  • 13
  • 1
    Hi, you've got a SQL injection vulnerability there, and please consider switching to either using mysqli or PDO to access your database (the `mysql_` functions are obselete & using them is discouraged). See http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php – John Carter Feb 13 '13 at 22:46
  • Thanks - I'll take a look. I'm just trying to get this working though... – FinalJon Feb 13 '13 at 22:48

1 Answers1

2

First, you should look into using MySQLi or PDO, as the PHP MySQL extension is quite old (and now deprecated in PHP5.5)
http://www.php.net/manual/en/mysqlinfo.api.choosing.php

The issue is that you are trying to insert raw text into the SQL query, which in addition to being an injection risk, causes an invalid statement:

Desired result:

INSERT INTO friend_data (UID, Name) VALUES (1234, "Friend Name");

Actual Result:

INSERT INTO friend_data (UID, Name) VALUES (1234, Friend Name);

You need to encapsulate the name value in quotes, as well as escape the values before inserting them:

$uid = $facebook->getUser();
$friends = $facebook->api('/me/friends');
$friendUID = mysql_real_escape_string($value["id"]);
$friendName = mysql_real_escape_string($value["name"]);
mysql_query("INSERT INTO friend_data (UID, Name) VALUES ($friendUID, \"$friendName\")");
gapple
  • 3,463
  • 22
  • 27
  • Thank you! Speaking of PDO and MySQLi - eventually I need to write statements in a Java Applet. Do I need to modify those as well to be not injectable? – FinalJon Feb 13 '13 at 22:54
  • 1
    @FinalJon yes, SQL injection is an issue you need to handle regardless of language. – John Carter Feb 13 '13 at 23:11