0

I have the following code which puts data into a mysql database:

$sql3 = "INSERT INTO $tableName (topic, title, date) VALUES ('$topic','$title','$today')";
mysql_query($sql3);

It works perfectly.

However, when I use the code within a function, it doesn't work. The parameters passed into the function are used elsewhere in the code and should not affect the operation of the code above.

When I add:

if(mysql_errno()){     
echo "MySQL error ".mysql_errno().": "          
.mysql_error()."\n<br>When executing <br>\n$query\n<br>"; }

I get the error:

MySQL error 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 '(topic, title, date) VALUES ('weather','It looks like Autumn is he' at line 1 When executing

I can't figure out why there is an SQL syntax error when the code is used in a function but not when it is on its own.

Thanks for you help in advance.

  • 1
    First: Be aware that this code is extremely vulnerable if those variables are user inputs. Second: Post the full function. – aurbano Oct 20 '13 at 13:27
  • post the full code please – Nimrod007 Oct 20 '13 at 13:28
  • [You should not use mysql_* functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) – Guillaume Poussel Oct 20 '13 at 13:29
  • 1
    Your variable `$tableName` is probably empty, and possibly because it is out of scope in your function (can't tell without seeing the whole thing). Turn on error reporting and you will probably see PHP complaining about it. Always in development: `error_reporting(E_ALL); ini_set('display_errors', 1);` – Michael Berkowski Oct 20 '13 at 13:29
  • http://php.net/manual/en/language.variables.scope.php – Pekka Oct 20 '13 at 13:30

1 Answers1

0

Your issue is most likely to do with variable scope. For example:

$myVar = "Hello!";

// Outputs Hello!

echo $myVar;

function sayHello() {
    // $myVar is no longer in scope because we are "inside" the function.
    echo $myVar;
}

// undefined variable $myVar
sayHello();

When you execute your query within a function the variable $tablename is no longer in scope therefore your query becomes:

INSERT INTO (topic, title, date) VALUES ('$topic','$title','$today')

Which is obviously invalid.

Either pass $tableName to your function, hard code it into the query or use global. However, the use of global variables is not a great idea.

Tomdarkness
  • 3,800
  • 2
  • 21
  • 26