Djacksway
Djacksway

Reputation: 457

PHP MySQL query error when passing a string

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]; 

Upvotes: 2

Views: 1156

Answers (2)

mgraph
mgraph

Reputation: 15338

Try :

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

instead of :

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

you can also add:

mysql_escape_string($_SESSION['id'])

Upvotes: 5

Emmanuel Tabard
Emmanuel Tabard

Reputation: 696

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'])

Upvotes: 1

Related Questions