I try to show the videos and pictures shared by the members in one page. The query I wrote works fine but is very slow. I don't know why this happened. That's why I need your help. You can also see the conditions I wrote in the following query.
Here is the sqlFiddle
$morequery="";
if($lastpostid) {
$morequery=" AND P.user_post_id<'".$lastpostid."' ";
}
$GetAllPostQuery = mysqli_query($this->db,"SELECT
P.user_post_id,
P.user_id_fk,P.post_type,
P.who_can_see_post,
P.post_image_id,P.post_video_id,
P.post_video_name,
U.user_name, U.user_fullname,U.influencer_status
FROM user_posts P
INNER JOIN users U
ON P.user_id_fk = U.user_id
WHERE
U.user_status='1' AND
U.influencer_status = '1' AND
(P.who_can_see_post IN('everyone','influencer','friends')) AND
(P.post_type IN('image','video')) $morequery
ORDER BY
P.user_post_id
DESC LIMIT " .$this->perpage) or die(mysqli_error($this->db));
//Store the result
while($row=mysqli_fetch_array($GetAllPostQuery)) {
// Store the result into array
$data[]=$row;
}
if(!empty($data)) {
// Store the result into array
return $data;
}
The Users Table Here:
-- phpMyAdmin SQL Dump
-- version 4.8.3
-- https://www.phpmyadmin.net/
--
-- Host: localhost:8889
-- Generation Time: Sep 10, 2019 at 11:56 AM
-- Server version: 5.7.23
-- PHP Version: 7.2.10
CREATE TABLE `users` (
`user_id` int(11) NOT NULL,
`user_name` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`user_status` enum('0','1','2','3') NOT NULL DEFAULT '0',
`user_fullname` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`influencer_status` enum('0','1') NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`user_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
And The User Posts Table Here:
CREATE TABLE `user_posts` (
`user_post_id` int(11) NOT NULL,
`user_id_fk` int(11) DEFAULT NULL,
`post_type` enum('text','image','link’,’video','audio','avatar','cover','gif','location','watermark','which','page','event','blog','group','product','bfaf','inf') NOT NULL DEFAULT 'text',
`post_created_time` int(11) NOT NULL DEFAULT '1524910573',
`who_can_see_post` enum('everyone','onlyme','friends','influencer') NOT NULL DEFAULT 'everyone',
`post_video_id` varchar(255) DEFAULT NULL,
`post_video_name` varchar(255) DEFAULT NULL,
`post_audio_id` varchar(255) DEFAULT NULL,
`post_image_id` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for table `user_posts`
--
ALTER TABLE `user_posts`
ADD PRIMARY KEY (`user_post_id`),
ADD KEY `ex_posts` (`user_id_fk`);
--
-- AUTO_INCREMENT for table `user_posts`
--
ALTER TABLE `user_posts`
MODIFY `user_post_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
--
-- Constraints for table `user_posts`
--
ALTER TABLE `user_posts`
ADD CONSTRAINT `ex_posts` FOREIGN KEY (`user_id_fk`) REFERENCES `users` (`user_id`);
What should I do to make the query work faster? Can you help me.
The fiddle contains too few rows to reproduce the problem but these 2 indexes might help.it really depends on your data distribution.
ALTER TABLE users ADD KEY(user_status,influencer_status);
ALTER TABLE user_posts ADD KEY(who_can_see_post,post_type);
Related
I am trying to upload some images to my database with some data, when I do this in localhost it's all work fine. But on the server, only some queries work fine. but others are not working.
This is my database pages table and papertag table
CREATE TABLE `pages`
(
`pageId` int(10) NOT NULL,
`paperId` varchar(255) NOT NULL,
`filePath` varchar(255) NOT NULL,
`fileType` varchar(20) NOT NULL,
`status` enum('0','1') NOT NULL,
`dateAndTime` datetime NOT NULL,
`description` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `pages`
--
ALTER TABLE `pages`
ADD PRIMARY KEY (`pageId`),
ADD KEY `paperId` (`paperId`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `pages`
--
ALTER TABLE `pages`
MODIFY `pageId` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=324;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `pages`
--
ALTER TABLE `pages`
ADD CONSTRAINT `pages_ibfk_1` FOREIGN KEY (`paperId`) REFERENCES `papers` (`paperId`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;
-----paper tag------
CREATE TABLE `papertag`
(
`tagId` int(11) NOT NULL,
`paperId` varchar(255) NOT NULL,
`tagName` varchar(255) NOT NULL,
`des` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `papertag`
--
ALTER TABLE `papertag`
ADD PRIMARY KEY (`tagId`),
ADD KEY `paperId` (`paperId`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `papertag`
--
ALTER TABLE `papertag`
MODIFY `tagId` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=460;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `papertag`
--
ALTER TABLE `papertag`
ADD CONSTRAINT `papertag_ibfk_1` FOREIGN KEY (`paperId`) REFERENCES `papers` (`paperId`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;
and this is my SQL query code in PHP file
$up22 = mysqli_query($connection, "INSERT INTO papertag(`paperId`, `tagName`) VALUES ('{$paperId}', '{$nme}')");
$up = mysqli_query($connection, "INSERT INTO pages(`paperId`, `filePath`, `fileType`, `status`, `dateAndTime`) VALUES ('{$paperId}', '{$img_dir}', '{$type}',2 , '{$date}' )");
I think you have to insert all columns with not null Constraint. you did not insert des column for example.
you need this code :
$up22 = mysqli_query($connection, "INSERT INTO papertag(`paperId`, `tagName`,`des`) VALUES ('{$paperId}', '{$nme}'),'{$des}'");
I am working on a study planner. The SQL query below is supposed to run when a logged in user tries to save a study plan from the welcome page. However, the code does not do anythin. The input values just disappear upon submission with no initialisation of the $result variable, no flag changes and no any error print-outs when I run the application via NetBeans...
// Set up a flag for monitoring the individual queries
$flag = true;
$query = "UPDATE
`modulecodes`
LEFT JOIN `moduletitles` ON `moduletitles`.`modulecodeid` = `modulecodes`.`modulecodeid`
LEFT JOIN `studyplans` ON `studyplans`.`modulecodeid` = `modulecodes`.`modulecodeid`
LEFT JOIN `comments` ON `comments`.`modulecodeid` = `modulecodes`.`modulecodeid`
SET
modulecode = '$moduleCode', moduletitle = '$moduleTitle', studydate = '$moduleStudyDate', numberofstudyhours = '$moduleAllocatedHours', comment = '$studyPlanComments'
WHERE userid = '$userid';";
// Execute the query and put the result in the variable $result
$result = mysqli_query($mysqli, $query);
if (!$result) {
$flag = false;
echo $flag;
echo "Error details for Result: " . mysqli_error($mysqli) . ".";
}
...And with hard-coded values (as per below) and direct test in phpMyAdmin, it runs but comes back with 0 rows affected. (Query took 0.0069 seconds.) and no changes in the database, whatsoever. So, I feel like I haven’t structured it well. Can someone kindly guide me on how to convert the query into one with a subquery or something more efficient and reliable, please or at the least, help point out what I am doing wrong?
I'd suspect other parts of the code but the fact that a direct test in phpMyAdmin tells me, the issue is with the SQL statement, besides I have already used other parts of the code elsewhere and with another query and it runs fine.
UPDATE
`modulecodes`
LEFT JOIN `moduletitles` ON `moduletitles`.`modulecodeid` = `modulecodes`.`modulecodeid`
LEFT JOIN `studyplans` ON `studyplans`.`modulecodeid` = `modulecodes`.`modulecodeid`
LEFT JOIN `comments` ON `comments`.`modulecodeid` = `modulecodes`.`modulecodeid`
SET
modulecode = 'P00100', moduletitle = 'Java', studydate = '2017/04/10', numberofstudyhours = '1', comment = 'Java'
WHERE userid = 20;
Database Code:
CREATE TABLE `comments` (
`commentid` int(10) NOT NULL,
`modulecodeid` int(10) NOT NULL,
`comment` text,
`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `modulecodes`
--
CREATE TABLE `modulecodes` (
`modulecodeid` int(10) NOT NULL,
`userid` int(10) NOT NULL,
`modulecode` varchar(10) NOT NULL,
`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `moduletitles`
--
CREATE TABLE `moduletitles` (
`moduletitleid` int(10) NOT NULL,
`modulecodeid` int(10) NOT NULL,
`moduletitle` varchar(100) NOT NULL,
`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `studyplans`
--
CREATE TABLE `studyplans` (
`studyplan` int(10) NOT NULL,
`modulecodeid` int(10) NOT NULL,
`studydate` date NOT NULL,
`numberofstudyhours` int(10) NOT NULL,
`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`userid` int(10) NOT NULL,
`firstname` varchar(100) NOT NULL,
`lastname` varchar(100) NOT NULL,
`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
To test the relationships, see if this returns the rows you expect to be updated:
SELECT
a.`modulecode`,
b.`moduletitle`,
c.`studydate`,
c.`numberofstudyhours`,
d.`comment`
FROM `modulecodes` a
LEFT JOIN `moduletitles` b ON b.`modulecodeid` = a.`modulecodeid`
LEFT JOIN `studyplans` c ON c.`modulecodeid` = a.`modulecodeid`
LEFT JOIN `comments` d ON d.`modulecodeid` = a.`modulecodeid`
WHERE `userid` = '$userid';
If any of the columns are NULL (joined table row not found), then the update will fail.
I do not know if it's possible at all, but I have two tables, userBasic and carPlateConfidence, in carPlateConfidence I would like to insert id of userBasic where emails are matched.
$query .= "INSERT IGNORE INTO userBasic (id_uM, userNameG, userEmailG) values ((SELECT id_uM FROM userMore WHERE userEmailG='$userEmailG'),'$userNameG', '$userEmailG');";
$query .= "INSERT IGNORE INTO carPlateConfidence (emailConfid, id_uB,plateNumber, confidencePlate, plateNumberUn) values ('$userEmailG', (SELECT id_uB FROM userBasic WHERE userEmailG='(SELECT max(emailConfid) FROM carPlateConfidence)'), '$plateNumber','$confidencePlate', '$plateNumberUn');";
So if I have:
userBasic:
id_uM = 555;
userNameG = BlaBla;
userEmailG = blabla#blabla.com
And in this table I would like
carPlateConfidence:
emailConfid = blabla#blabla.com;
id_uB = 555
plateNumber = 1111
confidencePlate = 70
plateNumberUn = 2222
AND if email do not matched:
emailConfid = blabla2#blabla.com;
id_uB = NULL
plateNumber = 1111
confidencePlate = 70
plateNumberUn = 222
P>S> Currently I have tried this, to select id from userBasic:
(SELECT id_uB FROM userBasic WHERE userEmailG='(SELECT max(emailConfid) FROM carPlateConfidence)')
id_uB in carPlateConfidence is set as foreign key;
Tables:
--
-- Table structure for table `carPlateConfidence`
--
DROP TABLE IF EXISTS `carPlateConfidence`;
CREATE TABLE IF NOT EXISTS `carPlateConfidence` (
`id_cof` int(11) NOT NULL AUTO_INCREMENT,
`id_uB` int(11) NOT NULL,
`emailConfid` varchar(50) NOT NULL,
`plateNumber` varchar(10) NOT NULL,
`confidencePlate` varchar(10) DEFAULT NULL,
`plateNumberUn` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id_cof`),
KEY `id_uB` (`id_uB`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
-- --------------------------------------------------------
--
-- Table structure for table `userBasic`
--
DROP TABLE IF EXISTS `userBasic`;
CREATE TABLE IF NOT EXISTS `userBasic` (
`id_uB` int(11) NOT NULL AUTO_INCREMENT,
`id_uM` int(11) NOT NULL,
`userNameG` varchar(50) NOT NULL,
`userEmailG` varchar(50) NOT NULL,
PRIMARY KEY (`id_uB`),
UNIQUE KEY `userEmailG` (`userEmailG`),
KEY `id_uM` (`id_uM`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=119 ;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `carPlateConfidence`
--
ALTER TABLE `carPlateConfidence`
ADD CONSTRAINT `carPlateConfidence_ibfk_1` FOREIGN KEY (`id_uB`) REFERENCES `userBasic` (`id_uB`);
--
-- Constraints for table `userBasic`
--
ALTER TABLE `userBasic`
ADD CONSTRAINT `userBasic_ibfk_1` FOREIGN KEY (`id_uM`) REFERENCES `userMore` (`id_uM`);
So you want an update, not an insert :
UPDATE carPlateConfidence t
SET t.id_uB = (SELECT distinct s.id_uM FROM userBasic s
WHERE s.userEmailG = t.emailConfid)
This will work only if there can be only 1 match, if there can be more then one match you should specify which one you want, if it doesn't matter, either use MAX() or limit :
UPDATE carPlateConfidence t
SET t.id_uB = (SELECT max(s.id_uM) FROM userBasic s
WHERE s.userEmailG = t.emailConfid)
I'm trying to get this MySQL code to work, but it's saying 0 rows affected.
UPDATE assessments, assessment_types
SET assessments.assessment_type_id = assessment_types.id
WHERE (assessment_types.description = "Skills Assessment" AND assessments.id = 2);
Basically I have assessment_types with id and description column, and I just have the id in the assessments.assessment_type_id
I need to update the id.
I searched and couldn't find quite what I need for this.
Thanks!
Table Data:
assessment_types
id description
1 Knowledge Assessment
2 Skill Assessment
3 Personal Information
4 Natural Skills
Table Structure:
--
-- Table structure for table `assessments`
--
CREATE TABLE IF NOT EXISTS `assessments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_bin NOT NULL,
`acronym` varchar(255) COLLATE utf8_bin NOT NULL,
`assessment_type_id` int(11) NOT NULL,
`language_id` int(11) NOT NULL,
`date_created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_updated` date NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`),
KEY `assessment_type_id` (`assessment_type_id`),
KEY `language_id` (`language_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=2385 ;
--
-- Table structure for table `assessment_types`
--
CREATE TABLE IF NOT EXISTS `assessment_types` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(255) CHARACTER SET latin1 NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=7 ;
You can try doing an explicit join of the two tables in your UPDATE statement:
UPDATE assessments a
INNER JOIN assessment_types at
ON a.assessment_type_id = at.id
SET a.assessment_type_id = at.id
WHERE (at.description = "Skills Assessment" AND a.id = 2);
Trying to track outbound clicks on advertisements, but im having troubles constructing the query to compile all the statistics for the user to view and track.
I have two tables, one to hold all of the advertisements, the other to track clicks and basic details on the user. ip address, timestamp, user agent.
I need to pull all of map_advertisements information along with Unique Clicks based on IP Address, and Total Clicks based on map_advertisements.id to be showin in a table with rows. 1 row per advertisement and two of its columns will be totalClicks and totalUniqueClicks
Aside from running three seperate queries for each advertisement is there a better way to go about this?
I am using MySQL5 PHP 5.3 and CodeIgniter 2.1
#example of an advertisements id
$aid = 13;
SELECT
*
count(acl.aid)
count(acl.DISTINCT(ip_address))
FROM
map_advertisements a
LEFT JOIN map_advertisements_click_log acl ON a.id = acl.aid
WHERE
a.id = $aid;
map_advertisements
-- ----------------------------
-- Table structure for `map_advertisements`
-- ----------------------------
DROP TABLE IF EXISTS `map_advertisements`;
CREATE TABLE `map_advertisements` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`youtube_id` varchar(255) NOT NULL,
`status` int(11) NOT NULL DEFAULT '1',
`timestamp` int(11) NOT NULL,
`type` enum('video','picture') NOT NULL DEFAULT 'video',
`filename` varchar(255) NOT NULL,
`url` varchar(255) NOT NULL,
`description` varchar(64) NOT NULL,
`title` varchar(64) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT;
map_advertisements_click_log
-- ----------------------------
-- Table structure for `map_advertisements_click_log`
-- ----------------------------
DROP TABLE IF EXISTS `map_advertisements_click_log`;
CREATE TABLE `map_advertisements_click_log` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`aid` int(11) NOT NULL,
`ip_address` varchar(15) NOT NULL DEFAULT '',
`browser` varchar(255) NOT NULL,
`timestamp` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=latin1;
A problem seems to be in your query there is no column with the name totalClicks in your table and distinct keyword is also used incorrectly. Try this:
SELECT *, count(acl.id) as totalClicks, count(DISTINCT acl.ip_address) as uniqueClicks
FROM map_advertisements a
LEFT JOIN map_advertisements_click_log acl ON a.id = acl.aid
WHERE a.id = $aid;