PHP / Mysql , compare the values from two while loops - php

Is there any way to take the contents of my while query below and use it elsewhere in my php script ?. What I am trying to do is collect the answers from a quiz and then compare them to the correct answers, the problem I am having is that the answers come from one table and the questions from another, so I am currently having to run two different while queries, but I cant use $quiz in the 2nd query as it just stays fixed with the last value it spat out. What im basically trying to do it load table A, look inside for the questionID, select that table and pull out the correct answer. Then load table B, looking inside that, select the answer with the same questionID and then use an if statement to compare to to, so that if correctanswer = actualanswer = correct , and loop over this for each question. The main problem that im coming up against though is the first while pulls out all the correct answers just fine, but I cant then use that in the other while to compare too. Im not sure if this is the correct way of doing it, or if there is a better way ?.
LOOK FOR THE CORRECT ANSWER :
$result0 = mysql_query("SELECT * FROM itsnb_chronoforms_data_createquestions
WHERE quizID='$quizID' ORDER BY cf_id ASC");
while($row0 = mysql_fetch_array($result0))
{
$answer = $row0['correctanswer'];
}
LOOK FOR THE ACTUAL ANSWER SUBMITTED :
$result = mysql_query("SELECT * FROM itsnb_chronoforms_data_answerquiz
WHERE quizID='$quizID' AND userID='$userID' ORDER BY cf_id ASC");
while($row = mysql_fetch_array($result))
{
$quiz = $row['quizselectanswer'];
}

Join is propably the best way to do this. But you could also use the php in_array()-Function:
$result0 = mysql_query("SELECT * FROM itsnb_chronoforms_data_createquestions WHERE quizID='$quizID' ORDER BY cf_id ASC");
while($row0 = mysql_fetch_array($result0))
{
$answers[] = $row0['correctanswer'];
}
And Then
$result = mysql_query("SELECT * FROM itsnb_chronoforms_data_answerquiz WHERE quizID='$quizID' AND userID='$userID' ORDER BY cf_id ASC");
while($row = mysql_fetch_array($result))
{
if(in_array($row['quizselectanswer'],$answers)){
...correct...
break;
}
}

SELECT * FROM itsnb_chronoforms_data_answerquiz a, itsnb_chronoforms_data_createquestions
q WHERE a.quizID='$quizID' AND a.userID='$userID' and q.quizID=a.quizID and
a.quizselectanswer = q.correctanswer
Should return all the correct answers. If you also want the wrong answers, you need to do a outer join on the two tables.

Related

Php loop all result in next mysql query

i have a small problem. I use two mysql queries for getting data.
First i want to get IDs from groups
$sqlGoups = "SELECT * from `groups` WHERE `Date`='$TodayDate' ";
$result = $conn->query($sqlGoups);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$IDgroups = $row["ID"];
With that, I'll get those IDs, for example 5, 7, 12, 15, 22
I want to put them all in the next mysql query:
$sqlNext = "SELECT * FROM `orders` WHERE ID = '$IDgroups' ORDER BY `ID` ASC ";
$result = $conn->query($sqlNext);
When I do this, I get the result only for the first ID (5). And I want for each
I can not INNER JOIN tables because I use this in next query.
I tried with foreach loop, but no effect.
Try this code
SELECT * FROM `orders`
WHERE ID REGEXP CONCAT('(^|,)(', REPLACE('$IDgroups', ',', '|'), ')(,|$)')
ORDER BY `ID` ASC
Just like #Elanochecer commented the best bet should be a JOIN statement, but if you wish to go through your route, you could use the IN and provide the IDs as comma separated string, your query should look similar to the one below:
...
$sqlNext = "SELECT * FROM orders WHERE ID IN ('$IDgroups') ORDER BY ID ASC ";
...
Also, confirm if $IDgroups is in the format 1,2,3,4
If you provide the schema I could come up with a workable JOIN statement for you, preferably you can create a repo with the schema

How can I select all id's from a sql table in descending order and then echo them (in php)?

I have several id's in a table called "leaderboards" that belong to different users. They're named as:"id_user" and they're not in order. What I want to do is printing divs in a leaderbord which should contain some info that I get from those id_user's.
The only problem I have about it is that after a research on stackoverflow and other websites, I still couldn't find how to select those id_user's in descending order AND be able to take one by one to get the info from that user and then continue with the next id_user, and so on.
I don't know how to select the specific row of each id_user in descending order to do the other codes that I already know how to do.
I hope it's not a duplicate of any other previosly asked question on this website (I really did a research and I couldn't find any specific answer to this question, for the sql part and the php part all together).
Thank you so so much beforehand.
An INNER JOIN between your tables will achieve what you intend.
SELECT *
FROM users
JOIN leaderboards WHERE users.id = leaderboards.id_user
ORDER BY users.id DESC
In each returned row, you will get the columns from both your users and leaderboards tables, so loop over the result and echo the information from the user you need.
$query = 'SELECT...';
$res = mysqli_query($query);
while ($row = mysqli_fetch_assoc($res)) {
echo '<div>'.$row['id'].' - '.$row['username'].' - '.$row['image'].'</div>';
}
You could do with a good read up on both PHP and MySql but I'll give you a clue.
EDIT
$query = "SELECT * FROM `the_name_of_your_table` ORDER BY `user_id` DESC;";
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
print $row["user_id"] . " - " . $row["username"] . "<BR>";
}
/* free result set */
mysqli_free_result($result);
}

