Pass id's to url on a count being diplayed in table - php

I have a function in which I am returning a count which when displayed is clickable. When clicked on this count the page redirects to listing of the of users with their details. The count displayed has link to the information page with id's of the users passed in URL. I am not getting the result as the link shows only one user id instead of two(as per database) or some irrelevant id's. Where I am missing the thing, any help will be highly appreciated.
function for displaying count,
function clearedmodule()
{
$id= '';
$res = mysql_query("SELECT id from tbl_users WHERE status= 1 AND type = 3 ");
while($row = mysql_fetch_array($res))
{
$query = mysql_query("SELECT DISTINCT user_id FROM tbl_user_quiz GROUP BY user_id HAVING COUNT(DISTINCT module_id) = '".$this->userQuestionModules()."' AND SUM(cleared) = 0 ");
while($row1 = mysql_fetch_assoc($query))
{
foreach($row1 as $cname => $id)
{
$id .= $row['id'].',';
}
}
}
return substr($id, 0, -1);
}
Now the <td> where the count is being displayed,
<td>Not Cleared</td>
<td>
<?php
$ids = $rep->clearedmodule();
$ids = explode(",",$ids) ;
$linkId = $rep->clearedmodule();
if($linkId)
{ ?>
<?php echo count($ids); ?>
<?php
}
else{
echo "0";
}
?> </a></td>
Using above, the URL I am getting is
reportNotCleared.php?Userid=10131183 where 1013 is right id , 1183 is not at all correct and I want them to be comma separated.

Your second query is the only query you needed. Just remove all the loops except the middle one and you should be good to go!
function clearedmodule() {
$query = mysql_query("SELECT DISTINCT user_id FROM tbl_user_quiz GROUP BY user_id HAVING COUNT(DISTINCT module_id) = '".$this->userQuestionModules()."' AND SUM(cleared) = 0 ");
while($row1 = mysql_fetch_assoc($query)){
$id .= $row1['user_id'] . ',';
}
return substr($id, 0, -1);
}

Related

The first html row is not being displayed

So, let’s say I have 10 rows in my database. However, after the mysql query, only 9 rows are being displayed in the html table.
I need every row from the database to be displayed in the html table.
I hope someone can point me in the right direction. I’ll be here if I need to provide anymore details.
This is my code:
<?php
$sqlQuery = "SELECT * FROM periods";
$result = mysqli_query($conn, $sqlQuery);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$out = $row['fell_out'];
$in = $row['fell_in'];
$sum = $row['sum'];
$nextEstimate = $row['next_estimate'];
$nextEstimateDays = $row['next_estimate_days'];
$notes = $row['notes'];
$sqlQueryLastDate = "SELECT * FROM (select * from periods WHERE id < $id ORDER BY id DESC LIMIT 1) AS x ORDER BY id LIMIT 1";
$resultLastDate = mysqli_query($conn, $sqlQueryLastDate);
$resultCheckLastDate = mysqli_num_rows($resultLastDate);
if ($resultCheckLastDate > 0) {
while ($rowLastDate = mysqli_fetch_assoc($resultLastDate)) {
$lastInDate = $rowLastDate['fell_in'];
$sqlQueryCurrentDate = "SELECT * FROM (select * from periods WHERE id = $id ORDER BY id DESC LIMIT 1) AS x ORDER BY id LIMIT 1";
$resultCurrentDate = mysqli_query($conn, $sqlQueryCurrentDate);
$resultCheckCurrentDate = mysqli_num_rows($resultCurrentDate);
if ($resultCheckCurrentDate > 0) {
while ($rowCurrentDate = mysqli_fetch_assoc($resultCurrentDate)) {
$currentOutDate = $rowCurrentDate['fell_out'];
$lastIn = new DateTime($lastInDate);
$currentOut = new DateTime($currentOutDate);
$intervalLastCurrent = $lastIn->diff($currentOut);
$elapsedLastCurrent = $intervalLastCurrent->format('%a days %h hours');
/*Why? Php is erasing everything after adding the above variable to the table...Entire first row gets erased!*/
echo "
<tr>
<td>".$id."</td>
<td class='test'>".$elapsedLastCurrent."</td>
<td class='dateOutResult'>".$out."</td>
<td class='dateInResult'>".$in."</td>
<td class='sumHours'>".$sum."</td>
<td class='nextEstimate'>".$nextEstimate." (".$nextEstimateDays.")</td>
<td class='notes'>".$notes."</td>
</tr>";
} /*$sqlQueryCurrentDate*/
}
} /*$sqlQueryLastDate*/
}
} /*$sqlQuery*/
}
?>
Here's the live result: https://unidrones.co.za/periods
I am really new to mysql/php so I do not understand what I'm doing wrong. The nested queries is probably not the best approach to use, but I'm still learning, and any input will be deeply appreciated.
This is because your query is
//select * from periods WHERE id < $id ORDER BY id DESC LIMIT 1;
your first $id will be always equal id.

Show query result in PHP

