Using multiple while loops getting only 1 record - php

I am just starting to learn php, so bear with me...
I am trying to get a list of employees from a list of supervisors.
I am only getting the last supervisor ..
I am guessing that it is because I have the code in the wrong places..
Here is the code I have so far..
//Get List of Supervisors
$result_supervisors = mysql_query("SELECT emp_no as semp_no, full_name as sfull_name,employee_email as s_email FROM employees where supervisor = '1' ORDER BY emp_no");
// Initializes Supervisor Array
$supervisors = array();
while($row = mysql_fetch_array($result_supervisors, MYSQL_ASSOC))
{
$supervisor = $row['semp_no'];
$supervisor_name = $row['sfull_name'];
$supervisor_email = $row['s_email'];
//add row to supervisors array
$supervisors[] = array($supervisor, $supervisor_name, $supervisor_email);
}
//Get employee for the supervisor
$empquery = "SELECT emp_no, full_name, review_date,employee_email as e_email FROM employees where review_date < curdate() and employment_status !='2' and emp_supervisor = ". $supervisor ;
$empresult = mysql_query($empquery);
while($emprow = mysql_fetch_array($empresult))
{
if ($emprow['cnt'] == '0')
{
// no records for supervisor
}
else
{
$emp_no = $emprow['emp_no'];
$full_name = $emprow['full_name'];
$e_email = $emprow['e_email'];
$review_date = $emprow['review_date'];
//add row to employees array
$employees[] = array($supervisor, $supervisor_name, $supervisor_email,$emp_no,$full_name,$e_email,$review_date);
}
}
print_r($employees);
I am trying to put the results into an html table and email it to the supervisor for the end result..
But getting more than one supervisor is my biggest issue..
Is there an easy way to put the data into an html table.. in case someone knows why only one supervisor is being done...
Any help that can help a newbie?
KD

Change your first query:
$result_supervisors = mysql_query("SELECT emp_no as semp_no, full_name as sfull_name,employee_email as s_email FROM employees ORDER BY emp_no");

Try this code :
//Get List of Supervisors
$result_supervisors = mysql_query("SELECT emp_no as semp_no, full_name as sfull_name,employee_email as s_email FROM employees where supervisor = '1' ORDER BY emp_no");
// Initializes Supervisor Array
$supervisors = array();
$employees = array();
while($row = mysql_fetch_array($result_supervisors, MYSQL_ASSOC))
{
$supervisor = $row['semp_no'];
$supervisor_name = $row['sfull_name'];
$supervisor_email = $row['s_email'];
//add row to supervisors array
$supervisors[] = array($supervisor, $supervisor_name, $supervisor_email);
//Get employee for the supervisor
$empquery = "SELECT emp_no, full_name, review_date,employee_email as e_email FROM employees where review_date < curdate() and employment_status !='2' and emp_supervisor = ". $supervisor ;
$empresult = mysql_query($empquery);
while($emprow = mysql_fetch_array($empresult))
{
if ($emprow['cnt'] == '0')
{
// no records for supervisor
}
else
{
$emp_no = $emprow['emp_no'];
$full_name = $emprow['full_name'];
$e_email = $emprow['e_email'];
$review_date = $emprow['review_date'];
//add row to employees array
$employees[] = array($supervisor, $supervisor_name, $supervisor_email,$emp_no,$full_name,$e_email,$review_date);
}
}
}
print_r($employees);

Related

Approach and Algorithm for checking availability for schedule using PHPmyadmin and SQL

