Jump to content

mysql_query using form variables


eklipse

Recommended Posts

Hello,

I am new here and still getting used to proper php syntax. I am having a problem getting my code to work correctly so any suggestions or help would be greatly appreciated.

 

 

<?php
//Portion I have narrowed the problem down to.
//I am converting form values to variables using:
$table=$_POST['table_name'];
$myusername=$_POST['username'];
$mypassword=$_POST['password'];

//then attempting to place the data:
$sqli="INSERT INTO $table (username, password) VALUES('$myusername', '$mypassword')";
$resulta=mysql_query($sqli);
?>

 

The mysql_query fails.

However, if I fore go trying to connect to the table using a variable and simply enter the table name as in:

 

<?php
$sqli="INSERT INTO table_name (username, password) VALUES('$myusername', '$mypassword')";
$resulta=mysql_query($sqli);
?>

The connection works and the data is stored correctly.

I need to get the first example working so I can use the form value of table_name to tell the DB which table to connect to.

 

Any idea what I am doing wrong?

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/189554-mysql_query-using-form-variables/
Share on other sites

I'm surprised that second piece of code you inserted is working, as that should insert literally $myusername rather than that value of $myusername.  Try something like this:

 

$sqli = "INSERT INTO `" . $table . "` (username, password) VALUES ('" . $myusername . "', '" . $mypassword . "')";

 

You should look in to mysql_real_escape_string() for escaping quotes and other nastyness in your MySQL statements, especially when handling form inputs.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.