Multiple mysql query in CI - php

There I have some multiple query and want to execute in Codeigniter.
Below are the code I tried.
function seememberfilter($course,$n)
{
$this->load->database();
$sql = array();
$sql[] = "CREATE TEMPORARY TABLE temp1";
$sql[] = "select id,rand, name,lname, email,phone from `member` where course like ('%$course%')";
$sql[] = "CREATE TEMPORARY table temp2";
$sql[] = "select distinct t.id,t.rand, t.name,t.lname, t.email,t.phone, a.quest_id from temp1 t left join assignment a on t.rand= a.rand";
$sql[] = "CREATE TEMPORARY table randid";
$sql[] = "select rand, quest_id from temp2 where quest_id=$n";
$sql[] = "select t.id,t.rand, t.name,t.lname, t.email,t.phone, r.quest_id from temp1 t left join randid r on t.rand= r.rand";
foreach ($sql as $sql_command)
{
if ($debugging == 0)
{
$this->db->query($sql_command);
}
elseif ($debugging == 1)
{
echo $sql_command;
}
}
return $query->result();
}
Above code is in model and below code is in Controller
public function assign(){
$this->load->model("user_model");
$course=$this->input->post('course');
$n=$this->input->post('id');
$data['sel'] = $this->user_model->seememberfilter($course,$n);
$this->load->view('assign',$data);
}
mysql query are executing well in phpmyadmin. I checked it
What I want: I want to execute mysql query in CI successfully .
I am editing this and giving you sql table complete details
DROP TABLE IF EXISTS `member`;
CREATE TABLE IF NOT EXISTS `member` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`rand` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`lname` varchar(255) NOT NULL,
`phone` varchar(255) NOT NULL,
`dob` varchar(255) NOT NULL,
`course` text NOT NULL,
`gender` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
`city` varchar(255) NOT NULL,
`state` varchar(255) NOT NULL,
`zip` varchar(255) NOT NULL,
`comment` text NOT NULL,
`Aboutme` text NOT NULL,
`dat` varchar(255) NOT NULL,
`tim` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
INSERT INTO `member` (`id`, `rand`, `email`, `name`, `lname`, `phone`, `dob`, `course`, `gender`, `address`, `city`, `state`, `zip`, `comment`, `Aboutme`, `dat`, `tim`) VALUES
(1, 'jrf20180961828', 'kk122344545#hotmail.com', 'Kishan', 'Yadav', '9717111111', '2018-09-01', 'paper first,Political Science,Philosophy,', 'male', 'Diamond Auto Mobiles', 'Belthara road', 'ballia', '221715', 'Good person.', '', '06-09-2018', '11:24:16pm'),
(2, 'jrf20180914721', 'kk1#gmail.com', 'Rohan', 'Yadav', '9717111111', '2018-09-01', 'paper first,Philosophy,History,', 'male', 'Diamond Auto Mobiles', 'Belthara road', 'ballia', '221715', 'Good Person.', '', '06-09-2018', '11:25:44pm'),
(5, 'jrf20180958284', 'ykishan94612121#gmail.com', 'kiran', 'Singh', '9717111111', '2018-07-07', 'paper first,Political Science,History,', 'female', 'Diamond Auto Mobiles', 'Belthara road', 'ballia', '221715', 'nnbmnm', '', '10-09-2018', '10:11:34pm'),
(4, 'jrf20180932851', 'kk12#gmail.com', 'Pankaj', 'Yadav', '9717111111', '2018-09-01', 'paper first,Philosophy,Psychology,History,', 'male', 'Diamond Auto Mobiles', 'Belthara road', 'ballia', '221715', 'nmbmbn', '', '10-09-2018', '10:10:19pm'),
(6, 'jrf20180929250', 'hjh#gmail.com', 'John', 'Corter', '9717111111', '2018-09-06', 'paper first,History,', 'male', 'Diamond Auto Mobiles', 'Belthara road', 'ballia', '221715', 'sxs', '', '11-09-2018', '12:09:49am');
COMMIT;
And second table is
DROP TABLE IF EXISTS `assignment`;
CREATE TABLE IF NOT EXISTS `assignment` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`rand` varchar(255) NOT NULL,
`course` varchar(255) NOT NULL,
`quest_id` varchar(255) NOT NULL,
`time` varchar(255) NOT NULL,
`date` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
INSERT INTO `assignment` (`id`, `rand`, `course`, `quest_id`, `time`, `date`) VALUES
(1, 'jrf20180914721', 'paper first', '2', '10:05:48pm', '2018-09-10'),
(2, 'jrf20180961828', 'paper first', '2', '10:06:49pm', '10-09-2018'),
(3, 'jrf20180914721', 'History', '2', '10:08:03pm', '10-09-2018'),
(4, 'jrf20180958284', 'History', '2', '10:12:05pm', '10-09-2018'),
(5, 'jrf20180914721', 'paper first', '1', '10:19:23pm', '10-09-2018'),
(6, 'jrf20180932851', 'History', '3', '12:07:48am', '11-09-2018');
COMMIT;
And my output should be kind of this, I join two table to get this output.
Attached pic of my output
I get this output using above query. Sorry for my english.

