无法在查询中使用变量

Baffled here: I am looking at a bunch of code written in PHP4 but running under PHP5 - the code (abridged) looks like:

$pid=(int)$customer_exists['pid'];//this value comes from an earlier query & does exist

$query2 = mysql_query("SELECT * FROM `products` AS p, `products_description` AS pd WHERE pd.products_id=p.products_id AND p.products_id='".(int)$pid." '"   );

This gets no result from the database. If the first line is changed to $pid=28; or if the query is changed to just search one table then we get a result.

Echo out $pid before and after the query will echo the value assigned in line 1

(have tried many versions of the actual $query2 - all get the same non-result)

What am I missing here?

Can you try changing this

AND p.products_id='".(int)$pid." '" 

to

AND p.products_id='".(int)$pid."'" 

theres a space after double quote and before single quote which you don't need. Also, you don't need (int) here as you already do it in the previous line.

Let me know if it works.

There are two points to improve here:

  1. mysql_* functions are deprecated of PHP 5.3 and will be removed soon, so don't use them. Use mysqli_* or PDO instead.
  2. This is a perfect code for SQL-injection (and that's bad). Better use prepared statements.

Example for PDO:

$pid=(int)$customer_exists['pid'];
$conn = new PDO($dsn, $user, $pass);
$stmt = $conn->prepare("`SELECT * FROM `products` AS p, `products_description` AS pd WHERE pd.products_id=p.products_id AND p.products_id='?'");
$result = $stmt->query(array($pid)); //note an array here
//Iterating
foreach ($result->fetchAll() as $row){
    //do what you need here
}

See http://www.php.net/manual/en/pdo.construct.php for explanation PDO constructor parameters.

As stated by Wbdvlpr there is an extra space:

In addition, you don't need to concatenate the string anymore if the statement is enclosed with double qoutes:

$query2 = mysql_query("SELECT * FROM `products` AS p, `products_description` AS pd WHERE pd.products_id=p.products_id AND p.products_id='$pid'");