我试图从行记录号为 9 的列中进行选择。这似乎是一项简单的任务,但我无法弄清楚。 这是我迄今为止尝试过的:
SELECT * FROM posts WHERE category = 9 LIMIT 3
还有这个
SELECT * FROM posts WHERE category LIKE '%9%' LIMIT 3
还有一些,但没有返回正确的结果。
更新:
在表帖子
中我有
post_id
....
category
类别具有值1
、2
等。
我只想在网站上显示类别列中值为 9 的帖子 category=9
更新2:
这是帖子表
CREATE TABLE IF NOT EXISTS `posts` (
`post_id` int(11) NOT NULL AUTO_INCREMENT,
`post_title` varchar(250) NOT NULL,
`post_text` longtext NOT NULL,
`post_author` varchar(20) NOT NULL,
`category` int(4) NOT NULL,
PRIMARY KEY (`post_id`),
KEY `category` (`category`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=13 ;
ALTER TABLE `posts`
ADD CONSTRAINT `posts_ibfk_1` FOREIGN KEY (`category`) REFERENCES `category` (`cat_id`);
例如数据
INSERT INTO `posts` (`post_id`, `post_title`, `post_text`, `post_author`, `category`) VALUES
(1, 'title', 'LOREM IPSUM', 'Athor', 1),
更新3:我尝试使用的完整代码
require_once 'misc/database.inc.php';
$pdo = Database::connect();
error_reporting(E_ALL);
ini_set('display_errors', 1);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function truncate($text, $chars = 180) {
$text = $text." ";
$text = substr($text,0,$chars);
$text = substr($text,0,strrpos($text,' '));
$text = $text." ...";
return $text;
}
$query2 = $pdo->query("SELECT * FROM posts WHERE category = '7' LIMIT 3");
foreach ($query2 as $row) {
echo '<li class="col-md-12 col-sm-4">
<div class="single-post">
<h4>'.$post['post_title'].'</h4>
<p>'.truncate($row['post_text']).'</p>
<a href="#" style="float: right;"> More -></a>
</div>
</li>';
}
Database::disconnect();
最佳答案
嗯,你在循环中使用 $post['post_title'] (ForEach) 尝试使用 $row->post_title
引用https://ellislab.com/codeIgniter/user-guide/database/results.html
关于mysql - 从列中选择值为 9 的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28631041/