简体   繁体   中英

PHP PDO MySQL strings and variables

Why does this work when using the value direct?

$stmt = $db->prepare('SELECT tablename FROM database WHERE item = :item');
$stmt->execute(array('item ' => "somevalue" ));
$result = $stmt->fetchAll();

But this one does not work when using a variable?

$itemstring = "somevalue"
$stmt = $db->prepare('SELECT tablename FROM catalogs WHERE item = :item ');
$stmt->execute(array('item ' => $itemstring));
$result = $stmt->fetchAll();

Am I missing something obvious?

This is on WAMP 2.4/MySQL

Only change is that I am using a variable instead of a string?

You are missing a semi-colon at end of first line. This should also be visible in your error log.

ALWAYS check your error log!

If you dont get errors, fix this before doing anything else.

$itemstring = "somevalue"; // <- missing semi-colon at end
$stmt = $db->prepare('SELECT tablename FROM catalogs WHERE item = :item ');
$stmt->execute(array('item ' => $itemstring));
$result = $stmt->fetchAll();

The problem was: HTML characters in my string! The string returns text but has tags like this: (bold html tags) where it was supposed to be this: string1 (粗体html标记),该标记应为:string1

i fix the issue with:

$MYFILTERVALUE= preg_replace('/<[^>]*>/', '', $_POST['stringtoget']);

This sanitizes the variable.

This is late but I'm pretty sure the syntax should be like the below. And this can help you understand a bit more about how PDO works.

https://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059

$itemstring = "somevalue"; 
$stmt = $dbcon->prepare('SELECT tablename FROM catalogs WHERE item = :item ');
$stmt->execute(array(':item' => $itemstring));<-- Colon in the identifier
$result = $stmt->fetchAll();

Or

$itemstring = "somevalue";
$query="SELECT tablename FROM catalogs WHERE item = :item";
$stmt = $dbcon->prepare($query);
$params = array(':item' => $itemstring);<-- Colon in the identifier, setting parameters.
$stmt->execute($params);
$result = $stmt->fetchAll();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM