I must be exhausted because I know I have done this before but I can't remember how I did or or find that snippet. I have two tables "questions" and "answers". The primary "id" from "questions" is also "id" in "answers". I'm trying to count "answers" based on "id" from that table.
<?php
$query = "SELECT * FROM questions ORDER BY id DESC";
$result = mysql_query("$query");
while($row = mysql_fetch_array($result)){
$id = $row['id'];
$date = $row['date'];
$question = $row['question'];
$time = date("U");
$likes = $row['likes'];
$query2 = "SELECT * FROM answers WHERE id = $id";
$num_rows = mysql_num_rows($query2);
print("<span style='font-size: .7em';><a href='qplusone.php?id=$id'>+1</a>
- Likes:$likes</span> $question - <a href='answer.php?id=$id&pp=$time'>answer it</a>
or <a href='answers.php?id=$id&pp=$time'>read $num_rows answers</a>
<span style='font-size: .7em';>($date)</span><br />");
}
?>
Well, first of all you never execute $query2. But even better than returning all the rows and counting them, simply return the number of rows counted by mysql.
$query2 = "SELECT count(*) FROM answers WHERE id = $id";
$result = mysql_query($q);
$row = mysql_fetch_array($result);
$count = $row['count(*)']; // $count holds the number of matching records.
To get the count of answers per question you can do this
select q.id,
count(*) as answers
from answer a
left join questions q on q.id = a.id
group by q.id
Related
I'm having an issue of retrieving values from two different tables. Here's the code so far:
$result = mysqli_query($conn,"SELECT * FROM articles");
$num = mysqli_num_rows($result);
while ($row = mysqli_fetch_array($result)) {
$uid=$row['_uid'];
$result2 = mysqli_query($conn, "SELECT _username FROM users WHERE _id = '$uid' ";
$num2 = mysqli_num_rows($result2);
while ($row2 = mysqli_fetch_array($result2)) {
$username = $row2['_username'];
}
$divtext='<h3>'.$row['_posttype'].'</h3> <h2>'.$username.' </h2>';
}
I've been reading that I should preform this while inside a while with multiple query, also found on w3 that you could directly assign a value to a variable directly using:
"SELECT _username INTO $username FROM users WHERE _id = '$uid' LIMIT 1";
But this works in SQL inside myadmin, in a php I can't find how to cast it.
I have also replace the fetch_row for fetch_assoc and still nothing, im struggling for two days already with this.
you could select al the value using a single query
SELECT a._uid , a._posttype, u._username
FROM articles a
INNER JOIN users u on a._uid = u._id
..
$result = mysqli_query($conn,
"SELECT a._uid , a._posttype, u._username
FROM articles a
INNER JOIN users u on a._uid = u._id");
$num = mysqli_num_rows($result);
while ($row = mysqli_fetch_array($result)) {
$divtext='<h3>'.$row['_posttype'].'</h3> <h2>'.$username.' </h2>';
}
$echo $divtext;
I am trying to get all the rows of results from my table 'question' where the quiz ID ($currentQuizID) is the same. My code only allows me to get a single row of data from the table, so what should I do?
$findQuiz = "SELECT QuizID FROM quiz ORDER BY QuizID DESC";
$result = mysqli_query($user->db,$findQuiz);
$iddata = mysqli_fetch_array($result);
$currentQuizID = $iddata['QuizID'];
$findQuestions = "SELECT Type, Question, Answer FROM question WHERE QuizID = '".$currentQuizID."'";
$result2 = mysqli_query($user->db,$findQuestions);
$iddata2 = mysqli_fetch_array($result2);
echo $iddata2[0];
echo $iddata2[1];
echo $iddata2[2];
Add this:
while($row = mysqli_fetch_array($result2)) {
echo $row["Type"]." ".$row["Question"]." ".$row["Answer "]."\n";
}
After getting Quiz id's Use while loop to get multiple records from question's table
$findQuiz = "SELECT QuizID FROM quiz ORDER BY QuizID DESC";
$result = mysqli_query($user->db,$findQuiz)
$totalArray = array();
while($iddata = mysqli_fetch_array($result);)
{
$currentQuizID = $iddata['QuizID'];
$findQuestions = "SELECT Type, Question, Answer FROM question WHERE QuizID = '".$currentQuizID."'";
$result2 = mysqli_query($user->db,$findQuestions);
$iddata2 = mysqli_fetch_array($result2);
$res['Type'] = $iddata2[0];
$res['Question'] = $iddata2[1];
$res['Answer'] = $iddata2[2];
array_push($totalArray,$res);
}
print_r($totalArray);
$findQuestions = "SELECT Type, Question, Answer FROM question WHERE QuizID = '".$currentQuizID."'";
$result2 = mysqli_query($user->db,$findQuestions);
$iddata_questions = array();
while($row = mysqli_fetch_array($result2)) {
$iddata_questions[] = array($row["Type"],
$row["Question"],
$row["Answer"]);
}
echo "<pre>";
var_dump($iddata_questions);
echo "</pre>;
I am not sure if the title expresses the problem accurately or not. Anyways, here is the explanation:
I have 2 tables, the first one holds users IDs, the other one holds their posts.
The fist query selects user IDs from the fist table, and it loop through the second table to find the users (IDs) posts.
The problem is that when the query finds eg. 5 results (user IDs 1, 6, 999.. etc) in the fist table, then it loops 5 times to search in the second table, it shows 5 results even if the real results is 2 post only created by user 1 and 6.
How can I avoid this repeatation?
Here is the code:
$stmt = $conn->prepare('select userid from table where para=?');
$stmt->bind_param('i', $para);
$stmt->execute();
$result = $stmt->get_result();
while( $row = $result->fetch_assoc()) {
$userid = $row["userid "];
$qname = "select postid,title from posts where uid='$userid'";
$result2 = $conn->query($qname);
$row2 = $result2->fetch_array(MYSQLI_ASSOC);
if ($row2 > 0) {
$postid= $row2['postid'];
$title= $row2['title'];
}
echo $postid." ".$title."<br>";
}
Try
$qname = "select postid,title from posts as P left join table as T on T.userid=P.uid where where para=?";
Or
You can store the results in a common array during the loop.
like
$tempResult = array();
while( $row = $result->fetch_assoc()) {
$userid = $row["userid "];
$qname = "select postid,title from posts where uid='$userid'";
$result2 = $conn->query($qname);
$row2 = $result2->fetch_array(MYSQLI_ASSOC);
if ($row2 > 0) {
$tempResult[$userid][] = $row2['postid'];
$tempResult[$userid][] = $row2['title'];
}
}
you can try this query using a JOIN MYSQL.
SELECT u.userid,p.postid,p.title FROM TABLE `user` u
JOIN posts p ON
p.uid = u.userid
WHERE para=?
You can avoid it by only running one query that joins the two tables together. Something like this:
<?php
$stmt = $conn->prepare('select posts.* from table t inner join posts p on t.userid = p.uid where t.para = ? order by uid');
$stmt->bind_param('i', $para);
$stmt->execute();
$result = $stmt->get_result();
while( $row = $result->fetch_assoc()) {
// $row now has userid, and all post details
}
?>
I'm displaying customer forms id row by row and that works fine. But I would also like to display the score of each form in the same row. How can i get the form_id from query 1 to work in query 2? I need the form_id to be able to sum the score for query 2.
I have added $WHAT-TO-PUT-HERE? in the code where I'm lost, what would be the correct way to solve this?
// get user_if from url
$user_id = $_GET['userid'];
// fetch form_id for form list
$query1 = "SELECT DISTINCT form_id FROM answers where user_id=$user_id";
$result1 = #mysqli_query($con, $query1);
while($row1 = mysqli_fetch_array($result1)) {
// get score based on form_id from query 1?
$result2 = mysqli_query($con,"SELECT SUM(answer_value) AS Poang FROM answers q JOIN questions a ON q.question_id = a.question_id WHERE form_id = $WHAT-TO-PUT-HERE? AND question_sort = 1");
while($row2 = mysqli_fetch_array($result2)) {
echo "<tr>";
echo "<td><a href='currentform?formid=" . $row1['form_id'] . "</a></td>";
echo "<td>".$row2['Poang'] ."</td></tr></table>";
}}
You need to use row1['form_id'] instead of $WHAT-TO-PUT-HERE.
In your
while($row1 = mysqli_fetch_array($result1)) {
The current result of your Select will be saved into $row1 as array, so you can access these values like a normal array.
If you give the select an alias the key of the array will have the name of the alias, else it will have the column name from the database.
You also need to concate the strings like this
$result2 = mysqli_query($con,"SELECT SUM(answer_value) AS Poang FROM answers q JOIN questions a ON q.question_id = a.question_id WHERE form_id = ".$row1['form_id']." AND question_sort = 1");
replace $WHAT-TO-PUT-HERE by $row1['form_id']
like
$result2 = mysqli_query($con, "SELECT SUM(answer_value) AS Poang FROM answers q
JOIN questions a ON
q.question_id = a.question_id
WHERE form_id = '".$row1['form_id']."' AND question_sort = 1");
This can be done with just one query:
SELECT
a.form_id,
SUM(answer_value) AS Poang
FROM
answers a
JOIN
questions q
WHERE
a.user_id = $user_id
AND
q.question_sort = 1
GROUP BY
a.form_id
Your $row1 variable contains an associative array including your database row.
There for use $row1['form_id'] or $row1[0] (column 0) to access the value
Suppose I have a while loop like:
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
}
then if first query return 5 results i.e 1-5 and second query returns 3 results than if i want to echo out second query it gives me like this..........
111112222233333
than how can i fix to 123 so that the second while loop should execute according to number of times allowed by me........!! how can i do that.........!!
I'm not sure I 100% understand your question - it's a little unclear.
It's possible you could solve this in the query with a GROUP BY clause
$sql_2 = mysql_query("SELECT id FROM secondtable WHERE id != $id GROUP BY id");
But that would only work if you need just secondtable.id and not any of the other columns.
When you say "number of time allowed by me" do you mean some sort of arbitrary value? If so, then you need to use a different loop mechanism, such as Greg B's solution.
Do you want to explicitly limit the number of iterations of the inner loop?
Have you considered using a for loop?
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
for($i=0; $i<3; $i++){
$ro = mysql_fetch_array($sql_2);
$id2 = $ro["id2"];
echo $id2;
}
}
Your first while loop is iterating over all 5 results, one at a time.
Your second while loop is iterating over each of the 5 results, producing it's own set of results (i.e. 3 results for each of the 5 iterations, totaling 15 results).
I believe what you are trying to do is exclude all IDs found in your first loop from your second query. You could do that as follows:
$sql = mysql_query("SELECT * FROM tablename");
$exclude = array();
while($row = mysql_fetch_array($sql)) {
array_push($exclude, $row['id']);
}
// simplify query if no results found
$where = '';
if (!empty($exclude)) {
$where = sprintf(' WHERE id NOT IN (%s)', implode(',', $exclude));
}
$sql = sprintf('SELECT * FROM secondtable%s', $where);
while($row = mysql_fetch_array($sql_2)) {
$id2 = $row["id2"];
echo $id2;
}
$sql = mysql_query("SELECT * FROM tablename");
$tmp = array();
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
if(!in_array($id, $tmp)) {
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
$tmp[] = $id;
}
}
Saving all queried $id's in an array to check on the next iteration if it has already been queried. I also think that GROUPing the first query result would be a better way.
I agree with Leonardo Herrera that it's really not clear what you're trying to ask here. It would help if you could rewrite your question. It sounds a bit like you're trying to query one table and not include id's found in another table. You might try something like:
SELECT * FROM secondtable t2
WHERE NOT EXISTS (SELECT 1 FROM tablename t1 WHERE t1.id = t2.id);