joer80 Posted May 27, 2016 Share Posted May 27, 2016 Ok, I am wanting to know the best practice for escaping a variable to prepare it for an sql insert when I am not using selectors. Its a traditional mysql query, but I want to use the same connection variables processwire uses. Without escaping it, it will throw an error out because $comment has an unescaped ' in it. What is the proper way to escape out the comment using the processwire database connection information?I tried the $comment= $this->wire('database')->quote($comment); but that doesnt seem to work. Thanks! Code: $comment = "The boat is 17' long. "; $sql= "INSERT INTO tablename (Comments) VALUES ('$comment')"; $database = $this->wire('database'); $database->exec($sql); Link to comment Share on other sites More sharing options...
joer80 Posted May 27, 2016 Author Share Posted May 27, 2016 Think I have it! It doesn't appear necessary to pass a connection. This worked: $comment = "The boat is 17' long. "; $comment = mysql_real_escape_string($comment); $sql= "INSERT INTO tablename (Comments) VALUES ('$comment')"; $database = $this->wire('database'); $database->exec($sql); Link to comment Share on other sites More sharing options...
gRegor Posted May 27, 2016 Share Posted May 27, 2016 I'd recommend using prepared statements. ProcessWire's database class extends mysqli, so you can do: $statement = $this->database->prepare('INSERT INTO tablename (Comments) VALUES (?)'); $result = $statement->execute(array($comment)); (This is written off the top of my head, not tested) 4 Link to comment Share on other sites More sharing options...
netcarver Posted May 27, 2016 Share Posted May 27, 2016 @joer80, You should be able to use the PDO prepare(), bind() and execute() methods. Here's a short example; $statement = wire()->database->prepare("INSERT INTO `tablename` (`comments`) VALUES (:comment)"); $statement->bindParam(":comment", "The boat is 17' long. "); // Defaults to binding as a string. $statement->execute(); 3 Link to comment Share on other sites More sharing options...
joer80 Posted May 27, 2016 Author Share Posted May 27, 2016 These work great! I would much rather do it this way and use pdo. This is the working code I am using: $statement = wire()->database->prepare('INSERT INTO tablename (comment) VALUES (:comment)'); $statement->bindParam(":comment", $comment); $statement->execute(); 1 Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now