Trying to use variable in MySQL INNER JOIN - php

I am a php and MySQL newbie. What I have done is created an html form with a <select> dropdown. Based on the selection from the form, it changes the $_SESSION[campaignID] variable. Changing the selection in the form is supposed to then change what displays on the page. The page consists of a forum style post that allows users to fill out a textarea and then submit it into the MySQL database into a table called "posts." On this same page I then display the contents of the "posts" table.
What I have done is in the posts MySQL table, I have added a campaignID row. Then in my campaigns table I also have a campaignID row. The campaignID in campaigns table auto increments every time a campaign is created. Then with the earlier mentioned dropdown I can select the campaign I want, and it should then show all posts with the same campaignID as the campaign I selected.
I can verify that the $_SESSION[campaignID] is changing when i select the various options. Because when I do that and then save another post, it takes the session variable campaignID and saves it properly in the posts table.
Now what I need it to do, is when I change the drop down (which then changes $_SESSION[campaignID]) I need it to display the posts that share the same campaignID as the selected campaign. I am just not able to get it to display when trying to put a variable in my INNER JOIN query. I have a feeling the info I have provided may not be enough, but not sure what else I need to include here. Help?
Code that contains the INNER JOIN query and displays the various rows of posts table
UPDATED
<?php
$con=mysqli_connect("localhost","dorians","ds2953!b67P$","aldentec");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$campaignID = $_SESSION['campaignID'];
$result = mysqli_query($con,"SELECT posts.postDate, posts.postName, posts.postEntry FROM posts INNER JOIN campaigns ON posts.campaignID=" . $campaignID);
while($row = mysqli_fetch_array($result))
{
echo "<div id='campaignPostContainer'>";
echo "<ul class='campaignPostBox'>";
echo "<p class='postInfo'>";
echo "Posted on:";
echo "<li>" . $row['postDate'] . "</li>";
echo "</p>";
echo "<p class='postInfo'>";
echo "Posted by:";
echo "<li>" . $row['postName'] . "</li>";
echo "</p>";
echo "<li class='postEntry'>" . $row['postEntry'] . "</li>";
echo "</ul>";
echo "</div>";
echo "<hr>";
}
mysqli_close($con);
?>

Without going into a use-prepared-statements rant...
You're not pulling the session variable, but assigning $campaignId to literally the string $_SESSION[campaignID].
Change your line:
$campaignID = '$_SESSION[campaignID]';
to:
$campaignID = $_SESSION['campaignID'];
Also, your query is going to generate a cross product unless you define something in your ON clause like:
SELECT posts.postDate, posts.postName, posts.postEntry FROM posts
INNER JOIN campaigns ON posts.campaignID= $campaignID
AND posts.campaignID= campaigns.id

The value should be in single quote ' so you may try this
posts.campaignID='" . $campaignID ."'"
instead of
posts.campaignID=" . $campaignID

Related

PHP - Trying to update multiple mysql values based on if checkbox is checked

I'm currently working on a points/rewards system, the problem I'm facing is I'm querying the database like so;
$result = mysqli_query($con,"SELECT * FROM users WHERE usertype='group_two' ORDER BY
points DESC");
while($row = mysqli_fetch_array($result)) {
echo "<li class='select-area'><label><span>" . $row['firstname'] . "</span>";
echo "<span>" . $row['lastname'] . "</span>";
echo "<span>" . $row['points'] . "</span><span><input type='checkbox'
name='receipient_id'
value=" . $row['id'] ." /></span></label></li>";
}
This lists the users that are able to receive points, and that works fine, but If I select multiple users it only sends points to the last checked user, where I would like it to send points to all checked users.
My update query is as follows;
$update_query="UPDATE users u1 JOIN users u2
ON u1.id = '$sender_id' AND u2.id= receipient_id
SET u1.points = '$sender_updated_points',
u2.points = '$receiver_updated_points';";
Are there any specific tricks I have missed using checkboxes to select multiple rows for updating? I've been googling for around 16 hours.
You can give the name property of checkboxes as an array like
<input type='checkbox' name='receipient_id[]' value=" . $row['id'] ." />
^
In this way, when the form with the selected checkboxes is send to the PHP script, the variable: $_POST['receipient_id'] will contain a numeric Array with the values of the selected checkboxes, having the index: 0, 1, 2,etc in their order.
$_POST['receipient_id'][0] will be the value of the first selected checkbox and $_POST['receipient_id'][1] will be the value of the second selected checkbox and so on.
Can you try it?
If you want to send multi values should be in array name="receipient_id" to name="receipient_id[]"
Suggestion on query
$update_query="UPDATE users u1 JOIN users u2
ON u2.id= u1.receipient_id
SET u1.points = '$sender_updated_points',u2.points = '$receiver_updated_points'
where u1.id = '$sender_id';";
This is how i used for the same condition as yours but i use it to delete multiple data that fetched from database
first in you while..loop
- give the name as array
<input type="checkbox" id="updcbx" name="updcbx[]" value="'.$row['id'].'"/>
than in your php submission, you can use code like this
if(isset($_POST['submit']))
{
if (is_array($_POST['updcbx']))
{
foreach($_POST['updcbx'] as $upd)
{
$update[$upd] = $upd;
$sql = "UPDATE TABLE SET FIELD = 'value' WHERE id = '$delete[$upd]'";
mysql_query($sql);
}
}
}
Hope this helps you :)

