Join column from one table to another column in other table CodeIgniter - php

I've got 2 Tables that I want some of the columns to auto update when the other one gets data from user.
Here is my scenario: User registers and his details go to "users" Table.
The registered user can now make a post. When he makes a post his post goes to "posts" table.
Now I want to display the users "username" when he/she makes a post.
So, conclusion is that I want the column "username" from table "users" to automatically synchronize with column "username" from table "posts". So that once a user makes a post, it will see that a specific user made a post.
Here's how i will implement it
<?php foreach ($posts as $post) : ?>
<div class="row">
<div class="col-md-3">
<img class="post-thumb img-fluid" src="<?php echo site_url();
?>assets/images/posts/<?php echo $post['post_image']; ?>">
</div>
<div class="col-md-9">
<h3><?php echo $post['title'];?></h3>
<small class="post-date">Posted on: <?php echo
$post['created_at']; ?>
in <strong><?php echo $post['category_name']?></strong> by
<strong><?php echo $post['username']?></strong></small><br>
<?php echo word_limiter($post['body'], 50); ?>
<br><br>
<p><a class="btn btn-info" href="<?php echo
site_url('/posts/'.$post['slug']);?>"
>Read More</a></p>
</div>
</div>
<?php endforeach; ?>
Here is a function I tried, but it doesn't update my "posts" table column "username" when I make a post.
public function get_posts($slug = FALSE){
if ($slug === FALSE){
$this->db->order_by('posts.id', 'DESC');
$this->db->join('categories', 'categories.id =
posts.category_id');
$this->db->join('users', 'users.username = posts.username');
$query = $this->db->get('posts');
return $query->result_array();
}
$query = $this->db->get_where('posts', array('slug' => $slug));
return $query->row_array();
}
Here are the DB tables
CREATE TABLE `posts` (
`id` int(11) NOT NULL,
`category_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`username` varchar(255) NOT NULL,
`posted_by` varchar(255) NOT NULL,
`title` varchar(255) NOT NULL,
`slug` varchar(255) NOT NULL,
`body` text NOT NULL,
`post_image` varchar(255) NOT NULL,
`created_at` datetime NOT NULL DEFAULT current_timestamp()
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`register_date` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
There is no error, just no result.
Any advice or help will be appreciated.
EDIT:
I've managed to make a "get_username" function. But I'm not sure why its not working and how to create a loop for it to loop through posts that have been made. Please see code below
public function get_username(){
$username = $this->db->query("
SELECT u.username AS username
FROM users u
LEFT JOIN posts p
ON u.id = p.user_id
WHERE p.id = ?"
, array('id')
)->row_array();
return $username['username'];
}
I get error saying:
A PHP Error was encountered
Severity: Notice
Message: Undefined index: username
Filename: posts/index.php
Line Number: 19

Your get_username() method takes no parameters - what if you wanted to get id of 5? or 20? Currently you have no ability to specify what id to query. The current query, results in:
LEFT JOIN posts p ON u.id = p.user_id WHERE p.id = 'id'
As it's passing a string literally called id, whereas what you actually want, is to pass a parameter with the associated ID to query.
/**
*
**/
public function get_username( int $userId )
{
$username = $this->db->query("
SELECT u.username AS username
FROM users u
LEFT JOIN posts p
ON u.id = p.user_id
WHERE p.id = ?"
, array( $userId )
)->row_array();
return $username['username'];
}

Related

How to join two tables and return result in php

I have two tables namely: users and messages
I want to JOIN messages table with users table and select users information from users table where the id in users table has NO row in messages table checking with the hash column.
Please Note: user_two column in messages table is the ids from users table
I tried but it return no result.
Please help:
<?php
//Get the friend a user wants to send message
if(isset($_POST['recipname']) && !empty($_POST['recipname'])){
$recipname = mysqli_real_escape_string($dbc_conn,htmlentities(trim($_POST['recipname'])));
$message_group_tatable = "messages";
$sql = "
SELECT users.id, users.username,users.FirstName ,
users.LastName , users.avatar ,
users.cell_group
FROM users
INNER JOIN $message_group_tatable
ON $table_name.id=$message_group_tatable.user_two
WHERE $message_group_tatable.hash = NULL
AND users.id != $message_group_tatable.user_two
AND users.username
LIKE '%$recipname%'
LIMIT 6
";
$query = mysqli_query($dbc_conn,$sql);
//die(mysqli_error($dbc_conn));
if(mysqli_num_rows($query) > 0){
while($row = mysqli_fetch_array($query)){
$name = ucfirst($row['FirstName'])." ".ucfirst($row['LastName']);
$user_id = $row['id'];
$user_name = $row['username'];
$school = $row['cell_group'];
$avatar = $row['avatar'];
?>
<div class="selectmeWrapper this">
<table class="selectme">
<tr>
<td><span class="selectmeavtspan"><img class="selectmeavatar" src="uploaded/<?php echo $avatar; ?>" /></span></td>
<td><span class="univ"><?php echo $name; ?></span></td>
</tr>
</table>
<span class="uiremovable selected" title="pro/<?php echo $user_name;?>">
<span> <img class="recipavt" src="uploaded/<?php echo $avatar; ?>" /></span>
<span class="selectedName">
<?php echo $name; ?>
<input type="hidden" autocomplete="off"
value="<?php echo $user_name ?>" />
</span>
<i class="fa fa-times"></i>
</span>
</div>
<?php
}
}else{
echo "<p class='noresult'>No Result Found.</p>";
}
}
?>
Table structure for table messages
CREATE TABLE IF NOT EXISTS `messages` (
`user_one` int(11) NOT NULL,
`user_two` int(11) NOT NULL,
`hash` int(11) DEFAULT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=54 ;
and Table structure for table users
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(64) DEFAULT NULL,
`FirstName` varchar(32) DEFAULT NULL,
`LastName` varchar(32) DEFAULT NULL,
`Email` varchar(64) DEFAULT NULL,
`Password` varchar(32) DEFAULT NULL,
`Month` varchar(6) DEFAULT NULL,
`Day` varchar(6) DEFAULT NULL,
`Year` varchar(11) DEFAULT NULL,
`Gender` varchar(6) DEFAULT NULL,
`cell_group` varchar(100) DEFAULT NULL,
`active` varchar(11) DEFAULT NULL,
`avatar` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=21 ;
You could use a not in clause
$sql = "
SELECT users.id, users.username,users.FirstName ,
users.LastName , users.avatar ,
users.cell_group
FROM users
WHERE users.id not in (select distinct user_two from " . $message_group_tatable . " )
AND users.username
LIKE concat('%', ". $recipname .", '%')
LIMIT 6
";

How to create a function and pass a variable to it using a custom php MVC

Im working with a custom PHP MVC application
I retrieved a list of posts using this method:
MODELs: videos_model.php
class Index_Model extends Model {
public function fetchVideos(){
$stmt = $this->db->prepare("SELECT * FROM bv_videos");
$stmt->setFetchMode(PDO::FETCH_OBJ);
return $stmt->fetchAll();
}
}
CONTROLLERs :
video.php
class Index extends Controller {
public function index(){
$this->view->render('../../public/templates/header');
$this->view->Videos = $this->model->fetchVideos();
$this->view->render('index/index');
$this->view->render('../../public/templates/footer');
}
}
Views :
<div class="entry-header video_frame_description">
<h3><?php echo $value->title; ?></h3>
<p class="pull-left post-info">
<span class="cat-links hidden-xs">
<a href="<?php echo URL; ?>?cat=<?php echo $value->cat_id; ?>">
Category:
** HERE I WANT TO ADD CATEGORY NAME UNDER EACH POST **
</a>
</p>
</div>
In the view, I want to show the name of the video category under each post.
I created this function in the index class
public function get_video_category($cat_id){
$stmt = $this->db->prepare("SELECT * FROM bv_categories WHERE cat_id=?");
$stmt->execute(array($cat_id));
$stmt->setFetchMode(PDO::FETCH_OBJ);
$data = $stmt->fetch();
return $data->category;
}
And then in the Controller I added this line:
$this->view->video_category = $this->model->get_video_category();
And here the problem. What parameter should I pass the get_video_category() function??
Here are the tables structure im using:
bv_videos
CREATE TABLE IF NOT EXISTS bv_videos (
video_id int(11) NOT NULL AUTO_INCREMENT,
title varchar(255) NOT NULL,
url text NOT NULL,
cat_id int(11) NOT NULL,
date_added int(11) NOT NULL,
status int(11) NOT NULL,
PRIMARY KEY (video_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=14 ;
bv_categories
CREATE TABLE IF NOT EXISTS bv_categories (
cat_id int(11) NOT NULL AUTO_INCREMENT,
category varchar(100) NOT NULL,
order_cat int(11) NOT NULL DEFAULT '100',
PRIMARY KEY (cat_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ;
I would extend this query
"SELECT * FROM bv_videos"
to
SELECT v.*, c.category as category_name FROM bv_videos v, bv_categories c WHERE v.cat_id = b.cat_id and v.cat_id = " . $cat_id;
or using left join
and then in view would just call category same way as you use category id
<a href="<?php echo URL; ?>?cat=<?php echo $value->cat_id; ?>">
Category name is: $value->category_name;
Your way:
$this->view->video_category = $this->model->get_video_category();
you need to enter category id, which seems to be $value->cat_id; if you are calling from view

Unable to retrieve and id from posted data

I am trying to add comments on a joke thread, but I am having trouble grabbing the joke_id which should be used to amend the comments on the post.
The problem i face is, the thread with no comments on will not add the joke_id to the database, and the thread with comments on works fine. I have no idea why.
This is a working example of what I am talking about:
http://ehustudent.co.uk/cis21732825/cis3122/jokehut_4/read/joke/14
This thread is fully working (i just emphasised the joke_id for test purposes)
and this thread does not work:
http://ehustudent.co.uk/cis21732825/cis3122/jokehut_4/read/joke/4
The comment and name is added to the database, but the joke_id is down as '0' and i have no idea why.
Here is my code in the view:
<?php
//assigning values
foreach($results as $row){
$name = $row->name;
$joke = $row->joke;
$joke_id = $row->joke_id;
$date_added = $row->date_added;
$vote = $row->vote;
?>
}
echo form_open('comments/insertComment');
?>
<div class="new-com-bt">
<span>Write a comment ...</span>
</div>
<div class="new-com-cnt">
<input type="text" id="name-com" name="name-com" value="" placeholder="Name is optional" />
<textarea required="yes" class="the-new-com" id="the-new-com" name="the-new-com" placeholder="Write your comment here..."></textarea>
<input type="hidden" name="joke_id" value="<?= $joke_id; ?>">
<input class="bt-add-com" type="submit" value="Post comment">
<div class="bt-cancel-com">Cancel</div>
</div>
<div class="clear"></div>
<?php
echo form_close(); ?>
Here is my controller:
public function index(){
$this->getComment();
}
public function getComment(){
$data['results'] = $this->comments_m->getComments();
$this->load->view('template/header');
$this->load->view('template/sidebar');
$this->load->view('content/comment_box', $data);
$this->load->view('template/footer');
}
public function insertComment(){
$data = array (
'user' => 'user',
'comment' => 'comment',
'joke_id' => 'joke_id',
'id_post' => 'joke_id'
);
$joke_id = $this->input->post('joke_id');
$this->comments_m->insertComment($data);
redirect(base_url('read/joke/'.$joke_id));
}
}
model:
//gets the comments
function getComments ($joke_id){
$query = $this->db->query("SELECT c.name, j.*, co.* FROM jokes j LEFT JOIN category c ON c.category_id = j.category_id LEFT JOIN comments co ON co.joke_id = j.joke_id WHERE j.joke_id = '$joke_id' ") or die("No results found" );
if ($query->num_rows > 0) {
return $query->result();
}
}
//inserts the comments
function insertComment (){
$data = array (
'user' => $this->input->post('name-com'),
'comment' => $this->input->post('the-new-com'),
'joke_id' => $this->input->post('joke_id'),
'id_post' => $this->input->post('joke_id')
);
if(strlen($data['user']) < 1){
$data['user'] = "Guest";
}
$this->db->insert('comments', $data);
}
comments table:
CREATE TABLE IF NOT EXISTS `comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user` varchar(40) NOT NULL,
`comment` text NOT NULL,
`joke_id` int(11) NOT NULL,
`id_post` int(11) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
jokes table:
CREATE TABLE IF NOT EXISTS `jokes` (
`joke_id` int(11) NOT NULL AUTO_INCREMENT,
`joke` varchar(1024) NOT NULL,
`category_id` int(11) NOT NULL,
`vote` int(255) NOT NULL,
`date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`joke_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Any help as to why the joke_id doesn't insert/show on pages with no jokes would be great.
Thank you

MySql - three sucessfully joined tables, but failing to get one column result?

I have three tables (user, post, comments) joined up (for an ajax powered social network thing I am doing for a degree).
So far so good but when I loop through them I am getting all the results except one. The reference to who commented on a post (stored within comments table) is coming up only as a number id (which should be joined to the user table but my join is obviously not working correctly!).
Any help very much appreciated! Probably something simple as I am still new at this PHP/mysql game!
MySQL tables:
CREATE TABLE `post` (
`pid` int(10) NOT NULL AUTO_INCREMENT,
`uid` int(10) NOT NULL,
`post` text NOT NULL,
`pid_imageurl` varchar(100) NOT NULL,
`likes` int(10) NOT NULL,
PRIMARY KEY (`pid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5
CREATE TABLE `user` (
`uid` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`password` varchar(20) NOT NULL,
`uid_imageurl` varchar(100) NOT NULL,
`joindate` varchar(11) NOT NULL,
PRIMARY KEY (`uid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
CREATE TABLE `comments` (
`cid` int(10) NOT NULL AUTO_INCREMENT,
`comment_pid` int(10) NOT NULL,
`comment_uid` int(10) NOT NULL,
`comment` text NOT NULL,
PRIMARY KEY (`cid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
Code:
$sql = "SELECT post.post, post.pid_imageurl, post.likes, user.name, comments.comment,
user.uid_imageurl, comments.comment_uid
FROM post
INNER JOIN user
ON post.uid=user.uid
LEFT JOIN comments
ON comments.comment_pid=post.pid
AND user.uid=comments.comment_uid
";
$result = mysql_query($sql);
while($row=mysql_fetch_assoc($result)){?>
<ul>
<li>User Profile image here:<? echo $row['uid_imageurl']; ?></li>
<li>Post:<? echo $row['post']; ?></li>
<li>Post by:<? echo $row['name']; ?></li>
<li>Post images:<? echo $row['pid_imageurl']; ?></li>
<li>post has: <? echo $row['likes']; ?> likes.</li>
<li><? echo $row['comment']; ?></li>
<li>by: <? echo $row['comment_uid']; ?></li>
<!--This is only output as a stored id no rather than users name--!>
</ul>
<?}
?>
First, your query should be this:
SELECT
p.post,
p.pid_imageurl,
p.likes,
u.name,
c.comment,
u.uid_imageurl,
cu.name as CommentName
FROM
post p
INNER JOIN user u ON
p.uid=u.uid
LEFT JOIN comments c ON
c.comment_pid=post.pid
left join user cu on
c.comment_uid = cu.uid
And $row['comment_uid'] should become $row['CommentName'].
Your original query is only grabbing comments that the original poster has made (your join condition). You want to join to the user table yet again to get the comment poster rather than the original poster.

Get number of posts in a topic PHP

How do I get to display the number of posts on a topic like a forum. I used this... (how very noobish):
function numberofposts($n)
{
$sql = "SELECT * FROM posts
WHERE topic_id = '" . $n . "'";
$result = mysql_query($sql) or die(mysql_error());
$count = mysql_num_rows($result);
echo number_format($count);
}
The while loop of listing topics:
<?php
$sql = "SELECT * FROM topics ORDER BY topic_id ASC LIMIT $start, $limit";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
?>
<div class="topics">
<div class="topic-name">
<p><?php echo $row['topic_title']; ?></p>
</div>
<div class="topic-posts">
<p><?php echo numberofposts($row['topic_id']); ?></p>
</div>
</div>
<?php
}
?>
Although it is a bad method of doing this... All I need is to know what would be the best method, don't just point me out to a website, do it here, because I'm trying to learn much. Okay? :D
Thanks.
EDIT:
SQL:
Posts table:
CREATE TABLE `posts` (
`post_id` mediumint(8) NOT NULL AUTO_INCREMENT,
`topic_id` mediumint(8) NOT NULL,
`forum_id` mediumint(8) NOT NULL,
`user_id` mediumint(8) NOT NULL,
`post_time` varchar(100) NOT NULL,
`post_timestamp` mediumint(20) NOT NULL,
`post_ip` varchar(20) NOT NULL,
`post_reported` tinyint(1) NOT NULL,
`post_reportdesc` text NOT NULL,
PRIMARY KEY (`post_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
--
-- Dumping data for table `posts`
--
INSERT INTO `posts` VALUES(1, 1, 0, 1, '15th Junenee', 0, '', 0, '');
Topics table:
CREATE TABLE `topics` (
`topic_id` mediumint(8) NOT NULL AUTO_INCREMENT,
`section_name` varchar(25) NOT NULL,
`topic_title` varchar(120) NOT NULL,
`topic_description` char(120) NOT NULL,
`user_id` mediumint(8) NOT NULL,
`topic_time` varchar(100) NOT NULL,
`topic_views` varchar(1000) NOT NULL,
`topic_up` mediumint(11) NOT NULL,
`topic_down` mediumint(11) NOT NULL,
`topic_status` tinyint(1) NOT NULL,
PRIMARY KEY (`topic_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
This should help you understand a bit more.
You can use:
"SELECT COUNT(topic_id) FROM posts WHERE topic_id = '?'"
The ? is a place-holder. If you use mysql, you should use mysql_real_escape_string:
$sql = "SELECT COUNT(topic_id)
WHERE topic_id = '" . mysql_real_escape_string($n) . "'";
If you use mysql_fetch_array, $row[0] will be the count. You can name it but it's not necessary.
A better option is some kind of prepared statements, such as PDOStatement or mysqli_stmt. This helps prevent SQL injection.
When you're listing topics, you should include the post count in a join:
SELECT t.*, COUNT(p.post_id) AS post_count
FROM topic t LEFT JOIN posts p ON p.topic = t.topic_id
GROUP BY t.topic_id
Didn't study your schema too much, but you get the point.
You could use this SQL query instead if you only want the number of records:
SELECT COUNT(topic_id) AS 'count' WHERE topic_id = '123'
Then after you do:
$result = mysql_query($sql);
if ($result !== false)
{
$row = mysql_fetch_assoc($result);
if ($row !== false)
echo('Number of rows = ' . $row['count']);
}
SELECT topic_title, COUNT(*) AS toipic_count
FROM topics
GROUP BY topic_id
ORDER BY topic_id ASC
Then you will not need any more mysql-querys, just use:
$row['topic_count']

Categories