Issues getting bind_results to work in while loop - php

I am attempting to loop through my bind_results, but it is not working like I need it to. I have tried this 20 different ways and the result is always the same. I get only the first records of $survey_user_id and $survey_result to echo out.
Also when I do a COUNT like I did in my query, do I need to loop through that as well? Because as of now it is only counting 1 record when there is multiple id's for rating_draft_result.id .
try {
$survey_title_stmt = $con->prepare("SELECT COUNT(rating_draft_result.id), rating_draft_result.user_id, rating_draft_result.result
FROM rating_draft_result
INNER JOIN users ON
rating_draft_result.user_id = users.id
AND rating_draft_result.result = users.id");
if ( !$survey_title_stmt || $con->error ) {
// Check Errors for prepare
die('Survey SELECT total count prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$survey_title_stmt->execute()) {
die('Survey SELECT total count execute() failed: ' . htmlspecialchars($survey_title_stmt->error));
}
$survey_title_stmt->store_result();
} catch (Exception $e ) {
die("Survey SELECT total count: " . $e->getMessage());
}
$survey_title_stmt->bind_result($survey_id, $survey_user_id, $survey_result);
while ($survey_title_stmt->fetch()) {
$survey_id;
$survey_user_id;
$survey_result;
}
?>
<div class="survey_results_out">
<div id="survey_results_title">Survey Results</div>
<div class="survey_popup_container">
<a class="survey_popup" href="javascript:void(0)">Who drafted best results</a>
<div id="">Users that completed this survey</div><?php echo $survey_id; ?>
<div class="survey_popup_wrap light_admin">
<a class="close_survey_popup" href="javascript:void(0)">X</a>
<div id="indexpopupTitleWrap">
<div id="indexpopupTitle">Results of who drafted the best</div>
</div>
<div id="survey_results_content_wrap">
<div id="survey_results_content_usernames">
<?php
echo $survey_user_id;
echo $survey_result;
?>
My database tables look like this...
users
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`lastname` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`phone_number` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
`username` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`salt` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`joined` datetime NOT NULL,
`group` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=105 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
rating_draft_result
CREATE TABLE `rating_draft_result` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`result` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=28 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
DESIRED OUTPUT:
users id``firstname``lastname``email``phone_number``username``password``salt``joined group
1 Jack Johnson jack#email.com 2222 jackusername ffd fdddfd today 1
10 Tom Thompson fdfdfddf#fef.com 5555 Tomusername
rating_draft_result
`id` `user_id` `result`
20 1 10
I want to be able to match the rating_draft_result's user_id and result with the user table's id field.
So I want to get the jackusername and tomusername fields.

Not quite sure what it is you want for that data.
However the following might help:-
This gets the rating_draft_result.id and the 2 user names that go with it
SELECT rating_draft_result.id, u1.username, u2.username
FROM rating_draft_result
INNER JOIN users u1 ON rating_draft_result.user_id = u1.id
INNER JOIN users u2 ON rating_draft_result.result = u2.id
This gets the count of rating_draft_result.id for each pair set of usernames in the rating_draft_result table
SELECT COUNT(rating_draft_result.id), u1.username, u2.username
FROM rating_draft_result
INNER JOIN users u1 ON rating_draft_result.user_id = u1.id
INNER JOIN users u2 ON rating_draft_result.result = u2.id
GROUP BY u1.username, u2.username

Related

mySql combine two SELECT queries with JOIN

I have two mySql queries to get result from databases. I am trying to join them together.
Query 1:
SELECT userEwallets.id as ewalletId, users.id as userId , money_repositories.money as money, a.nestedUserId
FROM userEwallets
JOIN users ON users.id = userEwallets.userId
JOIN money_repositories ON userEwallets.id = money_repositories.ewalletId
WHERE ewalletNumber = 'SHIRR937303656'
Query 2:
SELECT nested.id as nestedUserId
FROM userEwallets as nested
JOIN users ON users.id = nested.userId
JOIN money_repositories ON nested.id = money_repositories.ewalletId
WHERE ewalletNumber = 'SHIRR9122331743'
and then my combination command:
SELECT userEwallets.id as ewalletId, users.id as userId , money_repositories.money as money, a.nestedUserId
FROM (
SELECT nested.id as nestedUserId
FROM userEwallets as nested
JOIN users ON users.id = nested.userId
JOIN money_repositories ON nested.id = money_repositories.ewalletId
WHERE ewalletNumber = 'SHIRR912233'
) as a
JOIN users ON users.id = userEwallets.userId
JOIN money_repositories ON userEwallets.id = money_repositories.ewalletId
WHERE ewalletNumber = 'SHIRR93730'
I get this error:
#1054 - Unknown column 'userEwallets.id' in 'field list'
Both of commands are same but they have simple difference as ewalletNumber in where clause
UPDATE WITH DATABASE STRUCTURE
money_repositories table:
CREATE TABLE IF NOT EXISTS `money_repositories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userId` int(11) NOT NULL,
`ewalletId` int(11) NOT NULL,
`money` int(11) NOT NULL,
`createdAt` int(11) NOT NULL,
`updatedAt` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_persian_ci AUTO_INCREMENT=4 ;
userEwallets table:
CREATE TABLE IF NOT EXISTS `userEwallets` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userId` int(11) NOT NULL,
`ewalletNumber` varchar(15) COLLATE utf8_persian_ci NOT NULL,
`currencySymbol` varchar(5) COLLATE utf8_persian_ci NOT NULL,
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updatedAt` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_persian_ci AUTO_INCREMENT=7 ;
users table:
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) COLLATE utf8_persian_ci NOT NULL,
`password` varchar(65) COLLATE utf8_persian_ci NOT NULL,
`name` varchar(20) COLLATE utf8_persian_ci NOT NULL,
`family` varchar(20) COLLATE utf8_persian_ci NOT NULL,
`birthDay` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
`email` varchar(20) COLLATE utf8_persian_ci NOT NULL,
`mobileNumber` varchar(15) COLLATE utf8_persian_ci NOT NULL,
`verifyCode` varchar(5) COLLATE utf8_persian_ci NOT NULL,
`photoUri` varchar(50) COLLATE utf8_persian_ci NOT NULL,
`ebanNumber` varchar(20) COLLATE utf8_persian_ci NOT NULL,
`status` tinyint(1) NOT NULL,
`createdAt` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updatedAt` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_persian_ci AUTO_INCREMENT=35 ;
userEwallets.id should be a.id in Select of your combination command. Because you are getting subquery as a.
Modified combined query;
SELECT a.id AS ewalletId,
users.id AS userId,
money_repositories.money AS money,
a.nesteduserid
FROM (SELECT nested.id AS nestedUserId,
nested.id,
nested.ewalletnumber
FROM userewallets AS nested
JOIN users
ON users.id = nested.userid
JOIN money_repositories
ON nested.id = money_repositories.ewalletid
WHERE nested.ewalletnumber = 'SHIRR912233') AS a
JOIN users
ON users.id = userewallets.userid
JOIN money_repositories
ON userewallets.id = money_repositories.ewalletid
WHERE a.ewalletnumber = 'SHIRR93730'
camleCase query fixed:
SELECT a.id AS ewalletId,
users.id AS userId,
money_repositories.money AS money,
a.nestedUserId
FROM (SELECT nested.id AS nestedUserId,
nested.id,
nested.ewalletNumber
FROM userEwallets AS nested
JOIN users ON users.id = nested.userId
JOIN money_repositories ON nested.id = money_repositories.ewalletId
WHERE nested.ewalletNumber = 'SHIRR912233') AS a
JOIN users ON users.id = nested.userId
JOIN money_repositories ON userEwallets.id = money_repositories.ewalletId
WHERE a.ewalletNumber = 'SHIRR937303'
Because you are not including table userEwallets in the query except in the sub query which won't be recognized outside the subquery. Try
UPDATE
Select
users.id as userId, userEwallets.id As ewalletId,money_repositories.money
From
users
Inner Join
userEwallets ON userEwallets.userId= users.id
Inner Join
money_repositories ON money_repositories.userId=users.id
And
money_repositories.ewalletId = userEwallets.id
Where
userEwallets.ewalletNumber = 'SHIRR93730'

Issues with SQL JOIN failing

I have the following JOIN I am attempting to create.
SELECT rating_draft_result.COUNT(id), rating_draft_result.user_id, rating_draft_result.result
FROM rating_draft_result
INNER JOIN users ON
rating_draft_result.user_id, rating_draft_result.result = users.id
I am trying to COUNT the total id's of the rating_draft_result table and then also SELECT the user_id and result from that table. Then I am trying to match the user_id and result from the rating_draft_result table to the user's id column. Then I want to get the username from the user's table where the id matches, but I can't figure that part out and I am getting an error anyways with the following code.
I get the following error..
Survey SELECT total count prepare() failed: You have an error in your
SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near '.id' at line 4
My database tables look like this...
users
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`lastname` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`phone_number` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
`username` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`salt` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`joined` datetime NOT NULL,
`group` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=105 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
rating_draft_result
CREATE TABLE `rating_draft_result` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`result` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=28 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
What am I doing wrong in my query?
DESIRED OUTPUT:
users
CREATE TABLE users (
id``firstname``lastname``email``phone_number``username``password``salt``joined group
1 Jack Johnson jack#email.com 2222 jackusername ffd fdddfd today 1
10 Tom Thompson fdfdfddf#fef.com 5555 Tomusername
rating_draft_result
`id` `user_id` `result`
20 1 10
I want to be able to match the rating_draft_result's user_id and result with the user table's id field.
So I want to get the jackusername and tomusername fields.
Check JOIN condition
SELECT rating_draft_result.user_id, rating_draft_result.result, COUNT(*)
FROM rating_draft_result
INNER JOIN users
ON rating_draft_result.user_id = users.id
GROUP BY rating_draft_result.user_id, rating_draft_result.result;
You have
ON rating_draft_result.user_id, rating_draft_result.result = users.id
The problem is in your JOIN ON clause. You need to change it like
INNER JOIN users ON
rating_draft_result.user_id = users.id
(OR) If you want to have both the conditions then use a AND operator like
FROM rating_draft_result
INNER JOIN users ON
rating_draft_result.user_id = users.id
AND rating_draft_result.result = users.id
Change your entire query to be like below
SELECT COUNT(rating_draft_result.id),
rating_draft_result.user_id,
rating_draft_result.result
FROM rating_draft_result
INNER JOIN users ON
rating_draft_result.user_id = users.id
AND rating_draft_result.result = users.id;

MySQL Select rows where the user has not voted yet (contest app)

I have a photo contest app where users can vote. I would like to select all of the contests where the logged in user has not voted yet.
So I have two tables.
The "contest" table :
CREATE TABLE `contest` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`category_id` int(11) NOT NULL,
`title` varchar(255) NOT NULL,
`desc` text NOT NULL,
`created_date` datetime NOT NULL,
`started_date` datetime NOT NULL,
`nb_user_min` int(11) NOT NULL,
`nb_photo_max` int(11) NOT NULL,
`nb_photo_per_user` int(11) NOT NULL,
`duration` int(11) DEFAULT NULL,
`status` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
The "contest_vote" table :
CREATE TABLE `contest_vote` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`pic_id` int(11) DEFAULT NULL,
`contest_id` int(11) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
`date` datetime DEFAULT NULL,
`ip` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
So to be clear, I want to get the number (or the list) of contests where the user has not voted yet. So I have tried with a LEFT JOIN but it doesn't return the good set of result. Here it the query I have until now :
SELECT DISTINCT c.id, c.title, cv.user_id
FROM contest c
LEFT JOIN contest_vote cv
ON cv.contest_id = c.id AND cv.user_id != ?
GROUP BY contest_id
("?" represents the user_id parameter).
Can you help me to solve this?
This is pretty simple do with a subquery. Just grab all contest without where user is voted like this:
SELECT DISTINCT c.id, c.title
FROM contest c
WHERE c.id NOT IN (SELECT DISTINCT cv.contest_id FROM contest_vote cv WHERE cv.user_id = ?)
Try this one :
SELECT DISTINCT c.id, c.title, cv.user_id
FROM contest c
LEFT JOIN contest_vote cv ON cv.contest_id = c.id AND cv.user_id != ? WHERE c.user_id = ?
GROUP BY contest_id

Cannot retrieve column information from database

I have two tables, namely user_info and comments. I want to join the tables, so i can relate the user_id from the from comments after the inner join has happened, which will join based on the id columns. The whole reason for this is so i can find out what the id is of a user who posts a comment on a users profile, which i store in user_id.
SHOW CREATE TABLE user_info
CREATE TABLE `user_info` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(12) COLLATE utf8_unicode_ci NOT NULL,
`pass` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
`joined` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`))
ENGINE=InnoDB AUTO_INCREMENT=64 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci'
SHOW CREATE TABLE comments
'CREATE TABLE `comments` (
`id` int(11) DEFAULT NULL,
`comment` text COLLATE utf8_unicode_ci,
`date_posted` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`user_id` int(11) DEFAULT NULL)
ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci'
The query code
try {
$result = $db->prepare("SELECT user_id
FROM comments
INNER JOIN user_info USING (id)
WHERE id = :user");
$result->bindParam(':user', $post_session_user_id);
$result->execute();
$comment_details = $result->fetch();
}
How comment_details is stored
$comment_id = $comment_details[0];
and then i do a var_dump that returns NULL
var_dump($comment_id);
Any ideas what is wrong?
I think you should not be using USING as that works only when you have 2 fields, one in each table both having the same name.
In your tables comment.user_id holds the user_info.id
So your query should probably be
SELECT user_id
FROM comments
INNER JOIN user_info ON user_info.id = comments.user_id
WHERE comments.id = :user

"my network" function with sql subquery

I need a little help for one sql query;
here is my basic user database table
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(100) NOT NULL,
`pass` varchar(255) NOT NULL,
`fname` varchar(50) NOT NULL,
`lname` varchar(40) NOT NULL,
`network` varchar(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=27 ;
and here is my basic topics database table
CREATE TABLE IF NOT EXISTS `topics` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userid` varchar(100) NOT NULL,
`title` varchar(255) NOT NULL,
`body` text,
`tags` varchar(256) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
What I'm trying to do is;
i.e. list all topics from users who joined "harvard" network
You just need a simple JOIN. Join the tables on the userID (of those who are in "harvard").
SELECT title,body
FROM topics, users
WHERE userid = users.id
AND network = 'harvard'
Or using the JOIN keyword:
SELECT title,body
FROM topics
JOIN users ON userid = users.id
WHERE network = 'harvard'
This should do the trick, I think:
SELECT
title
FROM
topics t
INNER JOIN
users u ON t.userid=u.id
WHERE
network='Harvard'
SELECT t.title
FROM users u
INNER JOIN topics t ON u.id = t.userid
WHERE u.network = 'harvard'
GROUP BY u.id

Categories