Unable to retrieve and id from posted data - php

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

Related

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

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'];
}

Codeigniter 3 blog: echo author's name instead of id, without using an SQL Join

I am working on a basic blog application in Codeigniter 3.1.8.
I use 2 tables: authors and posts.
CREATE TABLE authors (
id int(11) NOT NULL AUTO_INCREMENT,
first_name varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
last_name varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
email varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
birthdate date NOT NULL,
added timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE posts (
id int(11) NOT NULL AUTO_INCREMENT,
author_id int(11) NOT NULL,
title varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
description varchar(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
content text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
created_at timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
The get_post method of the Posts model gets the single post data:
public function get_post($id) {
$query = $this->db->get_where('posts', array('id' => $id));
if ($query->num_rows() > 0) {
return $query->row();
}
}
Inside the Posts controller I have:
public function post($id) {
$data = $this->Static_model->get_static_data();
$this->load->model('Posts_model');
$data['post'] = $this->Posts_model->get_post($id);
if (!empty($data['post'])) {
// Overwrite the default tagline with the post title
$data['tagline'] = $data['post']->title;
$this->load->view('partials/header', $data);
$this->load->view('post');
} else {
$data['tagline'] = "Page not found";
$this->load->view('partials/header', $data);
$this->load->view('404');
}
$this->load->view('partials/footer');
}
Finally inside the post view:
<main class="content">
<h2 class="post-title display-4"><?php echo $post->title; ?></h2>
<div class="row post-meta">
<div class="left-half col-sm-9">
<span class="author">By <?php echo $post->author_id; ?></span> | <span class="date"> <?php echo $post->created_at; ?></span>
</div>
<div class="right-half col-sm-3">
<a class="comments" href="#" title="98 comments"><i class="fa fa-comments"></i> 98</a>
</div>
</div>
<div class="post-thumbnail">
<img src="http://lorempixel.com/1200/800" />
</div>
<div class="post-content">
<?php echo $post->content ?>
</div>
<?php $this->load->view("partials/comments");?>
</main>
Of course, this renders the author's id instead of his/her name, in the single post page.
Since we are talking of individual posts, I have a hunch the author's name can be echoed out, without using an SQL Join.
How can i do that, in a very Codeigniter specific way?
If joining table is not an option, then make another query inside your get_post for author's name:
public function get_post($id) {
$query = $this->db->get_where('posts', array('id' => $id));
if ($query->num_rows() > 0) {
$data = $query->row();
// run separate query for author name
$author_query = $this->db->get_where('authors', array('id' => $data->author_id));
if ($author_query->num_rows() == 1) {
$author = $author_query->row();
$data->first_name = $author->first_name;
$data->last_name = $author->last_name;
} else {
$data->first_name = 'Unknown';
$data->first_name = 'Unknown';
}
return $data;
}
}
Your database call for post data should join to the author table. Something like this should work. You can tweak to select which fields you needs, return array or object, and return different types depending on the result of the query.
public function get_post($id) {
$this->db->select('posts.id, posts.title, authors.first_name, authors.last_name');
$this->db->from('posts');
$this->db->join('comments', 'comments.id = blogs.id');
$this->db->where('id', $id);
$query = $this->db->get();
$results = $query->result_array();
return isset($result[0]) ? $result[0] : false;
}

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
";

get checked checkboxes from database

I am looknig to seek a way to get the tick boxes checked if they are assigned to the category in the database.
<?php
try{
// Selecting entire row from cat_list table
$results = $dbh->query("SELECT cat_id, cat_title FROM cat_list");
}catch(Exception $e) {
echo $e->getMessage();
die();
}
$category = $results->fetchAll(PDO::FETCH_ASSOC);
?>
<br>
<label><input type="checkbox" name="" class="selectall"/> Select all</label>
<div id="checkboxlist" >
<?php
foreach($category as $cat){
?>
<input type="checkbox" value="<?php echo $cat["cat_id"]; ?>" <?php echo ($cat['cat_id'] == 1) ? 'checked="checked"' : ''; ?> name="cat_no[]" id="box1"> <?php echo $cat["cat_title"]; ?></a><br>
<?php
}
So when I create the post I select from the available categories which are displayed as an array, the code above is taken from my edit post form so I want it retrieve the categories I assigned to it and tick the boxes.
I have 3 tables:
doc_list (Stores documents)
cat_list (Stores Categories)
cat_doc_link_table (stores the doc_id & cat_id from the previous two tables)
Here are how they are formed:
CREATE TABLE `cat_doc_link_table` (
`id` int(11) NOT NULL,
`link_cat_id` int(11) NOT NULL,
`link_doc_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE `cat_list` (
`cat_id` int(11) NOT NULL,
`cat_title` varchar(32) NOT NULL,
`cat_color` varchar(20) NOT NULL,
`cat_icon` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf16 AUTO_INCREMENT=66 ;
CREATE TABLE `doc_list` (
`doc_id` int(11) NOT NULL,
`doc_title` varchar(50) NOT NULL,
`doc_content` text NOT NULL,
`doc_created` datetime NOT NULL,
`user_id` int(11) NOT NULL,
`doc_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf16 AUTO_INCREMENT=295 ;
put the selected cat_id's in an array(). then use in_array() to check.
// query your db to return an array of cat_id's for the specified post.
$cats_array = array('123', '124', '156');
foreach($category as $cat){
// compare
if(in_array($cat['cat_id'], $cats_array)) {
// cat checked
}else{
// not checked
}
}

trying to create a 'join' statement using Zend DB Table - zend framework 2

I have a model that needs to execute a join query on 2 tables... lets call them friend_list and user_profile.
I am having a heck of a time trying to put together the zend style code to produce the proper query I need to accomplish this... below is the desired query:
SELECT friend_list.friend_id, user_profile.id, user_profile.username
FROM `friend_list`
INNER JOIN `user_profile`
ON friend_list.friend_id = user_profile.id
where user_id = 1
Here is my model_friends
<?php
//model created to add user to database, sendmail etc...
require_once 'Zend/Db/Table/Abstract.php';
class Model_Friends extends Zend_Db_Table_Abstract
{
protected $_name = "friend_list";
public function fetchFriendList($userID)
{
$accountsTable = array('up' => 'user_profile');
$select = $this->select()
->from($this->_name)
->join($accountsTable, 'up.id = friend_List.friend_id', array())
->where("up.id = ?", $userID);
$result = $this->fetchAll($select);
if ($result !== null){
echo $select;
return $result;
} else {
echo "no records found";
}
}
}
the above model produces the follow SQL statement which is NOT what I want...
SELECT `friend_list`.*
FROM `friend_list`
INNER JOIN `user_profile`
AS `up`
ON up.id = friend_List.friend_id
WHERE (up.id = '1')
adding the table structures as requested:
DROP TABLE IF EXISTS `buzz`.`friend_list`;
CREATE TABLE `buzz`.`friend_list` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`friend_id` int(11) NOT NULL,
`approved_timestamp` date NOT NULL,
`status` varchar(15) DEFAULT 'pending',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `buzz`.`user_profile`;
CREATE TABLE `buzz`.`user_profile` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`mob` varchar(50) NOT NULL DEFAULT 'no info',
`dob` varchar(50) NOT NULL DEFAULT '',
`yob` varchar(50) NOT NULL DEFAULT '',
`language` varchar(75) NOT NULL DEFAULT 'English',
`gender` varchar(25) NOT NULL DEFAULT 'no info',
`about` varchar(1000) NOT NULL DEFAULT 'no info',
`country` varchar(45) NOT NULL DEFAULT 'no info',
`username` varchar(45) NOT NULL,
PRIMARY KEY (`id`,`username`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
Try changing your Zend_Db_Select object to the following:
$select = $this->select()
->join($accountsTable, 'friend_list.friend_id = user_profile.id', array())
->where('user_profile.id = ?', $userID)
->reset('columns')
->columns(array('friend_list.friend_id', 'user_profile.id', 'user_profile.username'));
This is not an answer to the question but since i cant comment yet i will post this here. I found the following website helpful with the join examples.
github.com
the end result of my model_friends script is as follows:
<?php
//model created to add user to database, sendmail etc...
require_once 'Zend/Db/Table/Abstract.php';
class Model_Friends extends Zend_Db_Table_Abstract
{
protected $_name = "friend_list";
public function fetchFriendList($userID)
{
$select = $this->select()
->from($this)
->setIntegrityCheck(false)
->join(array('u'=>'user_profile'), 'friend_list.friend_id =u.id', array())
->columns(array('u.id', 'u.username'))
->where("friend_list.user_id = ?", $userID);
$result = $this->fetchAll($select);
if ($result !== null){
echo $select;
return $result;
} else {
echo "no records found";
}
}
}

Categories