How to show multiple result with a user which the user appear once in MySQL and PHP?

Now I am designing a query to get the user name and what they have posted
here is the fields in table "user" and "post"
user: user_name, u_id
post: p_id, u_id, content
And I want to write a query to display like that
user_name content
Cherry hi,i am cherry
hello
Tom good day today=)
But not
user_name content
Cherry hi,i am cherry
Cherry hello
Tom good day today=)
How can I achieve that on PHP in table form?
GROUP_CONCAT should be helpful to you. You can read documentation on it here.
Your query could look like this:
select user_name, group_concat(content,"\n") from post group by user_name;
This will group all of the posts together by each user, and then concatenate the content field of all of a user's rows into a single string separated by newline.
You can see the SQLFiddle with query and results here
(Keep in mind that SQLFiddle prints its results, by default, in tabular HTML. Choose Run SQL -> Plaintext Output to see the actual newlines printed out)
EDITED (added content below)
If you want to use PHP to handle this, you can do the following:
$query = 'select user_name, group_concat(content,"\n") as contents from post group by user_name;'
$result = mysqli_query($query)
print '<table><tr><td>USER NAME</td><td>CONTENTS</td></tr>';
while ($row = mysqli_fetch_assoc($result)) {
print '<tr>';
print '<td>' . $result['user_name'] . '</td>';
print '<td>' . preg_replace("/\n/", '<br>' . $result['contents']) . '</td>';
print '</tr>';
}
print '</table>';
Here are links to documentation on some of the functions I used in this example:
mysqli_query
mysqli_fetch_assoc
preg_replace
select user.user_name, post.content
from user inner join post on
user.u_id = post.u_id
get the results, and show them at your convenience. If the user_name comes up more than once, just print it once, and go through all its content.
Try this:
SELECT u . * , (
SELECT GROUP_CONCAT( p.content )
FROM post p
WHERE p.u_id = u.u_id
) AS combine
FROM user u
LIMIT 0 , 30
If you want to display it in a table-like form, you could keep a variable which holds the current username or id.
$currentUser = false;
foreach ($rows as $row) {
echo '<tr><td>';
if ($row['user_id'] != $currentUser) {
//print user
$currentUser = $row['user_id'];
}
echo '</td><td>';
//print content
echo '</td></tr>';
}

While loop displaying result 3 times

Basicly I'm trying to make a simple news feed but I'm stuck at the moment as my while loop display the result 3 times, why is this? :/
<?php
$sql ="SELECT
*
FROM
news,
admins";
$result = mysql_query($sql);
if(!$result)
{
echo 'Error while selecting from database. Please contact the administration team';
} else {
while($row = mysql_fetch_assoc($result))
{
echo '
<div class="content_news">
<h1>' . $row['news_name'] . '</h1>
<p style="font-size:12px;">Posted by <b>' . $row['admin_name'] . '</b> on ' . $row['news_date'] . '
<p>' . $row['news_description'] . '</p>
read more
</div>
';
}
}
?>
If you'd like to see what I am talking about: http://freewallpaperblog.com/freshrp/
Ignore the last 2(those are static html not php)
your query selects data from 2 tables (news, admins) so it joins every row of 1st table with every row of 2nd table
SELECT * FROM news, admins
i recommend you to use following query
SELECT news.*, admins.admin_name FROM news
INNER JOIN admins ON news.admin_id = admins.id
where admin_id is your correct column name
You either have 3 admins or 3 rows of news. Your query makes a direct multiplication between tables. Try "left join" instead...
SELECT * FROM news
INNER JOIN admins ON admins.id = news.adminid
Or whatever adminid is in the news table.
Try the following query:
SELECT
*
FROM
news
Inner join admins on news.admin_id = admins.id
You made no JOIN statement in your SQL, as someone else has already commented on in your question. It would help if you posted the associated fields you're grabbing, but based on your $row keys, my best guess is the following should work for you (but I can't promise it will without knowing how your database is designed, I can only infer from the variable names):
$sql = "SELECT news.name, news.date, news.description, news.link, admins.name"
. "FROM news"
. "INNER JOIN admins"
. "ON news.name=admins.name"
References:
http://www.w3schools.com/sql/sql_join_inner.asp
http://www.w3schools.com/sql/sql_join_left.asp
http://dev.mysql.com/doc/refman/5.0/en/join.html