After chat in db-fiddle:
select distinct t.id, t.rand, name, lname, email, phone, if(quest_id='2','2',NULL) as quest-id
from `member` t
left join assignment a on t.rand= a.rand
where t.course like '%History%'
and (a.course like '%History%') or a.id is null
Member constrained to course, assignment same course, quest(ion)_id 2 displayed if it was found, otherwise leave the field as NULL.

You can use transaction to separate Query execution
$this->db->trans_start();
$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->query('AND YET ANOTHER QUERY...');
$this->db->trans_complete();

Related

How to select all available rooms that are outside the interval choosen by the customer for check-in and check-out?

ROOM TABLE
CREATE TABLE `room` (
`id` int(11) NOT NULL,
`price` double NOT NULL,
`type` varchar(255) NOT NULL,
`photo` varchar(255) NOT NULL,
`max_capacity` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `room` (`id`, `price`, `type`, `photo`, `max_capacity`) VALUES (1, 25, 'Suite', 'something.jpg', 3);
INSERT INTO `room` (`id`, `price`, `type`, `photo`, `max_capacity`) VALUES (2, 20, 'Single', 'something.jpg', 1);
INSERT INTO `room` (`id`, `price`, `type`, `photo`, `max_capacity`) VALUES (3, 250, 'Family Suite', 'something.jpg', 8);
INSERT INTO `room` (`id`, `price`, `type`, `photo`, `max_capacity`) VALUES (4, 20, 'Twin', 'something.jpg', 2);
INSERT INTO `room` (`id`, `price`, `type`, `photo`, `max_capacity`) VALUES (5, 20, 'Twin', 'something.jpg', 2);
INSERT INTO `room` (`id`, `price`, `type`, `photo`, `max_capacity`) VALUES (6, 25, 'Suite', 'something.jpg', 3);
ALTER TABLE `room`
ADD PRIMARY KEY (`id`);
ORDERS TABLE
CREATE TABLE `orders` (
`id` int(11) NOT NULL,
`checkin` date NOT NULL,
`checkout` date NOT NULL,
`id_user` int(11) NOT NULL,
`id_room` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `orders` (`id`, `checkin`, `checkout`, `id_user`, `id_room`) VALUES
(1, '2023-01-12', '2023-01-13', 1, 1),
(2, '2023-01-11', '2023-01-15', 1, 2);
ALTER TABLE `orders`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
COMMIT;
I tried the following:
SELECT id,type FROM room WHERE (SELECT \* FROM orders WHERE (2023-01-12 NOT BETWEEN `checkin` AND `checkout`) AND (2023-01-13 NOT BETWEEN `checkin` AND `checkout`));
I expect to get all the room with id (2-6) and the id = 1 to not be showed if the reservation is made in the interval of 12.01.2023(checkin choosen by client x) and 13.01.2023(checkout choosen by client x).
I would appreciate your help alot! THANK YOU!
Try this
SELECT id, type
FROM room
WHERE id NOT IN (
SELECT id_room
FROM orders
WHERE checkin >= '2023-01-12' AND checkout <= '2023-01-13'
);

Empty results on LEFT JOIN in Codeigniter

So I'm trying to find users from my database that don't have ANY rows in another table for the previous month, although it looks like my query is correct; I'm getting empty results?
public function __construct() {
parent::__construct();
//Set Payment Dates
$this->dates = array('1st', '8th', '15th', '25th');
//Which Month do the figures need submitting as
$this->monthPrev = date('F Y', strtotime(date('F Y')." -1 month"));
$this->currentMonth = date('F Y', strtotime('this month'));
}
public function getUnreportedQuarterlies()
{
$this->db->select('quarterly_figures.month, quarterly_figures.centre, users.name, users.email');
$this->db->from('quarterly_figures');
$this->db->join('users', 'users.name = quarterly_figures.centre', 'left');
$this->db->where("quarterly_figures.month", $this->monthPrev);
$this->db->where("quarterly_figures.centre IS NULL");
return $this->db->get()->result();
}
My database rows look something like so:
users
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`name` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
`password` varchar(45) DEFAULT NULL,
`address` varchar(45) DEFAULT NULL,
`owners_password` varchar(45) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `users` (`id`, `name`, `email`, `password`, `address`, `owners_password`) VALUES
(1, 'Aldridge', 'aldridge#website.co.uk', 'password', '127.0.0.1', 'password');
quarterly_figures
CREATE TABLE `quarterly_figures` (
`id` int(11) NOT NULL,
`centre` varchar(45) DEFAULT NULL,
`month` varchar(45) DEFAULT NULL,
`date` date DEFAULT NULL,
`direct_debits` varchar(45) DEFAULT NULL,
`money_paid` varchar(45) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `quarterly_figures` (`id`, `centre`, `month`, `date`, `direct_debits`, `money_paid`) VALUES
(1, 'Rugby', 'January 2019', '2019-01-01', '128', '3519.00');
The 'user' table has no relation with the 'quarterly_figures' table , If there is no relation returned data is not possible. you can insert an users.id into 'quarterly_figures' for each input.

How to get one result from a table and several from another with the same catID?

Im trying to build a forum of a kind i dont know. Just fooling around with some code.
And now i got two tables, the first with the forum categories and the second with forum boards.
My question now is, can i use LEFT JOIN or any join to take one of each from the categories table and all the result with the same catID from boards?
This is my right now none working code:
$query = $_database->query("
SELECT boards.name AS boardName, boards.info, boards.category, boards.boardID, boards.sort, boards.topics, boards.posts,
categories.catID, categories.name AS catName, categories.sort
FROM ".PREFIX."forum_boards AS boards LEFT JOIN ".PREFIX."forum_categories AS categories ON boards.category = categories.catID GROUP BY categories.catID ORDER BY boards.boardID");
while ($rad = $query->fetch_array()) {
echo '<h2>'.$rad['catName'].'</h2>';
echo $rad['boardName'];
}
Got a request to post my table structure and here it is
Boards:
CREATE TABLE IF NOT EXISTS `mm_forum_boards` (
`boardID` int(11) NOT NULL,
`category` int(11) NOT NULL DEFAULT '0',
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`info` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`sort` int(2) NOT NULL DEFAULT '0',
`topics` int(11) NOT NULL DEFAULT '0',
`posts` int(11) NOT NULL DEFAULT '0'
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Categories:
CREATE TABLE IF NOT EXISTS `mm_forum_categories` (
`catID` int(11) NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`info` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`sort` int(11) NOT NULL DEFAULT '0'
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Some data:
INSERT INTO mm_forum_categories (`name`, `info`, `sort`) VALUES('Test Cat 1', 'Just giving some lorem data ^^', '1');
INSERT INTO mm_forum_categories (`name`, `info`, `sort`) VALUES('Test Cat 2', 'Just giving some lorem data ^^', '2');
INSERT INTO mm_forum_boards (`category`, `name`, `info`, sort`) VALUES('3', 'Test board 1', 'Lorem board for now', '1');
INSERT INTO mm_forum_boards (`category`, `name`, `info`, sort`) VALUES('3', 'Test board 2', 'Lorem board for now', '2');
INSERT INTO mm_forum_boards (`category`, `name`, `info`, sort`) VALUES('3', 'Test board 3', 'Lorem board for now', '3');
INSERT INTO mm_forum_boards (`category`, `name`, `info`, sort`) VALUES('4', 'Test board 4', 'Lorem board for now', '1')
The GROUP BY clause in the SQL is wrong here. It aggregeates all rows with the same category_id. This is useful when you want to count them, but not here.
When you want to order by the category, put it in the ORDER BY clause
Follow this below Query
SELECT
mm_forum_categories.name,
mm_forum_categories.info,
mm_forum_boards.name,
mm_forum_boards.info,
mm_forum_boards.sort,
mm_forum_boards.topics
FROM
mm_forum_categories
LEFT Join mm_forum_boards
ON mm_forum_categories.catID = mm_forum_boards.category
WHERE
mm_forum_categories.catID = '1'
I think it will solve your problem.
As far as I understand, you need a simple RIGHT OUTER JOIN. Have a look at this query.
SELECT mfc.name AS cat_name, mfc.catID as catID
FROM mm_forum_categories mfc
RIGHT OUTER JOIN mm_forum_boards
ON mfc.catID = mm_forum_boards.category;

php/mysql how to join three tables

I'm writing code for a school transcript system. However, I'm stuck in joining the tables which are the courses table I named 'causes', courses registered table I named 'courses_registered' and the students table 'students' actually the join works, but the problem is that data are repeated in multiples depending on how many data rows that are on the courses_registered table for example, if have 2 courses registered, I get 4 rows echoed out from all tables instead of two. so my question is, how can i join these three tables perfectly without data being repeated, when i loop through the data. this is the table structure for the three tables.
--
-- Table structure for table `courses`
--
CREATE TABLE IF NOT EXISTS `courses` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`course_code` varchar(255) NOT NULL,
`course_title` varchar(255) NOT NULL,
`cl` int(255) NOT NULL,
`level` int(255) NOT NULL,
`session` varchar(255) NOT NULL,
`semester` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `courses`
--
INSERT INTO `courses` (`id`, `course_code`, `course_title`, `cl`, `level`, `session`, `semester`) VALUES
(1, 'GSS 111', 'Use of English', 3, 1, '2009/2010', '1'),
(2, 'GSS 112', 'Nigerian History', 2, 1, '2009/2010', '1');
--
-- Table structure for table `courses_registered`
--
CREATE TABLE IF NOT EXISTS `courses_registered` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`course_id` int(255) NOT NULL,
`student_id` int(255) NOT NULL,
`score` int(255) NOT NULL,
`grade` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `courses_registered`
--
INSERT INTO `courses_registered` (`id`, `course_id`, `student_id`, `score`, `grade`) VALUES
(1, 1, 2, 60, 'B'),
(2, 2, 2, 80, 'A');
-- --------------------------------------------------------
--
-- Table structure for table `students`
--
CREATE TABLE IF NOT EXISTS `students` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`regno` varchar(255) NOT NULL,
`college` varchar(255) NOT NULL,
`dept` varchar(255) NOT NULL,
`level` varchar(255) NOT NULL,
`fname` varchar(255) NOT NULL,
`lname` varchar(255) NOT NULL,
`no_of_semesters` int(255) NOT NULL,
`gender` varchar(255) NOT NULL,
`dob` varchar(255) NOT NULL,
`age` int(255) NOT NULL,
`mstatus` varchar(255) NOT NULL,
`nationality` varchar(255) NOT NULL,
`religion` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`phone` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `students`
--
INSERT INTO `students` (`id`, `regno`, `college`, `dept`, `level`,
`fname`, `lname`, `no_of_semesters`, `gender`, `dob`, `age`,
`mstatus`, `nationality`, `religion`, `address`, `email`, `phone`)
VALUES
(2, 'MOUAU 09/14508', 'CEET', 'Electrical Electronics Engineering',
'1', 'Nnamdi', 'Okoro', 2, 'Male', '24-07-1989', 25, 'Single',
'Nigerian', 'christian', 'Okpu Umiobo road, Aba',
'nokoro#gmail.com', '09056733333');
Then this is the query
<?php
$sql = "
SELECT c.id as course_id
, c.course_code
, c.course_title
, c.cl
, c.level
, c.session
, c.semester
, r.id as rid
, r.course_id
, r.student_id
, r.score
, r.grade
, s.id
, s.regno
, s.fname
, s.lname
, s.no_of_semesters
FROM courses_registered r
JOIN courses c
ON r.course_id = course_id
JOIN students s
ON s.id = r.student_id
WHERE s.id = '$id'
";
$result = mysqli_query($con,$sql) or die ('Could not show students records.'. mysqli_error($con) );
if (mysqli_num_rows($result) > 0 ){
//echo mysqli_num_rows($result);
while($row = mysqli_fetch_array($result) ){
$score[] = $row['score'];
$course_code[] = $row['course_code'];
$course_title[] = $row['course_title'];
$cl[] = $row['cl'];
$grade[] = $row['grade'];
}
Try change this
ON r.course_id = course_id
to
ON r.course_id = c.id

Count function()

I have these two table with some data sample in them. I would like to to pull out number of classifieds in each category. I gave it a try, and I got (2) in each one which is not correct. So hopefully someone will help me with this.
CREATE TABLE IF NOT EXISTS `categories` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`name` text COLLATE utf8_unicode_ci NOT NULL,
`subcategory_id` int(2) NOT NULL DEFAULT '0',
`parent_id` int(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=27 ;
--
-- Dumping data for table `categories`
--
INSERT INTO `categories` (`id`, `name`, `subcategory_id`, `parent_id`) VALUES
(1, 'Announcements', 0, 0),
(2, 'Employment', 0, 0),
(3, 'Items For Sale', 0, 0),
(4, 'Services', 0, 0),
(5, 'Garage Sales', 0, 0),
(6, 'Automobiles', 0, 0),
(7, 'Announcement1', 1, 1),
(8, 'Announcement2', 1, 1),
--
-- Table structure for table `classifieds`
--
CREATE TABLE IF NOT EXISTS `classifieds` (
`classified_id` int(255) NOT NULL AUTO_INCREMENT,
`title` text COLLATE utf8_unicode_ci NOT NULL,
`description` text COLLATE utf8_unicode_ci NOT NULL,
`category_id` int(10) NOT NULL,
`name` text COLLATE utf8_unicode_ci NOT NULL,
`authorized` int(10) NOT NULL DEFAULT '0',
PRIMARY KEY (`adid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=177 ;
--
-- Dumping data for table `classifieds`
--
INSERT INTO `classifieds` (`classified_id`, `title`, `description`, `category_id`, `name`, `authorized`) VALUES
(1, 'Test Classified', 'Here is the First Test classified listing.', 1, 1);
INSERT INTO `classifieds` (`classified_id`, `title`, `description`, `category_id`, `name`, `authorized`) VALUES
(2, 'GMC For Sell', 'Looks like new 1979 GMC.', 6, 1);
here
$query = "SELECT category_id, COUNT(title) FROM classifieds GROUP BY category_id";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result)
$num_items_in_category = $row['COUNT(title)'];
echo "<><a href='category-".$row['id'].".php' >".$row['name'].$num_items_in_category."</a></li>";
Thanks
Change the SQL a bit, and loop through the results?
$query = "SELECT c.id, c.name,
COUNT(cl.category_id) AS num_items_in_category
FROM category_id c
LEFT JOIN aclassifieds cl ON cl.category_id=c.id
GROUP BY c.id";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo "<li><a href='category-".$row['id'].".php' >".$row['name'].$row['num_items_in_category']."</."</a></li>";
}
Just in case someone else wants to benefit my this:
enter $query = "SELECT c.id, c.name,
COUNT(cl.title) AS num_items_in_category
FROM categories c
LEFT JOIN classifieds cl ON cl.category_id=c.id
GROUP BY c.id";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo "".$row['name'].$row['num_items_in_category']."";
}
here
Thanks

Categories