I have two tables in my database:
1) blog_table
2) content
In blog_table I have values called postID that may or may not match up to values called id in the table content. I am wanting to know how I can write a while loop or foreach loop that will cycle through content table and perform one action if the id equals the value of postID in the blog_table and perform a different action if it doesn't.
Right now I can only get id = postID
$blog_table = $_REQUEST['blog_table'];
$getblogtable = mysql_query("SELECT * FROM content WHERE type = '5' AND blogID = '{$_REQUEST['id']}' ORDER BY `order` ASC");
while ($row = mysql_fetch_assoc($getblogtable))
{
$getblogposts1 = mysql_query("SELECT postID FROM `$blog_table`");
while ($row1 = mysql_fetch_assoc($getblogposts1))
{
if( $row1['postID'] == $row['id']) {
echo "do something<br>";
}else{
echo "do something else<br>";
}
} echo "<p></p>";
}
[Edit based on OP's comments and revised question]
$getblogposts = mysql_query("SELECT * FROM content WHERE type = '5' AND blogID = '{$_REQUEST['id']}' ORDER BY `order` ASC");
while ($row = mysql_fetch_assoc($getblogposts))
{
$matches = mysql_query("SELECT * FROM $blog_table WHERE postID = $row['id']");
if (mysql_num_rows($matches) > 0)
{
// do something
}
else
{
// do something else
}
}
Regarding a different design, I can't say for sure that it's necessary, but I don't like running a loop of queries like this. I think one query should be enough to get everything you need in this case. Maybe if you describe your application, we could find a better query or more appropriate design.
Just providing an easier to see solution for you to your problem.
I suggest using inner joins which will solve the issue at hand.
For example, Something like:
SELECT * FROM content AS C INNER JOIN $blog_table AS B on B.postID = C.id
Here is a great introduction to joins (inner, left, right, full):
http://www.w3schools.com/sql/sql_join.asp
$blog_table = $_REQUEST['blog_table'];
$getblogtable = mysql_query("SELECT postID FROM `$blog_table`");
while ($row = mysql_fetch_assoc($getblogtable))
{
$postID = $row['postID'];
$getblogposts1 = mysql_query("SELECT * FROM content WHERE id = '$postID' ORDER BY `order` ASC");
while ($row1 = mysql_fetch_assoc($getblogposts1))
{
// if( $row1[id] == $postId )
// do something
// else
// do something else
}
}
Related
hi I have to create a system of comments within various trhead I performed before and all the while the trhead 'while inside the comment and it works but is really slow and with a large number of threads often gives me timeout error how can I fix the problem?
function commenti($id) {
$query2 = "SELECT * FROM table2 WHERE numid='$id' ORDER BY id ASC";
$result2 = mysqli_query($conn,$query2);
if($result2->num_rows >0)
{
while($row2 = $result2->fetch_array(MYSQLI_ASSOC))
{
$idt2 = $row2['id'];
$testot2 = $row2['testo'];
return $testot2;
}
} else {
echo "No comment";
}
}
$query = "SELECT * FROM table1 where visualizza='1' ORDER BY id DESC";
$result = mysqli_query($conn,$query);
if($result->num_rows >0)
{
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$id = $row['id'];
$titolo = $row['titolo'];
$testo = commenti($id);
echo "$titolo $testo <br>";
}
}
mysqli_close($conn);
?>
I thought to use the join but if there are more duplicates also post comments
$query = "SELECT * FROM table1 left JOIN table2 ON table1.id = table2.numid where visualizza='1' ORDER BY id DESC";
I'm going to assume that you are trying to pull a ton of records. The best way to approach this is to add pagination and only load ~10-20 comments per page. depending on your server
Update:
#OP Basically on first load of the page you load ~10 comments, once they click view more then you load in the next few using ajax. Rinse and repeat.
So what I'm trying to do is create a live friends search. To do this I need an array of names for AJAX to search through.
Heres my while loop.
if($_REQUEST['D'] == 'viewfriends') {
$FREINDS = array();
$FRIENDS_QUERY = "SELECT * FROM `FRIENDS` WHERE `USER` = '{$Modules['User']->Username}' AND `STATUS` = 'accepted' ORDER BY `ID` Limit 10 ;";
$FRIENDS_RESULT = mysql_query($FRIENDS_QUERY);
if(mysql_num_rows($FRIENDS_RESULT) > 0) {
while($FRIENDS_ROW = mysql_fetch_assoc($FRIENDS_RESULT)) {
$sql = "SELECT * FROM `USERS` WHERE `USERNAME` = '{$FRIENDS_ROW['FRIEND']}' ;";
$REQUEST_ROW = mysql_fetch_assoc(mysql_query($sql));
$FRIENDS = $REQUEST_ROW['USERNAME'];
}
echo json_encode($FRIENDS);
} else {
echo'<div class="update status">Sorry, You have no friends at this time. sadface.</div>';
}
}
I put the echo $FRIENDS in there as a test, right now it doesn't display anything. Where did I derp?
You can't echo an array. You can use either print_r($friends) to display the whole row of fields requested in the query (you request *)
or you can echo $friends['name'] (depending on how you declared name in your database)
try this:
if($_REQUEST['D'] == 'viewfriends') {
$FRIENDS = array();
$USERNAME = $Modules['User']->Username;
$SQL_QUERY = "SELECT F.*, U.* FROM FRIENDS AS F LEFT JOIN USER AS U ON F.USER = U.USERNAME WHERE F.USERNAME = '{$USERNAME}' AND STATUS = 'accepted' ORDER BY F.ID LIMIT 10";
$RESULTS = mysql_query($SQL_QUERY);
if(mysql_num_rows($RESULTS) > 0) {
while($ROW = mysql_fetch_assoc($RESULTS)) {
$FRIENDS[] = $ROW['USERNAME'];
}
echo json_encode($FRIENDS);
} else {
echo'<div class="update status">Sorry, You have no friends at this time. sadface.</div>';
}
}
$FRIENDS[] = $REQUEST_ROW['USERNAME'];
then print_r($FRIENDS); echo will output array you need to loop the array or echo json_encode($FRIENDS); to see something
also are you sure that USERNAME is uppercase and not just username in lowercase lowercase as well as for the table name.
also i think you can use a JOIN clause instead of making to SQL requests
You have syntax error:
$FREINDS = array(); should be $FRIENDS = array(); .
And also:
$FRIENDS = $REQUEST_ROW['USERNAME'] should be $FRIENDS[] = $REQUEST_ROW['USERNAME']
And
echo $FRIENDS; should be echo json_encode( $FRIENDS );
The PHP won't actually echo out an array. If you do an echo of an array, it outputs "Array". Plus your javascript wouldn't know what to do with a PHP array if it did pass it that way.
Try:
echo(json_encode($FRIENDS));
Also, you should really listen to the feedback in the comments. Your code is very vulnerable to attack and not set up to scale well for such a potentially huge app.
You have a couple of issues that make your code either less secure or less efficient. The most obvious inefficiency is that you are doing a database call inside your while loop, so if someone has 10 friends, that means you've done 11 database queries when you may have only needed one or two. Here are the two queries:
SELECT * FROM `FRIENDS`
WHERE `USER` = '{$Modules['User']->Username}'
AND `STATUS` = 'accepted' ORDER BY `ID` Limit 10
SELECT * FROM `USERS` WHERE `USERNAME` = '{$FRIENDS_ROW['FRIEND']}'
So before we determine if these two can be combined, the first big red flag is the SELECT *. I use it all of the time, but it will get you kicked out of the better database bars. In your case, it's really unnecessary. We know from the second query that the only thing you are using from the first query is the $FRIENDS_ROW['FRIEND'] to match against the USERNAME. So that first query can become:
SELECT FRIEND FROM `FRIENDS`
WHERE `USER` = '{$Modules['User']->Username}'
AND `STATUS` = 'accepted' ORDER BY `ID` Limit 10
You also have the SELECT * in the second query, and we can tell that (for now) the the only thing you are using is the USERNAME, so it can become:
SELECT USERNAME FROM `USERS` WHERE `USERNAME` = '{$FRIENDS_ROW['FRIEND']}'
Finally, we can see from the second query that the FRIEND name and the USERNAME are identical; otherwise why would you query for the usernames where the username equals the friend name. If that's the case, we can drop your second query completely, since we already know the usernames from the first query.
The reason why it's both inefficient and unsafe is because you are using the OG mysql functions, which are clunky and don't offer the option of prepared statements. Prepared statements let you (among other things) put variables in your query in such a way that when you actually call the query, the parts that are variables are known and can thus be sanitized, avoiding the horrors of mysql injections that everyone has mentioned.
I won't bore you with the play-by-play, but here is what your code might look like if you used the newer mysqli library with a prepared statement:
if($_REQUEST['D'] == 'viewfriends') {
$friends = array();
$friend_lookup = $mysqli->prepare("SELECT FRIEND FROM FRIENDS WHERE
USER = ? AND STATUS = 'accepted'
ORDER BY FRIEND");
$friend_lookup -> bind_param('s', $userName);
$userName = $Modules['User']->Username;
$friend_lookup -> execute();
$friend_lookup -> bind_result($friend);
while($friend_lookup -> fetch()) {
$friends[] = $friend;
}
if($friends) {
echo json_encode($friends);
} else {
echo "Sorry, no friends. Boo.";
}
}
Im trying to call all users from a database with the same interests as the current, logged in user on my website.
I have the following
// Get Session USER interest
$interestsquery = "SELECT `interest` FROM `user_interests` WHERE `user_id` = " . $usersClass->userID();
$result = mysql_query($interestsquery);
$interests = array();
while(list($interest) = mysql_fetch_array($result))
$interests[] = $interest;
$interest1 = $interests['1'];
$interest2 = $interests['2'];
$interest3 = $interests['0'];
// END INTERESTS
//USers with Same Interests
$interests_query = "SELECT * FROM produgg_users
join user_interests on produgg_users.id = user_interests.user_id
where interest = '$interest1' and produgg_users.id != '".$usersClass->userID()."'";
$interests_result = mysql_query($interests_query) or die(mysql_error());
if($interests_result != 0) {
while($interests_row = mysql_fetch_array($interests_result, MYSQL_ASSOC))
{
echo $interests_row['user_id'];
}
}
else
{
print "No users to display!";
}
//END SAME INTERESTS
which doesnt bring back any data, yet if I add (beneath //USers with Same Interests)
$interest1 = 'footy';
the interests_query seems to work, can anybody see where im going wrong?
My problem seems to lie here...
$interest1 = $interests['1'];
$interest2 = $interests['2'];
$interest3 = $interests['0'];
// END INTERESTS
//USers with Same Interests
$interest1 = 'footy';
If I manually assign a value to $interest variable it works, but i need to get use the value from the array above, does this make sense?
If your code brings back the correct data when you add $interest1 = 'footy'; line, that would imply that there is something wrong with the value of that variable when you don't. Have you tried var_dump($interest1); right under //Users with Same Interests line to see what kind of input you get from your interestsquery?
I would expect the var_dump to not return a valid string (since if it would, the query would work following the $interest1 = 'footy'; assumption), so you would have to look at what interestsquery returns wrong.
Looks like you querying user_id from user_interests as number, but from produgg_users as string. Maybe there's a problem
You can do it with one query:
$userID = mysql_real_escape_string($usersClass->userID());
$sql = "
SELECT * FROM user_interests AS ui1
JOIN LEFT user_interests AS ui2 ON ui1.id = ui2.id
JOIN LEFT produgg_users AS pu ON ui2.user_id = pu.id
WHERE ui.user_id = " . userID ;
I am trying to print the duplicate records of the table but only the single row is getting
echoed.However in mysql this query results all the duplicate records. Here is the query:
$q = mysql_query("SELECT * FROM add WHERE cust_id = '144' GROUP BY cust_id");
$r = mysql_fetch_array($q);
$s = mysql_num_rows($q);
while($s !=0)
{
echo $r;
$s=$s-1;
}
Whats wrong with the code?
$q = mysql_query("SELECT * FROM add WHERE cust_id = '144' GROUP BY cust_id");
while($r = mysql_fetch_array($q))
{
print_r($r);
}
You need to loop through the entire record set... you are only grabbing the first row:
$resultset = mysql_query("select * from add where cust_id = '144' group by cust_id");
while($row = mysql_fetch_assoc($resultset))
{
echo $row['column_name'];
}
Your SQL query will in practice only ever return 0 or 1 rows, due to the GROUP BY clause. Are you absolutely sure that that's the query you were executing in mysql?
well, if you want to get duplicate values, then this query will serve you well:
T = the table
f = the field to check for duplicates
id = the rows id
select id,f from T group by f having count(f)= 2;
or >2 if you want every value in f that occurs in more than one row.
having is like where but evaluated after group by.
Try the following:
$q = mysql_query("SELECT * FROM add WHERE cust_id = '144'");
while($r = mysql_fetch_array($q))
{
echo $r;
}
The following goes into an endless loop, meaning it just constantly shows the same record over and over and over again.
<?php
while ($rowr = mysql_fetch_assoc(mysql_query("SELECT * FROM table1")) {
while($rowu = mysql_fetch_assoc(mysql_query("SELECT * FROM table2 WHERE id = '".$rowr['uid']."'"))){
while($rowc = mysql_fetch_assoc(mysql_query("SELECT * FROM table3 WHERE id = '".$rowr['cid']."'"))){
?>
<tr><td><?php echo $rowc['post']; ?></td><td><?php echo $rowu['username']; ?></td><td><font color="#FF0000">X</font></td></tr>
<?php
};
};
};
?>
Why does that happen and how can I fix it?
You are putting the mysql query in the while statement so every time it gets there it does the same query and shows the same first record, you are never advancing to the next record in the result set.
Personally I would combine all queries into one, but to show how you can solve your problem (the same applies to all loops):
$results = mysql_query("SELECT * FROM table3 WHERE id = '".$rowr['cid']."'");
while ($rowc = mysql_fetch_assoc($results))
{
// do stuff
}
Simply because the query gets executed again every time the loop condition is checked. That means you'll always get the same result unless something changes in the database in the meantime.
You need something like this:
<?php
$res1 = mysql_query("SELECT * FROM table1");
while ($rowr = mysql_fetch_assoc($res1)) {
$res2 = mysql_query("SELECT * FROM table2 WHERE id = '".$rowr['uid']."'");
while($rowu = mysql_fetch_assoc($res2)){
$res3 = mysql_query("SELECT * FROM table3 WHERE id = '".$rowr['cid']."'");
while($rowc = mysql_fetch_assoc($res3)){
?>
<tr><td><?php echo $rowc['post']; ?></td><td><?php echo $rowu['username']; ?></td><td><font color="#FF0000">X</font></td></tr>
<?php
}
}
}
?>
That's just to illustrate why it doesn't work. As others already noted, combining your queries into one using JOIN would be advisable.
Btw, you don't need a ; after a {} block.
Use joins and you can do it in one query.
Mysql Join
Join Tutorial
You're re-executing the queries on each loop iteration, restarting the results from scratch.
You want something like this instead:
$resultR = mysql_query("... table1");
while($rowR = mysql_fetch_assoc($resultR)) {
$resultU = mysql_query("... table2");
while($rowU = mysql_fetch_assoc($resultU)) {
etc...
}
}
Of course, this is a highly inefficient construct. You end up running count($rowR) * count($rowU) * count($rowC) queries. Why not reformulate it as a join?