Creating Categories using database in PHP

Hi I want to create Categories listed which are saved in my database so when user upload his images and he select the category it saves the data in database in Cat column
Now I want to show category in PHP like this
Categories Total
Animals (4)
Celebrations (2)
Locations And Travel (11)
Object or still life (1)
Transportation (9)
Here is my PHP I am succeeded to show Categories names but not total category in each category
<?php
$con=mysqli_connect("localhost","root","123","user");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"Select Cat from save_data Group By Cat ")
or die(mysql_error());
echo "<table border='1'>
<tr>
<th>Categories</th>
<th>Total</th>
</tr>";
while($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
echo "<tr>";
echo "<td>" . $row['Cat'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Extend the table cell:
<td colspan="2"></td>
This way it extends over another cell.
Also I notice you are mixing mysqli and mysql:
or die(mysql_error());
Try to use mysqli as objects and \Exceptions instead of errors. It's worth learning about :-)
Update:
I did not understand your question at first. Please provide your schema so we can see your table structure.
Usually you would have 2 tables, one with categories and one with data and join them with a GROUP BY (if an item can be in several categories, you would have a third table like category_has_item!):
SELECT c.category AS cat,
COUNT(i.items) AS num
FROM category c
LEFT JOIN items i
ON c.category_id = i.category_id
GROUP BY c.category
Use LEFT JOIN to display empty categories and JOIN (without LEFT) to avoid empty categories.
Change your table echo:
echo "<td>" . $row['cat'] . "</td><td>(" . $row['num'] . ")</td>";
Update:
If you only have 1 table, I strongly suggest you to read about database normalization.
Update your query:
Select Cat,COUNT(Data) AS num from save_data Group By Cat
Replace Data by your data column
and your echo line:
echo "<td>" . $row['Cat'] . "</td><td>(" . $row['num'] . ")</td>";
try to change your sql query like this
SELECT count(*) AS total_count FROM (SELECT Cat FROM save_data GROUP BY Cat HAVING COUNT(Cat) > 1) AS t

What's wrong with this INNER JOIN SQL query?

I have three tables, tblMembers, tblBooks and tblReviews. The idea is a book review website.
Currently the Book Title is only displayed if there are reviews written for it, however I want the book title to always be displayed along with; either a list of reviews, or, the text, 'this title has not yet been reviewed.'
What is wrong with this SQL query?
$sql = "
SELECT *
FROM tblBooks
INNER JOIN tblReviews
ON tblBooks.bookID = tblReviews.bookID
INNER JOIN tblMembers
ON tblReviews.userID = tblMembers.userID
WHERE tblReviews.bookID = :bookID";
$query = $odb->prepare($sql);
$query->execute(array(":bookID" => $bookID));
$results = $query->fetchAll();
echo "<h1>".$results[0]['longTitle']."</h1>";
if($results !== FALSE && $query->rowCount()>0) {
foreach($results as $result) {
echo "Reviewed by: " . $result['firstName'] . " " . $result['lastName'];
echo "<br />";
echo "Rating: " . $result['rating']."/100";
echo "<br />";
echo "Date: " . $result['reviewDate'] . " " . $result['reviewTime'];
echo "<br />";
echo "Review:";
echo "<br />";
echo $result['reviewText'];
echo "<hr />";
}
} else { // the book has not been reviewed yet
echo "There are no reviews for this title yet";
}
As mentioned above, the line echo "<h1>".$results[0]['longTitle']."</h1>"; is only executed if the book has reviews, I want to get the book details prior to checking if it has reviews or not. How can I do this?
On another note, how can I check which books haven't been reviewed yet and populate a drop down list with the results? - This has been answered :D
How can I either:
Populate two separate drop down lists, one for books that have reviews and one for books that haven't been reviewed yet (this one I can do as I have the SQL from the question above).
OR
Populate the single dropdown list but put books that have reviews at the top, separated by a string of characters, let's say "---------- THESE BOOKS HAVEN'T BEEN REVIEWED YET ----------" followed by the books that haven't yet been reviewed. Is this possible?
SELECT *
FROM tblBooks
LEFT JOIN tblReviews
ON tblBooks.bookID = tblReviews.bookID
LEFT JOIN tblMembers
ON tblReviews.userID = tblMembers.userID
WHERE tblReviews.bookID = :bookID
Will return all books regardless if there is a review or a member affiliated with it.
IF there is a review return it, and if the review has a member it as well. otherwise NULL values will come back in fields related to tblMembers or tblReviews.

Categories