2013-04-26 3 views
0

Я пытаюсь написать свою новую структуру и практику своих навыков, и я хочу, чтобы выбрать статьи по имени index.php?article=the name of the articleВыбор записей по названию

Тогда я пытаюсь выбрать его

$this->db->connect(); 

    //sanitize data 
    $title = $this->db->escape($title); 

    $this->db->prepare(" 
    SELECT 
     `date`, `title`, `content`, `author` 
    FROM 
     `articles` 
    WHERE 
     `title` like '%$title%' 

    LIMIT 1 ; "); 

    //execute query 
    $this->db->query(); 
    $article = $this->db->fetch('array'); 
    return $article; 

это не работа ...

Когда я пытаюсь запустить запрос непосредственно в базе данных - это не работает (0 возвращаемых строк) (смотри ниже)

SELECT 
    `date`, `title`, `content`, `author` 
FROM 
    `articles` 
WHERE 
    `title` like '%How to generate Lorem Ipsum%'; 

образец базы данных:

SET @saved_cs_client  = @@character_set_client; 
SET character_set_client = utf8; 
CREATE TABLE `articles` (
    `id` int(11) NOT NULL auto_increment, 
    `date` varchar(25) NOT NULL, 
    `title` varchar(50) NOT NULL, 
    `content` text NOT NULL, 
    `author` varchar(100) NOT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; 
SET character_set_client = @saved_cs_client; 

LOCK TABLES `articles` WRITE; 
/*!40000 ALTER TABLE `articles` DISABLE KEYS */; 
INSERT INTO `articles` VALUES 
    (1,'Dec 12, 2008','How to generate Lorem Ipsum','Nam accumsan enim tristique urna commodo mollis. Etiam eget leo est. Donec tincidunt quam nec nulla pulvinar sed tristique lorem tincidunt. Pellentesque nibh lectus; suscipit sed ullamcorper sed, laoreet ut tortor. Morbi ut ante tellus. Integer vitae felis id justo tempor adipiscing. Curabitur eget ipsum et urna ultricies pulvinar. Fusce enim dolor, interdum eu egestas vel, iaculis eget nisl. Aenean pretium diam accumsan quam tincidunt sit amet dictum lorem scelerisque. In gravida ultricies aliquet. Phasellus porta erat vel augue sodales feugiat! Pellentesque mattis malesuada ultrices. Mauris eleifend mi quis arcu tincidunt vehicula! Nam sodales commodo lacus, et commodo metus venenatis vel. Sed mollis molestie congue. Nulla ante leo, aliquet et convallis sed; consequat sed turpis. Duis augue leo, adipiscing at venenatis eget, eleifend vitae velit! ','John Squibb'), 
    (2,'Jan 03, 1988','Using __autoload','Now in order to try out our new library and driver setup, we have to first make some changes to the way files are served in our framework. Open up the router.php file located in the controllers folder that we created in the first part of this tutorial. If we look at our __autoload function we\'ll see the code we wrote to handle the \'lazy loading\' of our models. Since we used the same naming convention for our libraries and drivers, a quick modification to this code will allow us to load those as easily.','Frank Rabbit'); 
+1

ли вам в любой точке правопреемника '$ _GET [ 'статьи']' в '$ названию '? –

+0

Он работает правильно для меня пример с жестко закодированным названием. –

+0

BTW, в коде PHP вы используете подготовленные заявления WRONG! Вы должны поместить местозаполнитель, а не реальную стоимость, а затем привязать значение к заполнителю: '$ stmt = $ db-> prepare ('SELECT foo FROM articles WHERE title =: title'); $ stmt-> bindValue (': title', $ _GET ['title']); $ stmt-> execute(); ' –

ответ

0

Собственно, ваш способ подготовки запроса не имеет смысла. Подготовить утверждения используются, когда вам нужно привязать переменные на нем. Вы можете просто нравится:

$this->db->select('date,title,content,author') 
     ->like('title',$title, 'both') 
     ->get('articles'); 

Но, если вы хотите, чтобы подготовить заявление, попробуйте следующее:

$sql = "SELECT date, title, content, author FROM articles 
     WHERE title like %?% limit 1"; 
$this->db->query($sql, array($title)); 
+0

Я дезинфицирую входные данные раньше; тем не менее у меня другая проблема: я не могу выбрать данные. Он отлично работает, если я использую идентификатор, но не буду выбирать по имени ... Я думаю, что ему, возможно, придется что-то сделать с godaddy.com (здесь я запускаю свою БД) – Andrew

+0

, как вы упомянули по вопросу о том, что запрос работает в базе данных, это также должно работать – hsuk

0

Если вы уже установили $_GET['article'] в $titles, я не вижу никаких проблем, за исключением, чем выбрать неправильный таблицу или базу данных. обратитесь к своей строке подключения и проверьте, является ли она правильной базой данных. проверьте, находитесь ли вы в локальной или удаленной базе данных.

EDIT1; возможно, изменить title like '%$title%' до title like '%".$title."%' полезно.

+0

Он работает на sqlfddle ... Я h = очень смущен ... Возможно, это проблема godaddy.com' http://sqlfiddle.com/#!2/f5edf/ 1 – Andrew