UPDATED
I'm trying to create a basic schedule for all students in their final year to present their final project to 2 supervisors. I have successfully created a schedule with no constraints but now i need to create a schedule based on the supervisors availability.
Here is a detailed description of the problem.
A student is assigned a supervisor and a supervisor will supervise more than one student. The supervisor also teaches classes during the day. Now i need to create a schedule for all of the students to present to their supervisor and one additional supervisor that supervises other students. (for the moment I'm focusing on the supervisors that are assigned to the student and not the second one until i get it working.
I want to compare the supervisors availability for the slots time if they're free then assign them to the slot and then update the availability of that time to false to avoid double booking using a PHP sql query.
so...
What i have done so far:
// get all of the Slots.
$sql = "SELECT Slot_ID FROM slot WHERE StartTime < '18:00:00'";
$result = mysqli_query($con, $sql);
$DayTimeSlots = array();
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$DayTimeSlots [] = $row;
}
}
// Store slots into simple array
function extractSlotId($DayTimeSlots){
return $DayTimeSlots['Slot_ID'];
}
$slots = array_map("extractSlotId",$DayTimeSlots);
// SHOW SLOTS
foreach ($slots as $slotID) {
echo " SlotID: = $slotID <br>";
}
// Get All students
$sql = "SELECT Student_ID FROM student WHERE PartTime =0";
$result = mysqli_query($con, $sql);
$FullTimeStudents = array();
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$FullTimeStudents [] = $row;
}
}
// Store into a simple array
// Extract student id and Supervisor_ID
function extractStudentId($FullTimeStudents){
return $FullTimeStudents['Student_ID'];
}
$students = array_map("extractStudentId",$FullTimeStudents);
// Combine the Slot and Students array
$min = min(count($FullTimeStudents), count($DayTimeSlots));
$result = array_combine(array_slice($students , 0, $min), array_slice($slots, 0, $min));
foreach($result as $key=>$value){ // $Key = Student_ID, $value = Slot_ID
echo " $key : $value ";
// get supervisor ID
$sql = "select Supervisor_ID FROM student where Student_ID = $key";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_array($query);
$SuperID = $row['Supervisor_ID'];
echo "SuperID : $SuperID ";
// get slotID
$sql = "select Date, StartTime FROM Slot where Slot_ID = $value";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_array($query);
$Date = $row['Date'];
$StartTime = $row['StartTime'];
echo "Slot Date : $Date Start Time : $StartTime ";
// get Date id
$sql = "select Date_ID FROM dates where Date = '$Date'";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_array($query);
$DateID = $row['Date_ID'];
echo "Date ID : $DateID ";
// Check if the supervisor is available
$sql = "select `$StartTime` FROM supervisor_availability where Date_ID = $DateID AND Supervisor_ID = $SuperID";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_array($query);
$Available = $row["$StartTime"];
echo "Is the Lecture Available? : $Available ";
$Time = "`$StartTime`";
if($Available == 1){
$sql = "INSERT INTO student_slot (Student_ID, Slot_ID) VALUES ($key, $value)";
$result = mysqli_query($con, $sql);
$sql = "UPDATE `supervisor_availability` SET $Time = '0' WHERE `supervisor_availability`.`Supervisor_ID` = $SuperID AND `supervisor_availability`.`Date_ID` = $DateID" ;
$result = mysqli_query($con, $sql);
} else if ($Available == 0) {
// Not sure what to do here.
// Can i make the Slot it's currently checking go to the end of the
// array for a different student and then check the next slot and come
// back to it.
}
}
I'm using echo for debugging.
The algorithm works fine if the Supervisor is available, it assigns it correctly and then updates the Supervisors availability for that time slot
Just need help with how to handle it if they're not available.
Any help or advice would be appreciated.
Supervisor_Availability Slot Table Student Table Date Table DB_Structure

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
}

mysql_fetch_array only running once, should be six

