2

Hi I am having an issue with a MySQL query not passing a string variable.

If $pass contains only numbers it works fine. When it contains letters I get the Cannot execute the query error.

Example:

$pass=123456     //works fine
$pass=z23456     //cannot execute the query
$_SESSION['id']=$pass;           //start session

if (isset($_SESSION['id'])) {

// Query database for user information.
$query = "SELECT RepName FROM RepTable WHERE RepNumber = 
".$_SESSION['id']."";
$result = mysql_query ($query) OR die ('Cannot execute the query.');
$rinfo = mysql_fetch_array ($result);
$RepInfo = $rinfo[0]; 
3
  • 2
    What type is RepNumber in the database? Commented Jun 19, 2012 at 14:27
  • 1
    A debugging tip: try OR die ("Cannot execute the query $query"); - use in development only - NEVER use it in production. This will show you that, if for example $pass="foo" your SQL statement reads SELECT RepName FROM RepTable WHERE RepNumber = foo - as you can see, foo is not a valid identifier, function or number, so will need to be quoted. Assuming that RepNumber is a string type, mgraph's answer is your solution. If RepNumber is a numeric type, then you will need to validate $pass first. Commented Jun 19, 2012 at 14:34
  • Incidentally, use of the mysql extension is discouraged; you really ought to consider using the mysqli or pdo extensions instead. See here for more information Commented Jun 19, 2012 at 14:39

2 Answers 2

5

Try :

'".$_SESSION['id']."'"

instead of :

".$_SESSION['id'].""

you can also add:

mysql_escape_string($_SESSION['id'])
Sign up to request clarification or add additional context in comments.

Comments

1

You should use prepared statements with mysql, it's safer (SQL injections for example) :

http://php.net/manual/en/pdo.prepared-statements.php

Eg:

$stmt = $dbh->prepare("SELECT RepName FROM RepTable WHERE RepNumber = ?");
$stmt->execute($_SESSION['id'])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.