Here is the thing:
I have controller that retrieve data from database and pass info to view. In the view I have a loop like this:
foreach ($myphotos->result() as $myphoto){
echo $myphoto->p_id
}
But in that loop I need to pick up $myphoto->p_id and ask database to retrieve me users with this p_id.
SELECT * FROM users WHERE u_id IN (SELECT u_id FROM p_votes WHERE p_id = 268);
and in:
foreach ($myphotos->result() as $myphoto){
echo $myphoto->p_id
$this->load->model('m_member');
$users_voted = $this->m_member->getUsersVotedOnImage($myphoto->p_id);
foreach ($users_voted->result() as $users){
echo '<div id="voterfooter">voted:'.$users->name.
}
}
Ok that was one option that I come up, but there is also another option, but select statement is so complicated!
here is how:
I already have this one:
SELECT * FROM photos WHERE p_id NOT IN (SELECT distinct p_id FROM p_votes where u_id = ".$this->session->userdata('u_id').") LIMIT ".$segment_url.", ".$config['per_page'];
But how to pick up also from users people that voted on that picture and print it in view?
Here is database scheme:
CREATE TABLE IF NOT EXISTS `users` (
`u_id` int(10) unsigned NOT NULL auto_increment,
`fb_id` varchar(255),
`fb_url` varchar(255),
`email` varchar(100),
`username` varchar(100),
`name` varchar(100),
`lastname` varchar(100),
`mini_pic_fb` varchar(255),
`mini_pic` varchar(255),
`country` varchar(100),
`place` varchar(100),
`address` varchar(100),
`nr` int(10),
`postcode` varchar(10),
`pass` varchar(35),
`active` varchar(35),
`activation_code` varchar(42),
PRIMARY KEY (`u_id`),
UNIQUE KEY `email` (`email`),
UNIQUE KEY `username` (`username`),
UNIQUE KEY `fb_id` (`fb_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=229 ;
CREATE TABLE IF NOT EXISTS `photos` (
`p_id` bigint(20) unsigned NOT NULL auto_increment,
`u_id` bigint(20) unsigned NOT NULL default '0',
`p_date` datetime NOT NULL default '0000-00-00 00:00:00',
`p_content` longtext NOT NULL,
`p_title` text NOT NULL,
`p_photo` text NOT NULL,
`p_small` text NOT NULL,
`p_thumb` text NOT NULL,
`p_up` bigint(20),
`p_down` bigint(20),
PRIMARY KEY (`p_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=229 ;
CREATE TABLE IF NOT EXISTS `p_votes` (
`pv_id` bigint(20) unsigned NOT NULL auto_increment,
`u_id` bigint(20) unsigned NOT NULL,
`p_id` bigint(20) unsigned NOT NULL,
`pv_date` datetime NOT NULL default '0000-00-00 00:00:00',
`pv_ip` varchar(200) NOT NULL,
PRIMARY KEY (`pv_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=229 ;
I braked MVC pattern but I didn't know how to do this other way!
If someone knows how to do this without breaking MVC please respond!
In the view:
foreach ($myphotos->result() as $myphoto){
$query = "SELECT * FROM users WHERE u_id IN (SELECT u_id FROM p_votes WHERE p_id = ".$myphoto->p_id.")";
$voters = $this->db->query($query)->result();
echo $myphoto->p_title;
foreach($voters as $row){
echo '<div id="voterfooter">';
echo '<a href="'.base_url().'clanovi/clan/'.$row->u_id.'">';
echo $row->name.' '.$row->lastname.'</a>';
echo '</div>';
}
}
Related
I'm getting error after trying to create a table for my data base
This is my script
CREATE TABLE `users` (
`id` int PRIMARY KEY NOT NULL AUTO_INCREMENT,
`user_role_id` int NOT NULL,
`first_name` varchar(250) NOT NULL,
`last_name` varchar(250) NOT NULL,
`name` varchar(250),
`email` varchar(250) NOT NULL,
`dni_type` varchar(32) NOT NULL,
`dni` int NOT NULL,
`phone` int,
`address` varchar(250),
`city` varchar(125),
`state` varchar(125),
`country` varchar(32),
`zip` varchar(32),
`created_at` datetime,
`created_by` int,
`updated_at` datetime,
`updated_by` int,
`deleted_at` datetime,
`deleted_by` int
);
I'm getting
#1064 - Something is wrong in your syntax near 'CREATE TABLE `users` (
`id` int PRIMARY KEY NOT NULL AUTO_INCREMENT,
`u...' on line 2
Why is the error generated, and how can I avoid it in the future?
CREATE TABLE `users` (
`id` int PRIMARY KEY NOT NULL AUTO_INCREMENT
Don't use `
CREATE TABLE `users` (
id int PRIMARY KEY NOT NULL AUTO_INCREMENT
Here is my code that will display all chat message groups and messages ORDERED BY when the group was created.
I am trying to instead order the messagegroup list by the last message received instead (exactly how imessage or any text message works)
You have no messages at this time.
<div id="messagegroups">
<?php while($row_messages = mysqli_fetch_assoc($sql_messages)){ ?>
<?php
$snm = mysqli_query($connect, "SELECT * FROM message_group WHERE group_id = '$row_messages[group_id]' ORDER BY id DESC");
$rm = mysqli_fetch_assoc($snm);
$nm = mysqli_num_rows($snm);
$ur = mysqli_query($connect, "SELECT * FROM users WHERE username = '$rm[recipients]' ORDER BY id DESC;");
$rr = mysqli_fetch_assoc($ur);
$um = mysqli_query($connect, "SELECT * FROM messages WHERE group_id = '$row_messages[group_id]' ORDER BY id DESC;");
$rrr = mysqli_fetch_assoc($um);
?>
<div id="messagegroupholder">
<div class="qo cj ca js-msgGroup groupclick" id="msg" data-id="<?php echo $rm['group_id']; ?>">
<a class="b">
<div class="qf">
<span class="qj">
<img class="cu qh" src="./img/<?php echo $rr['image']; ?>" style="height: 42px; width: 42px;">
</span>
<div class="qg">
<strong><?php echo $rr['username']; ?></strong> and <strong><?php echo $nm - 1 ?> others</strong>
<div class="aof">
<?php echo substr($rrr['message'], 0, 60); ?> …
</div>
</div>
</div>
</a>
</div>
</div>
<?php } ?>
<?php } ?>
</div>
MySQL Structure:
-- --------------------------------------------------------
--
-- Table structure for table `messages`
--
CREATE TABLE IF NOT EXISTS `messages` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(100) NOT NULL,
`message` text NOT NULL,
`ipaddress` varchar(100) NOT NULL,
`timestamp` int(11) NOT NULL,
`group_id` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=318 ;
-- --------------------------------------------------------
--
-- Table structure for table `message_group`
--
CREATE TABLE IF NOT EXISTS `message_group` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(100) NOT NULL,
`recipients` varchar(255) NOT NULL,
`group_id` varchar(20) NOT NULL,
`ipaddress` varchar(100) NOT NULL,
`timestamp` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=82 ;
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
`user_level` int(11) NOT NULL DEFAULT '0',
`name` varchar(100) NOT NULL,
`image` varchar(100) NOT NULL DEFAULT 'default.png',
`profile_background` varchar(255) NOT NULL DEFAULT 'default_background.png',
`description` varchar(255) NOT NULL,
`went_to_school` varchar(100) NOT NULL,
`worked_at` varchar(100) NOT NULL,
`lives_in` varchar(100) NOT NULL,
`from_originally` varchar(100) NOT NULL,
`expires` datetime NOT NULL,
`ipaddress` varchar(50) NOT NULL,
`browser` varchar(100) NOT NULL DEFAULT 'n/a',
`show_email` int(11) NOT NULL DEFAULT '1',
`timestamp` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Here is a preview of how the data is stored: http://imgur.com/fdG2n0g
So how can I instead order the message_groups by the last message received instead of when the last group was created?
first you can do a MAX() and GROUP BY to get the latest timestamp for each group_id like
SELECT MAX(timestamp) as latestTimeStamp,group_id
FROM messages
GROUP BY group_id
Then you could call that inner query table as M having the latestTimeStamp and INNER JOIN that with message_groups like
SELECT MG.*,M.latestTimeStamp
FROM message_groups MG
INNER JOIN
(SELECT MAX(timestamp) as latestTimeStamp,group_id
FROM messages
GROUP BY group_id)as M
ON MG.group_id = M.group_id
ORDER BY M.latestTimeStamp DESC
I'm trying to convert this mysql query to active record, but the like clause not working properly and not return any output. I don't get what I missed actually.
table schema:
tbl_batch:
CREATE TABLE `tbl_batch` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Round` varchar(5) COLLATE utf8_bin NOT NULL,
`BatchID` varchar(255) COLLATE utf8_bin NOT NULL,
`TSP` varchar(10) COLLATE utf8_bin NOT NULL,
`Slot` tinyint(1) NOT NULL,
`Trade` int(11) NOT NULL,
`StartDate` date NOT NULL,
`EndDate` date NOT NULL,
PRIMARY KEY (`BatchID`),
UNIQUE KEY `ID` (`ID`),
UNIQUE KEY `BatchID` (`BatchID`),
UNIQUE KEY `BatchID_2` (`BatchID`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8 COLLATE=utf8_bin
tbl_tsp_info:
CREATE TABLE `tbl_tsp_info` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`TSP` varchar(10) NOT NULL,
`Name` varchar(50) NOT NULL,
`Email` varchar(50) NOT NULL,
`Website` varchar(50) NOT NULL,
`ContactPerson` varchar(50) NOT NULL,
`ContactPhone` varchar(11) NOT NULL,
`Phone` varchar(11) NOT NULL,
`Fax` varchar(11) NOT NULL,
`Address` varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4
tbl_instructor_info
CREATE TABLE `tbl_instructor_info` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`InstructorID` varchar(7) NOT NULL,
`Name` varchar(50) NOT NULL,
`Mobile` varchar(11) NOT NULL,
`Email` varchar(50) NOT NULL,
`Trade` int(1) NOT NULL,
`TSP` int(1) NOT NULL,
`Slot` tinyint(1) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `InstructorID` (`InstructorID`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8
MySQL Query: (Working perfectly)
SELECT BatchID
from tbl_batch
WHERE Round='7'
AND BatchID LIKE concat('%', (SELECT ShortCode FROM tbl_tsp_info WHERE id=
(SELECT TSP FROM tbl_instructor_info WHERE Email='monir.ssts#gmail.com')),'%')
Codeigniter Model:
public function get_batch_byUser($email=string) {
$this->db->select('TSP');
$this->db->from('tbl_instructor_info');
$this->db->where('email',$email);
$tsp = $this->db->get_compiled_select();
$this->db->select('ShortCode');
$this->db->from('tbl_tsp_info');
$this->db->where("`id`= ($tsp)", null, false);
$batchCode = $this->db->get_compiled_select();
$this->db->select('BatchID ');
$this->db->from('tbl_batch');
$this->db->where('round',7);
$this->db->like('BatchID', $batchCode);
$query = $this->db->get();
return $query->result();
}
I see the problem but the solution may or may not work.
Here's how to see the problem. Replace the last line of code your code return $query->result(); with
echo $this->db->get_compiled_select();
You will see
SELECT `BatchID`
FROM `tbl_batch`
WHERE `round` = 7
AND `BatchID` LIKE '%SELECT `ShortCode`\nFROM `tbl!_tsp!_info`
\nWHERE `id`= (SELECT `TSP`\nFROM `tbl!_instructor!_info`
\nWHERE `email` = \'me#example.com\')%' ESCAPE '!'
See where the wildcards characters (%) are? Not going to work.
If you change
$this->db->like('BatchID', $batchCode);
to
$this->db->like('BatchID', "($batchCode)");
The echo is this
SELECT `BatchID` FROM `tbl_batch`
WHERE `round` = 7
AND `BatchID`
LIKE '%(SELECT `ShortCode`\nFROM `tbl!_tsp!_info`
\nWHERE `id`= (SELECT `TSP`\nFROM `tbl!_instructor!_info`
\nWHERE `email` = \'me#example.com\'))%' ESCAPE '!'
I don't know if that will execute correctly - I don't have the datasets. But the syntax looks right. Right?
Sometime "Active Record" (in Codeigniter > v3.0 "Query Builder") is not the most efficient way to get what you need. Falling back to more basic methods will often be a lot less trouble.
$sql = "SELECT BatchID from tbl_batch WHERE Round='7' AND BatchID
LIKE concat('%', (SELECT ShortCode FROM tbl_tsp_info
WHERE id = (SELECT TSP FROM tbl_instructor_info
WHERE Email= ?)),'%')";
$query = $this->db->query($sql, [$email]);
return $query->result();
I'm trying to create a game database. I have already created a user table where the users, password and email are stored.
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL,
`password` char(40) DEFAULT NULL,
`email` varchar(60) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=111 DEFAULT CHARSET=utf8;
I have also created a games table where the game type, name of the game, duration, description, active and who has created the game.
CREATE TABLE `games` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`type` varchar(30) DEFAULT NULL,
`name` varchar(60) DEFAULT NULL,
`duration` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`description` varchar(255) DEFAULT NULL,
`Active` tinyint(1) DEFAULT NULL,
`Completed` tinyint(1) DEFAULT NULL,
`createdBy` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8;
The users will be able to create a game and invite x number of users, hence it will be a many-to-many relations. I have tried to create a table called active_games but I'm not sure how I should proceed. I need a connection so that I know who has created the game and who is playing that game.
CREATE TABLE `active_games` (
`user_id` int(11) NOT NULL DEFAULT '0',
`game_id` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`user_id`,`game_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
What would be the next step? If a user creates a game and sends the "invite" to other friends, is it possible to automatically assign a game ID and the users invited to the that game ID? And if I want to find all the active games for a specific user, how can I do that?
You need two more tables. UserGames would have information about users who create games:
CREATE TABLE UserGames (
UserGameId int not null auto_increment primary key,
userid int NOT NULL references users(id),
gameid int not null references games(id),
CreationDate datetime,
. . .
);
And GameInvites:
CREATE TABLE GameInvites (
GameInviteId int not null auto_increment primary key,
UserGamesId int not null references UserGames(UserGamesId),
invited_userid int NOT NULL references users(id),
AcceptedFlag bit
. . .
);
The . . . represent additional information that might want to store about each relationship.
I need to create 5-10 tables in mysql using php, but i think there is better way than the create 10 queries, so my question is, how to do this with a single query? is it psosible? Every table is different.
$sql = "CREATE TABLE IF NOT EXISTS `db_countries` (
`countrykey` int(11) NOT NULL,
`countrynamelat` varchar(500) NOT NULL default '',
PRIMARY KEY (`countrykey`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8";
mysql_query($sql);
$sql2 = "CREATE TABLE IF NOT EXISTS `db_city`(
`city_key` int(11) NOT NULL,
`city_name` varchar(500) NOT NULL,
`city_code` int(11) NOT NULL,
`city_country_key` int(11) NOT NULL,
PRIMARY KEY(`city_key`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8";
mysql_query($sql2) or die(mysql_error());
You can create a Stored Procedure that creates all your tables:
DELIMITER $$
CREATE PROCEDURE `localhost`.`sp_CreateTables` ()
BEGIN
CREATE TABLE IF NOT EXISTS `db_countries` (
`countrykey` int(11) NOT NULL,
`countrynamelat` varchar(500) NOT NULL default '',
PRIMARY KEY (`countrykey`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `db_city`(
`city_key` int(11) NOT NULL,
`city_name` varchar(500) NOT NULL,
`city_code` int(11) NOT NULL,
`city_country_key` int(11) NOT NULL,
PRIMARY KEY(`city_key`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
END
Then just call the stored procedure from PHP:
$sql = "call sp_CreateTables()";
mysql_query($sql) or die(mysql_error());