I can see in my logcat that the $check query is only running once, when it should be running once for every result of the $result query, which is 6. I've been troubleshooting this for hours and I just can't figure out why it's not working properly.
Is there an obvious reason why $check is only running once?
$result = mysql_query("SELECT * FROM `posts` WHERE facebook_id = $fbid ORDER BY id DESC") or die(mysql_error());
while ($row1 = mysql_fetch_array($result))
{
$mytime = $row1['time'];
$mylat = $row1['latitude'];
$mylon = $row1['longitude'];
$mypostid = $row1['id'];
// get all products from products table
$check = mysql_query("SELECT facebook_id as fid, id as uid,
TIMESTAMPDIFF(SECOND, `time`, '$mytime') AS timediff
FROM `posts`
WHERE `facebook_id` != $fbid
HAVING `timediff` <= '180'
ORDER BY `time` DESC") or die(mysql_error());
if (mysql_num_rows($check) > 0)
{
$response["products"] = array();
while ($row = mysql_fetch_array($check))
{
// temp user array
$product = array();
$product["facebookid"] = $row["fid"];
$product["timediff"] = $row["timediff"];
$product["theirpostid"] = $row["uid"];
$product["mypostid"] = $mypostid;
// push single product into final response array
array_push($response["products"], $product);
}
}
}
$response["success"] = 1;
echo json_encode($response);
I guess this is because you set
$response["products"] = array();
inside every cycle. Move it out of this inner while.

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

problem of while loop and array

$result=array();
$table_first = 'recipe';
$query = "SELECT * FROM $table_first";
$resouter = mysql_query($query, $conn);
while ($recipe = mysql_fetch_assoc($resouter, MYSQL_ASSOC)){
$result['recipe']=$recipe;
$query2="SELECT ingredients.ingredient_id,ingredients.ingredient_name,ingredients.ammount FROM ingredients where rec_id = ".$recipe['rec_id'];
$result2 = mysql_query($query2, $conn);
while($ingredient = mysql_fetch_assoc($result2)){
$result['ingredient'] = $ingredient;
}
echo json_encode($result);
}
this code show me all the recipes but only the last ingredients i.e
{"recipe":{"rec_id":"14","name":"Spaghetti with Crab and Arugula","overview":"http:\/\/www","category":"","time":"2010-11-11 14:35:11","image":"localhost\/pics\/SpaghettiWithCrabAndArugula.jpg"},"ingredient":{"ingredient_id":"55","ingredient_name":"test","ammount":"2 kg"}}{"recipe":{"rec_id":"15","name":"stew recipe ","overview":"http:\/\/www","category":"","time":"2010-11-11 14:42:09","image":"localhost\/pics\/stew2.jpg"},"ingredient":{"ingredient_id":"25","ingredient_name":"3 parsnips cut into cubes","ammount":"11"}}
i want to output all the ingredient records relevant to recipe id 14 and this just print the last ingredient.
$result['ingredient'] = $ingredient;
Is replacing the variable $result['ingredient'] with the most recent $ingredient value each time, culminating with the last value returned, you should use:
$result['ingredient'][] = $ingredient;
To incrememnt/create a new value within the $result['ingredient'] array for each $ingredient. You can then output this array according to your needs. Using print_r($result['ingredient']) will show you its content...to see for yourself try:
while($ingredient = mysql_fetch_assoc($result2)){
$result['ingredient'][] = $ingredient;
}
print_r($result['ingredient']);
If I understand correctly what you want to do, there is a way to optimize the code a lot, by fetching recipes and ingredients in one single query using a JOIN :
$recipes = array();
$recipe_ingredients = array();
$query = "SELECT * FROM recipe LEFT JOIN ingredients ON ingredients.rec_id=recipe.rec_id ORDER BY recipe.rec_id DESC";
$resouter = mysql_query($query, $conn);
$buffer_rec_id = 0;
$buffer_rec_name = "";
$buffer_rec_cat = "";
while( $recipe = mysql_fetch_array($resouter) )
{
if( $buffer_rec_id != $result['recipe.rec_id'] )
{
$recipes[] = array( $buffer_rec_id, $buffer_rec_name, $buffer_rec_cat, $recipe_ingredients);
$recipe_ingredients = array( );
$buffer_rec_id = $result['recipe.rec_id'];
$buffer_rec_name = $result['recipe.rec_name'];
$buffer_rec_cat = $result['recipe.rec_category'];
}
else
{
$recipe_ingredients[] = array( $result['ingredient_id'], $result['ingredient_name'], $result['ammount'] );
}
}
$print_r($recipes);
This code should give you a multi-dimensional array that you can use later to get the data you want.
I let you adapt the code to have exactly the information you need.

Categories