Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * String store, using sqlite & PDO to store and search your strings.
- */
- class string_store{
- private $db;
- function __construct($dsn,$setup_query){
- $this->dsn = $dsn;
- $this->setup = $setup_query;
- $this->chkSetup();
- }
- /**
- * Connect
- */
- public function connect(){
- try{
- if (!$this->db instanceof PDO){
- $this->db = new PDO($this->dsn);
- $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- $this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
- $this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
- }
- }catch (Exception $e){
- die($e->getMessage());
- }
- }
- /**
- * Search store for matching words
- *
- * @param string $string
- * @return array
- */
- public function search($string){
- $this->connect();
- $words = explode(' ',$string);
- $sql = "SELECT * FROM strings WHERE ";
- $w = array();
- foreach($words as $word){
- $w[] = '%'.$word.'%';
- $sql .= "string LIKE ? OR ";
- }
- $sql = rtrim($sql,'OR ');
- $statement = $this->db->prepare($sql);
- $statement->execute($w);
- return $statement->fetchAll(PDO::FETCH_ASSOC);
- }
- /**
- * Insert strings into the store
- *
- * @param array $values
- */
- public function insert($values){
- $this->connect();
- $fieldnames = array_keys($values[0]);
- $fields = '('.implode(' ,',$fieldnames).')';
- $bounds = '(:'.implode(', :',$fieldnames).')';
- $sql = "INSERT INTO strings {$fields} VALUES {$bounds}";
- $statement = $this->db->prepare($sql);
- foreach($values as $vals){
- $statement->execute($vals);
- }
- }
- /**
- * Setup and Create table for store
- */
- function chkSetup(){
- $dso = explode(':',$this->dsn);
- if(file_exists($dso[1])){
- return;
- }else{
- $this->connect();
- //Setup Table
- if(is_array($this->setup)){
- foreach($this->setup as $table){
- $this->db->query($table);
- }
- }else{
- $this->db->query($this->setup);
- }
- exit(header("refresh:0;url=./"));
- }
- }
- }//End Class
- ?>
- <?php
- include('./string_store.php');
- $string_store_table = array("CREATE TABLE strings ( id INTEGER PRIMARY KEY,
- string TEXT);");
- $string_store = new string_store("sqlite:./strings.db", $string_store_table);
- /* Insert your strings into the store
- $listofsearhches = array(array('string'=>'Java programmer is a good boy'),
- array('string'=>'he plays ball at times'),
- array('string'=>'java and dogs hate each other'),
- array('string'=>'dogs are not java programmers'),
- );
- $string_store->insert('strings',$listofsearhches);
- */
- $search = "Java programmer"; //GET INPUT FROM USER
- $result = $string_store->search($search);
- print_r($result);
- /* Result
- Array
- (
- [0] => Array
- (
- [id] => 1
- [string] => Java programmer is a good boy
- )
- [1] => Array
- (
- [id] => 3
- [string] => java and dogs hate each other
- )
- [2] => Array
- (
- [id] => 4
- [string] => dogs are not java programmers
- )
- )
- */
- ?>
Add Comment
Please, Sign In to add comment