I have a query:
$string = "SELECT COUNT(id) as sponsered FROM `$database`.`$mem` where parent_id = 2 group by plan";
Which result in:
sponsored plan
2 gold
1 silver
1 mitra
This result is shown when I run this query in MySQL.
Now I want this result in PHP in an array data[] where
data[0] contains 2
data[1] contains 1
data[2] contains 1
I have tried this
$string = "SELECT COUNT(id) as sponsered FROM $database.$mem where parent_id = 2 group by plan";
$res = mysqli_query($con, $string);
while($data = mysqli_fetch_assoc($res)) {
echo $data['sponsered'];
}
But it results in data['sponsered'] containing 211
It would be better if this can be done without using any loop.
Inside the while loop assign the values to array.
$string = "SELECT COUNT(id) as sponsered FROM $database.$mem where parent_id = 2 group by plan";
$res = mysqli_query($con, $string);
$data = array();
while($result = mysqli_fetch_assoc($res)) {
$data[] = $result['sponsered'];
}
print_r($data);
Output:
data[0] contains 2
data[1] contains 1
data[2] contains 1
Your display is correct you just need a separator so the data isn't all clumped. In a browser:
echo $data['sponsered'] . "<br>";
in your loop should do it, or command line,
echo $data['sponsered'] . PHP_EOL;
should do it.
As is it throws 2, then 1, then 1 which views as 211.
Try this:
Please refrain from passing data directly into query in a prepare statement, use ? or : as deemed necessary.
Below is a sample code:
<?php
$table_name = $table; //not recommended to pass table_name as variable, unless necessary.
$parent_id = 2;
$p = $plan;
$string = "SELECT COUNT(id) as sponsered FROM $table_name where parent_id = ? group by ?";
if ($stmt = $db->prepare($string))
{
$stmt->bind_param('is', $parent_id, $p);
$stmt->execute();
$stmt->bind_result($sponsored, $plan);
$stnt->store_result();
$html ='';
while ($stmt->fetch() !== FALSE)
{
// Do what you like with the variables here, i.e. $sponsored, $plan
$html .= "<table>
<th> Sponsored </th>
<th> Plan</th>
<tr>
<td>$sponsored</td>
<td>$plan</td>
</tr>
</table>";
}
else {
die("Query failed");
}
var_dump($html);
}
?>
NOTE: If your result from your question is just an HTML (table/column), you don't need to do bind, you can just output the HTML formatted.
Use mysqli_fetch_array($result, MYSQLI_NUM) to retreive the data as numeric array

Outputting the number of records in a database column and assign it as a variable

I am wanting to count the id field in my users table in my current query and output that. How can I change my query or my output, so that if there are 40 id's in my user table with the same WHERE conditions apply, that I can output it with a variable?
$member = mysqli_query($con,"SELECT * FROM users WHERE `group` IN (2, 3, 4, 5) ORDER BY id DESC LIMIT 1");
$numrows_member = mysqli_num_rows($member);
if($numrows_member > 0){
while($row_member = mysqli_fetch_assoc($member)){
$memberid = $row_member['id'];
$member_username = $row_member['username'];
}
} else {
$no_members = "No Members Found...";
}
Try this code :
Warning : also rename group column because group is reserve keyword of mysql database in example i renamed it as groupid.
<?php
$member = mysqli_query($con,"SELECT * FROM users WHERE `groupid` IN (2, 3, 4, 5) ORDER BY id DESC LIMIT 1");
$numrows_member = mysqli_num_rows($member);
if($numrows_member > 0){
$totalRecord=null;
while($row_member = mysqli_fetch_assoc($member)){
$memberid = $row_member['id'];
$member_username = $row_member['username'];
$group_id = intval($row_member['groupid']);
if($group_id > 0){
$totalRecord = getTotalRow($con,$group_id);
}
}
echo 'ID : '.$memberid.' UserName : '.$member_username. ' Total records : '.$totalRecord;
} else {
echo $no_members = "No Members Found...";
}
function getTotalRow($con,$id){
$record=0;
$result = mysqli_query($con,"SELECT count(id) as total FROM users WHERE groupid = $id ");
while($row = mysqli_fetch_row($result)){
echo $record = $row[0];
}
return $record;
}
?>

select fields and group them in a category in php and mysql

i have a table with staff_id and subjects, i want to display all staffs according to their subjects.
my table
result i want
Physics
-001
-004
-006
Chemistry
-002
-009
Biology
-003
-008
Mathematics
-005
My code
$q = mysql_query("Select staff_id from my_table");
while($row = mysql_fetch_array($q)){
echo $subject .'</br>';
echo $staff_id.'</br>';
}
but this doesn't give the result i want.
any help?
What you need is ORDER BY.
Change your query to:
SELECT STAFF_ID, SUBJECT FROM my_table ORDER BY SUBJECT, STAFF_ID
So you get the records in the right order to work with them.
Something like this?
$q = mysql_query("SELECT `staff_id`, `subject` FROM `my_table`;");
$data = array();
while($row = mysql_fetch_array($q)){
$data[$row['subject']][] = '-'.$row['staff_id'];
}
print_r($data);
Or to echo out the rows
foreach($data as $heading => $rows){
echo $heading.'<br>';
foreach($rows as $row){
echo $row.'<br>';
}
}
You can write your code like this below:
$q = mysql_query("SELECT * FROM my_table ORDER BY SUBJECT, STAFF_ID");
while($row = mysql_fetch_array($q)){
//Do staff
}
The following code should help. You should split each subject into a separate array within your query. Once your query is complete, you should iterate through the subject array, and then within each staff id.
$subjects = array();
$q = mysql_query("Select staff_id from my_table");
while($row = mysql_fetch_array($q)){
if ($subjects[$row['SUBJECT']] == nil) {
$subjects[$row['SUBJECT']] = array();
}
array_push($subjects[$row['SUBJECT']], $row['STAFF_ID']);
}
foreach ($subjects as $key=>$value) {
echo $key . '<br>;
foreach ($vaue as &$staff) {
echo $staff . '<br>';
}
}
$result=mysql_query("SELECT * from table GROUP BY subject");
while($ext=mysql_fetch_object($result)) {
$query=mysql_query(" SELECT * from table WHERE subject='".$ext->subject."'");
echo $ext->subject;
while($res=mysql_fetch_object($query)) {
echo $res->staff_id;
}
}

how can i controll while loop into another while loop

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);

Categories