I have 2 tables, one is called post and one is called followers. Both tables have one row that is called userID. I want to show only posts from people that the person follows. I tried to use one MySQL query for that but it was not working at all.
Right now, I'm using a workaround like this:
$getFollowing = mysqli_query($db, "SELECT * FROM followers WHERE userID = '$myuserID'");
while($row = mysqli_fetch_object($getFollowing))
{
$FollowingArray[] = $row->followsID;
}
if (is_null($FollowingArray)) {
// not following someone
}
else {
$following = implode(',', $FollowingArray);
}
$getPosts = mysqli_query($db, "SELECT * FROM posts WHERE userID IN($following) ORDER BY postDate DESC");
As you might imagine im trying to make only one call to the database. So instead of making a call to receive $following as an array, I want to put it all in one query. Is that possible?
Use an SQL JOIN query to accomplish this.
Assuming $myuserID is an supposed to be an integer, we can escape it simply by casting it to an integer to avoid SQL-injection.
Try reading this wikipedia article and make sure you understand it. SQL-injections can be used to delete databases, for example, and a lot of other nasty stuff.
Something like this:
PHP code:
$escapedmyuserID = (int)$myuserID; // make sure we don't get any nasty SQL-injections
and then, the sql query:
SELECT *
FROM followers
LEFT JOIN posts ON followers.someColumn = posts.someColumn
WHERE followers.userID = '$escapedmyuserID'
ORDER BY posts.postDate DESC
Related
I am currently trying to make a system which selects a user at random from the table 'users' and appends it to another table 'agreeuser' or 'disagreeuser' depending on whether or not the user has the 'opinion' value of 'like' or 'dislike'. I am doing this by using $row to select the full row where the user has the opinion of 'like', but it doesn't seem to be adding the data stored in '$row[username]' to the 'user' column of the 'agreeuser' or 'disagreeuser' table.
I have already tried storing the '$row['username'] value as a variable and using this in the value aspect of the query, but it doesn't seem to have worked. I have also tried combining the INSERT and SELECT queries and it still has no effect. Can anyone tell me what I am doing wrong, please? :)
if($_SESSION['pageLoaded'] != "true") {
$selectLikesQuery = "SELECT * FROM users WHERE opinion = 'like' ORDER BY RAND() LIMIT 1";
$likeSelectorResult = mysqli_query($userConnect, $selectLikesQuery);
while($row = mysqli_fetch_assoc($likeSelectorResult)) {
$removeCurrentAgreeContent = "TRUNCATE TABLE agreeUser";
$addAgreeUserQuery = "INSERT INTO agreeUser (user) VALUE ('$row[username]')";
mysqli_query($chatConnect, $removeCurrentAgreeContent);
mysqli_query($chatConnect, $addAgreeUserQuery);
}
$selectDislikesQuery = "SELECT * FROM users WHERE opinion = 'dislike' ORDER BY RAND() LIMIT 1";
$dislikeSelectorResult = mysqli_query($userConnect, $selectDislikesQuery);
while($row = mysqli_fetch_assoc($dislikeSelectorResult)) {
$removeCurrentDisagreeContent = "TRUNCATE TABLE disagreeUser";
$addDisagreeUserQuery = "INSERT INTO disagreeUser (user) VALUE ('$row[username]')";
mysqli_query($chatConnect, $removeCurrentDisagreeContent);
mysqli_query($chatConnect, $addDisagreeUserQuery);
}
$_SESSION['pageLoaded'] = "true";
}
I need the username from 'users' to be inserted into the 'user' column of 'agreeuser'. Thanks for any help, and apologies if I'm doing something stupid :)
Why don't you use SQL views to just see needed data in "a virtual table", instead of creating duplicate data?
Views is a very helpful feature.
For example, make a SELECT query to find needed rows:
SELECT * FROM users WHERE opinion = 'dislike'
If this select suits you, just add:
CREATE OR REPLACE VIEW v_agreeUsers AS SELECT * FROM users WHERE opinion = 'dislike'
And make the same for users who agree:
CREATE OR REPLACE VIEW v_disagreeUsers AS SELECT * FROM users WHERE opinion = 'like'
To be honest, I don't understand why do you do random select and insert users only one by one.
In case you want to get only one and random user, just run this query after you've already created views mentioned upper:
SELECT * FROM v_agreeUsers ORDER BY RAND() LIMIT 1
SELECT * FROM v_disagreeUsers ORDER BY RAND() LIMIT 1
Good luck! :)
This should be a basic question, but I haven't used Mysql for a very long time and forgot all the basic stuff. So SO programmers please bear with me.
I have 2 tables like this:
Table 1 (events): here
Table 2 (users): here
I would like to select all rows in the events table where event_invitees contains a username. I was able to do this using:
SELECT * FROM meetmeup_events WHERE event_invitees LIKE '%$username%'
Now I'd like to also select the event_invitees's photo from the users table (column called user_userphoto). My attempt to this was this:
$result = mysql_query("SELECT meetmeup_events.*, meetmeup_user.user_photo
FROM meetmeup_events
WHERE event_invitees LIKE '%$username%'
INNER JOIN meetmeup_user
ON meetmeup_user.user_username = meetmeup_events.event_inviter");
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows['meetmeup_user'][] = $r;
}
echo json_encode($rows);
This gave me an error: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource
How can I do this? What am I missing? Can you give me some examples?
Thanks in advance! I'll be sure to accept the working answer!
You should change your mysql functions to either mysqli / PDO, although the problem seems to be the query itsef. Should be:
SELECT meetmeup_events.*, meetmeup_user.user_photo
FROM meetmeup_events
INNER JOIN meetmeup_user
ON meetmeup_user.user_username = meetmeup_events.event_inviter
WHERE event_invitees LIKE '%$username%'
(the WHERE clause at the end)
Sql fiddle demo: http://sqlfiddle.com/#!2/852a2/1
Its just a matter of getting the query coded in the correct order, and you might like to make it a little more managable by using alias's for the table names
Try this :-
SELECT me.*,
mu.user_photo
FROM meetmeup_events me
INNER JOIN meetmeup_user mu ON mu.user_username = me.event_inviter
WHERE me.event_invitees LIKE '%$username%'
This of course assumes that all the column names are correct and the mu.user_username = me.event_inviter does in fact make sence because those fields are in fact equal
Additional Suggestion
You are not actually issuing the query for execution by mysql.
You have to do this :-
$sql = "SELECT me.*,
mu.user_photo
FROM meetmeup_events me
INNER JOIN meetmeup_user mu ON mu.user_username = me.event_inviter
WHERE me.event_invitees LIKE '%$username%'";
$result = mysql_query($sql);
$rows = array('mysql_count' => mysql_num_rows($result) );
while($r = mysql_fetch_assoc($result)) {
$rows['meetmeup_user'][] = $r;
}
echo json_encode($rows);
Now in your browser using the javascript debugger look at the data that is returned. There should at least be a mysql_count field in it even if there is no 'meetmeup_user' array, and if it is zero you know it found nothing using your criteria.
I have this table advertisements, where I store all my advertisements. Everytime a user clicks on an advertisement, I record that click into a table called advertisement_clicks.
What I store in both tables is: userid and a unique token.
So, I want to count how many available advertisements there is for the user to see. Currently, I am doing it like this:
$ex = $dbh->prepare("SELECT * FROM advertisements WHERE status='2' AND fixed='0'");
$ex->execute();
foreach ($ex as $normal) {
$search2=$dbh->prepare("SELECT * FROM advertisement_clicks WHERE token=:token AND username=:username");
$search2->bindParam(":token",$normal['token']);
$search2->bindParam(":username",$userdata['id']);
$search2->execute();
}
$allnormal = $ex->rowCount();
$clickednormal = $search2->rowCount();
$normalads = $allnormal-$clickednormal;
$allnormal = how many advertisements is available.
$clickednormal = how many of these advertisements has the user clicked.
So the above approach is a bit messy and it doesn't give the correct result.
Can someone help me do this a smarter way?
You can use COUNT to get it through SQL instead.
SELECT count(*) as addCount FROM advertisement_clicks WHERE
token=:token AND username=:username"
I havn't messed with php in a while so I'm not going to even attempt to write some code lol, but the way I did it was I executed this query:
SELECT COUNT(*) FROM advertisement_clicks WHERE token=:token AND username=:username
Then get the query result which will return the advertisement count.
I have small PHP script which has
$query = "SELECT MAX(id) FROM `dbs`";
//query run
$row = mysql_fetch_array($result);
$val = $row[0];
Which runs fine, but I want to understand why i can't access the row with the fieldname, like if i have this
$query = "SELECT id FROM `dbs`";
i am able to use the folowing
$val = $row['id'];
but whenever i use this MAX() function, i have to change to
$val = $row[0];
to access the values
I have no clue about this. Any help would be appreciated. Thankss
You need to give it an alias:
<?php
$query = "SELECT MAX(id) AS `id` FROM `dbs`";
//query run
$row = mysql_fetch_array($result);
$val = $row['id'];
Edit:
To explain this it's probably best to show an example of a different query:
SELECT MAX(`id`) AS `maxId`, `id` FROM `dbs`
Using the above it will return as many rows are in the table, with 2 columns - id and maxId (although maxId will be the same in each row due to the nature of the function).
Without giving it an alias MYSQL doesn't know what to call it, so it won't have an associative name given to it when you return the results.
Hope that helps to explain it.
SELECT MAX(id) AS myFieldNameForMaxValue
FROM `dbs`
and then
$row = mysql_fetch_array($result);
$val = $row['myFieldNameForMaxValue'];
If you run this query on mysql commandline you'll see that the field name returned by mysql is MAX(id). Try running on phpmyadmin and you'll see the same. So if you try $row['MAX(id)'] it'll work. When using a mysql function, it gets added to the name, so use an alias, like other said here, and you're good to go: SELECT MAX(id) AS id FROM dbs. Also, never forget to use the ` chars, just in case you have some columns/tables with reserved names, likefrom`.
i got a fairly simple layout going and for the life of me i cant figure out why this returns nothing:
<?php
// Gets A List Of Comic Arcs
$result = mysql_query("SELECT * FROM ".$db_tbl_comics." GROUP BY ".$db_fld_comics_arc." ORDER BY ".$db_fld_comics_date." DESC LIMIT 20");
while ($comic = mysql_fetch_array($result)) {
// Now Go Back And Count Issues For Each Comic Arc Above
$result22 = mysql_query("SELECT * FROM ".$db_tbl_comics." WHERE ".$db_fld_comics_arc."=".$comic[$db_fld_comics_arc]);
$total_issues = mysql_num_rows($result22);
echo $total_issues;
}
?>
No other query is refered to as $result22.
$comic[] has already been defined in the previous query.
echo mysql_error($result22); returns no errors.
Let me know if you need any other info.
I am assuming that the column $db_fld_comics_arc is a string.
Change:
$result22 = mysql_query("SELECT * FROM ".$db_tbl_comics." WHERE ".$db_fld_comics_arc."=".$comic[$db_fld_comics_arc]);
To:
$result22 = mysql_query("SELECT * FROM ".$db_tbl_comics." WHERE ".$db_fld_comics_arc."='".$comic[$db_fld_comics_arc]."'");
Am I wrong? If so, let me know the table structure, and what your error reporting is set to.
Also, could you let us know the purpose of your SQL? It may also be possible to put the data together in one query, instead of looping sql queries through, and using data from a first query.
Maybe it is because $db_fld_comics_arc is in $comic[$db_fld_comics_arc]
if both are the same then you should try replacing $db_fld_camics_arc with $comic[$db_fld_comics_arc].