mysql_query returning wrong result - php

Consider the following code
if ( isset( $_SESSION['FBID'] ) ) {
$uid = $_SESSION['FBID'];
$sql = "SELECT *, count(member_nr) AS notifyMe
FROM poolWinners
WHERE member_nr = '$uid' AND notification ='1'";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result)){
$notification = $row['notifyMe'];
}//while
if ( $notification > 0 ) {
echo '<span class="badge">' . $notification . '</span>';
} //if
var_dump($notification);
} //isset( $_SESSION['FBID'] )
The above script returns how many notifications a member has as you can see in image below
My Problem
The script is returning the wrong result (wrong number of notifications). Have a look at the table below, the member number appears 3 times in the table so:
$notification = $row['notifyMe'] Should = 3 AND NOT 1
What am I missing or doing wrong here? Thanks for reading

Use
$sql = "SELECT *, count(*) AS notifyMe
FROM poolWinners
WHERE member_nr = '$uid' AND notification ='1'";
Notice count(*) , it will fetch how many records are matching criteria.
And initialize $notification = 0; at the start.

Have you tried approaching it from this angle
$sql = "SELECT * FROM poolWinners WHERE member_nr = '$uid' AND notification ='1'";
$result = mysql_query($sql);
$notification = array();
while($row=mysql_fetch_array($result)){
$notification[] = $row['notifyMe'];
}
//an array count on notification should give you the number of elements in the array i.e those that matched the query
$total_count = count($notification);

In your code the notification will be always one, since it will take only the notifyMe field of last row in the result set.
If you want to get number of notifications, try this
if ( isset( $_SESSION['FBID'] ) ) {
$uid = $_SESSION['FBID'];
$sql = "SELECT *, count(member_nr) AS notifyMe
FROM poolWinners
WHERE member_nr = '$uid' AND notification ='1'";
$result = mysql_query($sql);
$notification = 0;
while($row=mysql_fetch_array($result)){
$notification++;
/*
OR $notification += $row['notifyMe'];
*/
}//while
if ( $notification > 0 ) {
echo '<span class="badge">' . $notification . '</span>';
} //if
var_dump($notification);
} //isset( $_SESSION['FBID'] )

$sql = "SELECT *
FROM poolWinners
WHERE member_nr = '$uid' AND notification ='1'";
$result = mysql_query($sql);
$notification = mysql_num_rows($result);

$sql = "SELECT * FROM poolWinners WHERE member_nr = '$uid' AND notification ='1'";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
echo "Toal notification".mysqli_num_rows($result);
}
mysqli_close($con);
?>

Related

ranking of student position based on their percentage scores

I use this code below to determine the position of each student result based on the percentage score of their subject, the program assigned their position as (1st, 2nd, 2nd, 4th ...)
My challenge now is that whenever the percentage score is 100, the system position the student as last in the class instead of 1st position.
Below is the code:
<?php
session_start();
include("DB/config.php");
ini_set('max_execution_time', 1000000);
$class_arm= $_SESSION['clas'];
$queris = "select * from setup";
$result3 = mysqli_query($con,$queris) or die(mysqli_error($con));
$rws3 = mysqli_fetch_assoc($result3);
$ses3=$rws3['section'];
$term3=$rws3['term'];
$query_sj = "SELECT subj FROM sec_result where class='$class_arm' and year='$ses3' and term='$term3' and tsc<>'' and tsc is not null and tsc <> '0'";
$result_sj = mysqli_query($con,$query_sj) or die(mysqli_error($con));
while($row_sj = mysqli_fetch_array($result_sj)){
$query = "SELECT distinct studid,subj,tsc FROM sec_result where class='$class_arm' and year='$ses3' and term='$term3' and subj='".$row_sj['subj']."' ORDER BY tsc DESC";
$result = mysqli_query($con,$query) or die(mysqli_error($con));
/*$row2 = mysqli_fetch_array( $result );
echo $row2['tsc'];
exit;*/
if( !$result ){
echo 'SQL Query Failed';
}else{
$rank = 0;
$last_score = false;
$rows = 0;
while( $row = mysqli_fetch_array( $result ) ){
$rows++;
if( $last_score!= $row['tsc'] ){
$last_score = $row['tsc'];
$nuval = $row['tsc'];
$rank = $rows;
}
mysqli_query($con,"UPDATE sec_result SET pos = '$rank' where studid='".$row['studid']."' and year='$ses3' and term='$term3' and subj='".$row_sj['subj']."'") or die(mysqli_error($con));
}
}
}
?>
My expectation is that the student that scores 100 percent should be given the first position.
Please, I need your help to resolve this, Thanks.
My expectation is that the student that scores 100 percent should be given the first position.

Unable to get key value from a mysql multi-dimensional array

