0

I have this quick question, i have got the username variable from a form and i need to insert it in a query, can you please tell me where i'm going wrong, it says: Unknown column '$username' in 'field list'

Here is the code:

echo $HTTP_POST_VARS['username'];

   echo $username;
   $query = sprintf( 'SELECT $username FROM hostess' );
4

4 回答 4

1
  1. In the code supplied you never set $username.
  2. You're wide open for Sql injection.
  3. You're using sprintf without any reason - it formats a string but you're not supplying any formatting, my example below does
  4. You're trying to 'SELECT $username FROM hostess' but that's not a valid Sql statement at all.

You'd be wanting something more like:

$query = sprintf( "SELECT * FROM hostess WHERE username='%s'", $username);

AFTER making sure you clean $username.

于 2012-06-19T22:48:41.623 回答
0
$query = sprintf( 'SELECT %s FROM hostess', $username);

-or, if that's a string value, I suspect you may want to include that in single quotes in the query text -

$query = sprintf( "SELECT '%s' FROM hostess", $username);

NOTE: The generated SQL statement looks a bit odd, in that its going to return the same literal value for every row in the hostess table. If there's a hundred rows in the hostess table, you are going to return 100 rows with the same literal value. This may be what you want, but it strikes me as VERY odd.

NOTE: The sprintf function looks for %s, %d, etc. placeholders in the first argument, and replaces them with values from the remaining arguments.)

NOTE: If $username contains a value coming in from a form, and has not been validated, to thwart SQL injection attacks, I would use the (admittedly old school) mysql_real_escape_string function. (Others will offer suggestions for better, more modern techniques to accomplish the same result.)

$query = sprintf("SELECT '%s' FROM hostess",mysql_real_escape_string($username));
于 2012-06-19T22:40:41.263 回答
0

in PHP, using the single quote for strings will not parse the string for variables. Use either concatenation or double quotes:

$query = sprintf( 'SELECT ' . $username . ' FROM hostess' );
$query = sprintf( "SELECT $username FROM hostess");

Of course, this is to say nothing about the terrible risks using a POST var this way implies.

于 2012-06-19T22:42:06.177 回答
0

Uhmm about everything seems wrong..

First of all, you never defined the variable $username. What you are doing would only be valid in a version of PHP that still supports suberglobals.

Second, why are you using sprintf for a query?

By the way, HTTP_POST_VARS is deprecated. Use POST

Correct code would be something like this;

    $username = $_POST['username'];
echo $username;

$query = mysql_query("SELECT ".$username." FROM hostess");
于 2012-06-19T22:43:31.890 回答