mysql - How to escape single-quote (apostrophe) in string using php -
i have sql query this:-
$stmt = $pdo->prepare( "select * `products_keywords` `product_type` = '" . $product_type . "' ");
i don't know value in $product_type variable. now, getting men's shirt in $product_type variable causing syntax error in sql query. sure error due single quote in men's shirt value. how escape value according query? , how check if there single quote in $product_type variable , escape according query. in advance.
the answer don't need to. proper way use pdo's prepare this:
$stmt = $pdo->prepare( "select * `products_keywords` `product_type` = ?");
this whole point of using prepared statement. bind parameter follows:
$stmt->bindparam(1, $product_type)
proof,
schema:
create table `products_keywords` ( `id` int not null, `products_keywords` varchar(1000) not null, `product_type` varchar(100) not null ); insert `products_keywords` (`id`,`products_keywords`,`product_type`) values (1,'zoom lawn cut mower',"lawn mower"), (2,'stylish torso polo','men\'s shirt');
view data:
select * `products_keywords`; +----+---------------------+--------------+ | id | products_keywords | product_type | +----+---------------------+--------------+ | 1 | zoom lawn cut mower | lawn mower | | 2 | stylish torso polo | men's shirt | +----+---------------------+--------------+
php:
<?php // turn on error reporting, or wonder why nothing happening @ times error_reporting(e_all); ini_set("display_errors", 1); $servername="localhost"; $dbname="so_gibberish"; $username="nate123"; $password="opensesame1"; try { $pdo = new pdo("mysql:host=$servername;dbname=$dbname", $username, $password); $pdo->setattribute(pdo::attr_errmode, pdo::errmode_exception); $pdo->setattribute(pdo::attr_emulate_prepares, false); $product_type="men's shirt"; $stmt = $pdo->prepare("select * `products_keywords` `product_type` = ?"); $stmt->bindparam(1, $product_type); $stmt->execute(); while($row = $stmt->fetch()) { echo $row['id'].", ".$row['products_keywords'].", ".$row['product_type']."<br/>"; } } catch (pdoexception $e) { echo 'pdo problemo: ' . $e->getmessage(); // dev not production code exit(); } ?>
browser:
Comments
Post a Comment