I am trying to compare items in two different DB tables

I'm having trouble getting this to work correctly on my classifieds website, but basically what I am doing is taking all from an Item table LIMIT 40 and displaying it on page. Now for the hard part, I am taking all from a category table, which contains the names of the categories (each category name has a relative id). I need to print out the name of the category WHEN its id is equal to the id of the item. Hopefully the code will help clarify:
$sql = mysql_query("SELECT * FROM table_item ORDER BY creationtime DESC LIMIT 40");
$sql2 = mysql_query("SELECT * FROM table_category");
$ad_count = mysql_num_rows($sql);
$row2 = mysql_fetch_array($sql2);
if($ad_count > 0){
while($row = mysql_fetch_array($sql)){
$item_categoryId = $row["cid"];
$categoryId = $row2["id"];
$categoryName = $row2["name"];
while($item_categoryId == $categoryId){
$catName = $categoryName;
}
echo $catName;
}
}
Now, there is a little more to the code then what I put up, I tried to keep this short and sweet. Instead of echoing the category name, its actually being put into an HTML table row and there is also a lot more information being put in as well. Everything works fine when I don't do anything with the category name, but when I try to build something to access and compare it, then everything goes to shit.
Also, I should mention that this nested while loop seemed to be the best way to go about this (I have tried many ways) and the error I am getting for this is that "there is an unexpected '}'".
Use joins instead of nested loops:
SELECT
*
FROM
table_item,
INNER JOIN
table_category
ON
table_item.cid=table_category.id
ORDER BY
creationtime DESC
LIMIT 40
If not every item has a corresponding category, use LEFT JOIN instead of INNER JOIN.

Count comments to each recension?

I need someone to help me with this problem. My head doesn't want to think straight today.
So, i have a table named "recensions", and another named "comments". In each table, i have a column named "amne_id". This would make so i could connect the comments to the correct recension.
Now, on my first page, i simply get all the recensions with the code:
$rec = $this->db->get('recensions');
What i want is to count how many comments each recension has. But i have no idea how. I guess i maybe should use JOIN and num_rows()?
Please ask if you dont understand, so i can explain better.
Have a nice day!
$this->db->select('COUNT(*) as count, recensions.anme_id as recension_id')
->from('recensions')
->join('comments','recensions.anme_id = comments.anme_id','left')
->group_by('anme_id');
$result = $this->db->get();
Should give you the recensions id and the comment count for that id.
then loop:
foreach($result->result() as $row){
echo "Recension id $row->recension_id has $row->count comments<br />";
}
Like this??
$sql = mysql_query("SELECT * FROM recensions");
while($row = mysql_fetch_array($sql)){
$amne_id = $row{"amne_id"};
$sql2 = mysql_query("SELECT * FROM comments WHERE amne_id='$amne_id'");
$total_comments = mysql_num_rows($sql2);
echo $total_comments;
}
I don't know about the database connector you are using, but in pure SQL (assuming the connection recensions.id=comments.anme_id connection), try this:
SELECT COUNT(comments.id), anme_id
FROM recensions
LEFT JOIN comments on comments.anme_id=recensions.id
GROUP BY anme_id

MySQL Query Isnt Returning A Result

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].

Categories