I am trying to get the key value from the multidimensinal array which I have created using .The Array snapshot is given after the Code.
Below is my PHP code-
$selectTicket = "select ticketID from ticketusermapping where userID=$userID and distanceofticket <=$miles;";
$rsTicket = mysqli_query($link,$selectTicket);
$numOfTicket = mysqli_num_rows($rsTicket);
if($numOfTicket > 0){
$allRowData = array();
while($row = mysqli_fetch_assoc($rsTicket)){
$allRowData[] = $row;
}
$key = 'array(1)[ticketID]';
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (".implode(',', array_keys($key)).")";
Array Snapshot-
I need the tickedID value from this array . Like the first one is 49 .
Please help.
change your code like
$selectTicket = "select ticketID from ticketusermapping where userID=$userID and distanceofticket <=$miles;";
$rsTicket = mysqli_query($link, $selectTicket);
$numOfTicket = mysqli_num_rows($rsTicket);
if ($numOfTicket > 0) {
$allRowData = array();
while ($row = mysqli_fetch_assoc($rsTicket)) {
$allRowData[] = $row['ticketID'];
}
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (" . implode(',', $allRowData) . ")";
$ids = array_column( $allRowData, 'ticketID'); //this will take all ids as new array
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (".implode(',', $ids).")";
You should do a single query using JOIN for this:
$query = "
SELECT t.*
FROM ticket t
JOIN ticketusermapping tum
ON t.ticketID = tum.ticketID
AND tum.userID = '$userID'
AND tum.distanceofticket <= '$miles'
";
$stmt = mysqli_query($link, $query);
$numOfTickets = mysqli_num_rows($stmt);
while($row = mysqli_fetch_assoc($stmt)){
var_dump($row); // here will be the ticket data
}

how to execute multiple count query in php

I executed 4 count queries from one table. but I am getting the same output from all the queries. but the actual value is different in the table.
Here is my table.
ID || notify_type || status
__________________________________________
1 || resume_uploaded || 1
Here are my queries:
$notify_query1 = "select count(*) from notify where status = 1 and notify_type = 'resume_uploaded'";
$row1 = mysqli_query($db_manager->connection,$notify_query1);
$rcount = mysqli_num_rows($row1);
$notify_query2 = "select count(*) from notify where status = 1 and notify_type = 'detail_filled'";
$row2 = mysqli_query($db_manager->connection,$notify_query2);
$dcount = mysqli_num_rows($row2);
$notify_query3 = "select count(*) from notify where status = 1 and notify_type = 'job_detailed'";
$row3 = mysqli_query($db_manager->connection,$notify_query3);
$jcount = mysqli_num_rows($row3);
$notify_query4 = "select count(*) from notify where status = 1 and notify_type = 'msg_sent'";
$row4 = mysqli_query($db_manager->connection,$notify_query4);
$mcount = mysqli_num_rows($row4);
I am getting output 1 from all the four queries:
Please help me.
Use fetch_row() instead mysqli_num_rows().
$result = $db->query("select count(*) from notify where status = 1 and notify_type = 'resume_uploaded'");
$row = $result->fetch_row();
echo 'No of count: '. $row[0];

Random row selection using MySQL returns NULL

I am trying to get a random row from MySQL table but all three attemps:
$query = "SELECT cid FROM table LIMIT 1 OFFSET ".rand(1,$num_rows);
$query = "SELECT cid FROM table OFFSET RANDOM() * (SELECT COUNT(*) FROM table) LIMIT 1";
$query = "SELECT * FROM table ORDER BY RAND() LIMIT 1";
give a NULL result in mysql_query($query).
Higher up my PHP code I obtain a row from the same table OK by specifying WHERE, so I don't understand why I can't retrieve a random one.
Here is the code snippet:
$query = "SELECT uid,clu FROM uable WHERE un = '$un'";
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$resultid = mysql_fetch_assoc($result);
$uid = $resultid['uid'];
file_put_contents('debugging.txt',__LINE__.' - $uid = '.var_export($uid,true).PHP_EOL,FILE_APPEND);
$query = "SELECT * FROM table WHERE uid = $uid AND cn = '$cn'";
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$cr = mysql_fetch_assoc($result);
$cid= $cr['cid'];
file_put_contents('debugging.txt',__LINE__.' - $cid= '.var_export($cid,true).PHP_EOL,FILE_APPEND);
$query = "SELECT * FROM fable WHERE cid= '$cid'";
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
file_put_contents('debugging.txt',__LINE__.' - $result = '.var_export($result,true).PHP_EOL,FILE_APPEND);
$fr = mysql_fetch_assoc($result);
file_put_contents('debugging.txt',__LINE__.' - $fr = '.var_export($fr,true).PHP_EOL,FILE_APPEND);
echo '<form action="'.$_SERVER['PHP_SELF'].’" method="post">';
if (!$fr) {
$o= $cn;
while ($o= $cn) {
// $ac = mysql_query("SELECT * FROM table") or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
// $num_rows = mysql_num_rows($ac);
//file_put_contents('debugging.txt',__LINE__.' - $num_rows = '.$num_rows.PHP_EOL,FILE_APPEND);
// --$num_rows;
// $query = "SELECT cid FROM table LIMIT 1 OFFSET ".rand(1,$num_rows);
$query = "SELECT cid FROM table OFFSET RANDOM() * (SELECT COUNT(*) FROM table) LIMIT 1";
// $query = "SELECT * FROM table ORDER BY RAND() LIMIT 1";
$resultid = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$opr = mysql_fetch_assoc($resultid);
$o= $opr['cn'];
}
file_put_contents('debugging.txt',__LINE__.' - $query = '.$query.PHP_EOL,FILE_APPEND);
file_put_contents('debugging.txt',__LINE__.' - $resultid = '.var_export($resultid,true).PHP_EOL,FILE_APPEND);
file_put_contents('debugging.txt',__LINE__.' - $op[\'cid\'] = '.$op['cid'].PHP_EOL,FILE_APPEND);
$query = "SELECT * FROM table WHERE cid= ".$op;
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$opr = mysql_fetch_assoc($opr);
$o= $opr['cn'];
$od= $opr['description'];
echo '<p>'.$op;
if ($od<> '') {
echo ','.$odesc;
}
echo '</p>';
echo '<input type="submit" name="continue" id="continue" value="Continue">';
} else {
echo '<p>'.$fr['p'].'</p>';
echo '<input type="submit" name="continue" id="continue" value="Continue">';
}
echo '</form>';
The resulting debugging.txt:
24 - $uid = '4'
29 - $cid = '21'
32 - $result = NULL
34 - $fr = false
These queries look OK, but I think you're starting at the wrong place. When you're uncertain how to frame something in SQL, open up a SQL client like SequelPro or Navicat and try writing a few queries by hand until you get the result you want. (Also this gives you a chance to double-check the contents of relevant tables and ensure the expected data are there.) Then you can go back into the PHP with full confidence that the SQL code is correct, so if there's a problem it must be with the PHP (either the variables you inject into a Mysql statement, or the way you call that statement).

Order MySQL inbox by newest conversation first?

I've a MySQL/PHP code for a private messaging system that I built. It works great although I'm fairly new to it all so struggling to get the message threads to display by newest first. Is there any chance you could offer advice? The current code is as follows:
$result = '';
$nowTime = time();
$getmessages = mysql_query("SELECT * FROM messages WHERE msg_to = '$session_memberid' GROUP BY msg_from ORDER BY ID DESC");
while($iamessages = mysql_fetch_array($getmessages))
{
$msg_id = $iamessages['ID'];
$msg_from = $iamessages['msg_from'];
$msg_conversation = $iamessages['conversation'];
$getmsgdata = mysql_query("SELECT * FROM messages WHERE msg_to = '$session_memberid' AND msg_from = '$msg_from' ORDER BY ID DESC LIMIT 1");
while($imsd = mysql_fetch_array($getmsgdata))
{
$msg_message = $imsd['msg_message'];
$msg_time = $imsd['time'];
$msg_read = $imsd['msg_read'];
}
$msg_conversation = suitcrypt($msg_conversation);
if ( $msg_read == 'no' ) { $msgclass = "messagepostunread"; } else { $msgclass = "messagepost"; }
$getfromdata = mysql_query("SELECT FullName, Username, status FROM members WHERE ID = '$msg_from'");
while($ifd = mysql_fetch_array($getfromdata))
{
$msg_from_name = $ifd['FullName'];
$msg_from_username = $ifd['Username'];
$msg_from_status = $ifd['status'];
}
$getfromdata1 = mysql_query("SELECT Link FROM images WHERE MemberID = '$msg_from' AND is_primary = 'yes'");
while($ifd1 = mysql_fetch_array($getfromdata1)) {
$msg_from_img = $ifd1['Link'];
}
$timepass = timing($msg_time);
if ( $timepass == 'data' ) {
$timepass = date("dS M", $msg_time);
}
if ( ( $msg_from_status == 'full' ) || ( $msg_from_status == 'active' ) ) {
$result .= "
<div class=\"$msgclass\" onclick=\"showconversation('$msg_conversation');\">
<img src=\"m/members_image/$msg_from/thumb-$msg_from_img\" class=\"feedpic\" width=\"55\" height=\"55\" /><div class=\"messageposttext\">$msg_from_name:<div class=\"inboxfeedreply\">Reply · $timepass</div><br />$msg_message</div>
</div>
<div class=\"splittermessages\"></div>
";
}
Within each table entry in the messages table there is a 'time' stamp. Here's an example of the time entries: 1367680391. What's the best way to order the threads by newest reply first?
First off I think you should group by $msg_conversation and find the last date on each conversation. With the code below you have the conversatons ordered by the last message each conversation/thread had.
$result = '';
$nowTime = time();
$getmessages = mysql_query("SELECT conversation, max(date) FROM messages WHERE msg_to = '$session_memberid' GROUP BY conversation ORDER BY max(date)");
while($iamessages = mysql_fetch_array($getmessages))
{
$msg_conversation = $iamessages['conversation'];
...
Further on you can get the messages for each conversation by date descending.
I got someone to help and the answer was to update the query to the following:
$getmessages = mysql_query("SELECT * FROM messages WHERE msg_to = '$session_memberid' GROUP BY msg_from ORDER BY MAX(time) DESC");

Categories