OrangeTwine
OrangeTwine

Reputation: 45

T_STRING error - Trying to use PHP array in SQL where statement

I feel like I'm making a rookie error here somewhere but can't figure out what's going wrong. I am using PHP and mySQL. I have an array $users that stores a current user's information. The array is storing the customer id (cid, its an integer). So I'm trying to pull information that is only tagged to a specific customer. My code is:

try
{
    $sql = 'SELECT id, title, image_url FROM shelf WHERE cid = $user['cid']'; 
    $result = $pdo->query($sql);
}

I feel like I have similar code in other parts of my program that are working so this seems like I may be doing something wrong in terms of syntax. If I replace $user['cid'] in the request with a hard-coded number like 22, the statement works fine. However, I need to pull the integer from $user. I'm getting a T_STRING error on the SELECT statement line. I have also tried to add an additional set of single quotes around $user['cid'] but that's not working either (i.e. $user['cid'])

Thanks for your help.

Twine

Upvotes: 1

Views: 104

Answers (3)

tadman
tadman

Reputation: 211670

You're using PDO, so you should be using place-holders, too:

$stmt = $pdo->prepare('SELECT id, title, image_url FROM shelf WHERE cid=:cid');
$stmt->bindParam(':cid', $user['cid']);
$stmt->execute();

This ensures your data is escaped correctly and handles conversion to the appropriate database format where required.

Upvotes: 2

Bogdan Burym
Bogdan Burym

Reputation: 5512

$sql = 'SELECT id, title, image_url FROM shelf WHERE cid = '.intval($user['cid']);

Upvotes: -2

Maciej Sz
Maciej Sz

Reputation: 12035

Yup, rookie error. Change to double quotes and add { } around value like:

$sql = "SELECT id, title, image_url FROM shelf WHERE cid = {$user['cid']}"; 

Upvotes: 2

Related Questions