force a pointer to reset on postgres result array - php

I am attempting to make a calendar for my salesman of what sort of clients they have lined up for the week.
There is a table that I have that stores each lined up client as an entry.
I have an SQL statement that scoops all this up and I am trying to get a layout that looks like:
Monday | Tuesday | Wednesday | Thursday | Friday
And then I want to dump all the entries as divs under each of this columns in the table.
The sql data is not grouped by day, so it will return something like:
array("Monday","Joe blow"); // index 0
array("Monday","Sally Smith"); // index 1
and so on.
I have this placed right after the result is retrieve from the statement:
while ($row = pg_fetch_array($result,null,PGSQL_ASSOC) {
}
And this iterates through each row.
However what happens when I need to dump more than one row under a single column?
I was thinking some code along the line of:
while ($row = pg_fetch_array($result,null,PGSQL_ASSOC)) {
while ($row['day']=="Monday") {
echo '<div>'.$row['client_name'].'</div>';
}
while ($row['day']=="Tuesday") {
echo '<div>'.$row['client_name'].'</div>';
}
}
however that didn't go anywhere as it seems to return true everytime it hits "Thursday" because the pointer hasn't reset on the original while loop to fetch the next record.
I am trying to figure out a clean way to set the pointer to the next record and start again at the original while loop.
Anybody got an idea on this??
Thanks a million!

I found it!
The function to use is pg_result_seek() as covered in here
Thank you rjdown!

Related

How to remove a row from result_array() with CodeIgniter

Background
I am creating a ranking system which retrieves a bunch of records to compare their grades, put it on rank and delete that record for the next comparison. However, I'm having trouble on how to delete the record I tried unset() but it does not seems to work either.
Question
This the code that I'm using. Please take note that this is just pseudo-code of what we are doing and is not the actual code just to avoid confusions from the question. Take a look at this code:
// Retrive all the student records with grades.
$students = $this->grades->RetrieveRecords();
// Occupy slot.
$iterator=0;
$highest_index =0 ;
for($i=0;$i<5;$i++){
// Search student for rank $i.
foreach($students as $student)
{
// Some comparisons
// consider we found the highest yet.
if($highest<$student['grade']){
// Store which index it is, because it will be deleted
// on the next cycle if this $student['grade'] is indeed the highest on this cycle.
$highest_index = $iterator;
}
$iterator+=1;
}
// After getting the highest for rank $i. Delete that current record
// from $students so on next cycle, it will be removed from the comparison.
$unset($students[$highest_index]); // Does not work, any alternative? - Greg
// Reset the foreach iterator for next comparison cycle.
$iterator=0;
The $unset($students[$highest_index]); is the one we need to do the job but doesn't. We just need to delete a specific record from result_array() which is the $students. For now we ran out of alternatives and still searching across the internet/documentations. However, I'll just leave this here for some help.
We will also update this if ever we got a solution for the few hours.
you can use array_filter:
$students = array_filter($students, function($student) use($highest)
{
return $student['grade'] < $highest;
});

How to perform a looping check on date/time mysql field for time values NOT equal to "00:00"?

I have a mysql table called "dobs" with a field called "dob" that is a date/time field. So examples in that field could be:
2010-09-24 01:01:00
2008-09-24 00:00:00 (this means no time was entered, only a date. I don't allow midnight to avoid confusion. If user tried to enter midnight, it would put "00:01:00" there)
I need to loop through all the fields and check to see if any of the TIME portions of that field is anything other than "00:00:00".
If just one of them has something other than "00:00:00" then I want the loop to stop because I now know what I need to know.
Here is what I have so far:
$sql = "SELECT dob FROM dobs";
$getdobs= mysqli_query($connection, $sql);
if (!$getdobs) {
die("Database query failed: " . mysqli_error($connection));
} else {
while ($row = mysqli_fetch_array($getdobs)) {
if (date("H:i", strtotime($row['dob'])!=="00:00") {
//stop loop and set $times=yes
$times="yes";
break;
} else {
//keep looping to look at next one
$times="no";
}
}
}
Now I can check $times for either yes or no to do further things I need to do. This code above works, I just worry that it's not the most efficient way to go about it. Two questions:
Did I "stop" the loop properly with "break"?
Is there a clearly more efficient way to perform this type of check?
Your code is spot on. Break is the correct reserve word to stop a loop. If your going to continue loop when the if statement isn't satisfied you can remove the else statement because it is irrelevant unless it never finds a date that is not 00:00 from the last row. Hope that helps.

Output MySQL query in HTML table cell with PHP

I'm working in the IT department of my company and it is my responsibility to send daily reports of the calls registered in the Call Center department. I'm new with MySQL, PHP or HTML and I'm already facing my first problems.
My objective is to run some queries in PHP and then output them in a HTML table cell. Let me be more specific. I have access to a telephone record database and I need to count the number of total calls and lost calls of every branch daily. Right now I just run 2 queries in MySQL and then copy-paste them in a .xls table.
I have the right queries, I get the right result in mysql, even in PHP I get the result posted on the webpage (kind of), but I don't know how to create a table, or how to input the result of a query into a specific cell of the table.
Here's what I've got so far:
<?php
$conn=#mysql_connect('host', 'username', 'password', 'asteriskcdrdb.cdr');
echo ('total calls ROPCW: ');
$result=mysql_query('select count(*) from asteriskcdrdb.cdr where calldate like "2016-04-11%" and dst="020" and disposition="ANSWERED" and duration > "10" ');
echo mysql_result($result, 0);
mysql_close($conn);
?>
This code will post on my page the count of total calls made on 4.11.2016 like this:
total calls ROPCW: 369
My objective is to create a table like this:
So the result of that query I mentioned above would go on the ROPCW->Total cell (where is 305) on the left side, on the right side are the monthly reports so far.
You can work out one big query or use a view to gather the data you need from a single source. Other suggestion would be, looping through all your branches and gather all the data you need, to build an associative array indexed similar to this:
$records[branch] = [date => [total => x, lost => y], mtd => [total => X, lost => Y]];
Then just do a:
foreach ($records as $branch => $record)
{
echo string to build table row
}
I suggest use mysql_fetch_object or mysql_fetch_assoc functions instead of mysql_result. Basically because those functions fetch an entire row instead of one single cell value. For your example query works fine because your aggregate function returns only one cell and row. But for your desired output won't work.
Keep in mind that you can inject HTML code within PHP and vice versa. Just do something like:
The idea would be run a select * from yourTable;
Then,
$result = mysql_query($sql);
echo "<table>\n";
echo "<tr><th>Branch</th></tr>\n";
while ($callRecord = mysql_fetch_object($result)) {
echo "<tr><td>{$callRecord->branch}</td></tr>\n";
}
echo "</tr>\n";
echo "</table>\n";
That should output a list of all tour branches. this is a guideline.
Hope this helps!!
You can go to www.php.net and choose between mysql_fetch functions which one will work better for you.

Echo'ing a piece of the phpMyAdmin database in wordpress

I have a wordpress toggle function that toggles a status depending on the value in the wp_database. The user basically has the option to report sick and to report healthy. When the user reports sick i want a piece of tekst to echo out the date stored in the database. So if for example i reported myself sick on the 1st of December 2014 i want to echo out that date. The code i have so far is listed below.
$date = $wpdb->get_results( "SELECT sick FROM ziekbeter WHERE person =
$user_ID AND healthy IS NULL" );
$status="You reported sick on DATE.";
Image being the 'ziekbeter' table in my database. I know for a fact that the array it echo's only contains a single date.
Lets say that we're person 2 and we take a look at my code above.
SELECT sick FROM ziekbeter WHERE person = $user_ID AND healthy IS NULL
This would select the 'sick' row from table 'ziekbeter' (the whole table) but only the value of 'sick' where person = $user_ID (which is the user thats currently logged in to the system) and when the 'healthy' field is empty. This value (which if we're person 2 is 2014-11-13) will get put into $date. Now the only problem i face is that i need to echo this date on my website. Is there any way to do this?
The second image is of my website's front-end. You see the big red button which says 'report healthy'. If the user clicks that butten the date which they enter in the date field on the right gets put in the database (in the healthy field). (NOTE: All of this code works, im just looking for a way to output my $date on my page).
EDIT
If i var_dump the array i get the following code:
array(1) { [0]=> object(stdClass)#2315 (1) { ["sick"]=> string(10)
"2014-11-03" } }
What
print_r($array);
tells you?
Did you try
echo $array["sick"];
?
or maybe
echo $array->sick ?
$array being the name of the array containing the result of your MySQL query (the one you var_dump'ed).
Ok turns out the answer was rather simple.
$date2 = $wpdb->get_results( "SELECT sick FROM ziekbeter WHERE person = $user_ID AND healthy IS NULL" );
foreach ($date2 as $row) {
echo $row->sick;
}
I simply had to declare he had to echo the sick field again. The original SELECT did select the table at first but didnt remember that value when stored in a variable. I added a foreach row in the date variable and echo'ed the sick field. Since there is only 1 value ever in the table it has my desired result. Thanks all!

Referencing PHP array from MSSQL

Using MSSQL and PHP, I'm writing a calendar form that lists times in a user's schedule and lets him enter whether he is busy, available, etc.
Once the user submits the info, it's saved to a database.
If the user goes back to the form, he should see the form fields defaulting to the values he already entered.
Ok, so I could query the database for each day and timeslot, and use the result to determine what's shown on the form...but that's 145 calls to the database, since that's the number of timeslots the user can have in a week.
It seems there should be a way to query the database once, store the 145 results in an array, then query the array by day and time for each field.
So I've got:
$sql="SELECT * FROM committee_employee_schedules WHERE fac_id = $user_id";
$result= mssql_query($sql,$conn);
But from there I don't want to go into a while loop with mssql_fetch_array()...how would I go about querying my result set instead? Thanks.
Here's some more example code, since I seem to be failing to communicate:
<form>
<label for="7:30AM">7:30AM</label>
<select name="7:30AM">
<option>Available</option>
<option>Class</option>
<option>Office Hours</option>
</select>
<label for="8:00AM">8:00AM</label>
<select name="8:00AM">
<option>Available</option>
<option>Class</option>
<option>Office Hours</option>
</select>
<label for="8:30AM">8:30AM</label>
<select name="8:30AM">
<option>Available</option>
<option>Class</option>
<option>Office Hours</option>
</select>
</form>
...and this goes up till 9:30PM, Monday-Friday, for a total of 145 dropdown fields.
Each field needs to know IF a row in the table exists for that timeslot, and, if so, select the appropriate activity.
I can grab all the records for the user using the code above, but do I then have to loop over those 145 rows for every single field on the form? Isn't there a way to stick the records into an array and reference it with results['Monday']['7:30'][Activity] or something?
So, you are getting back 145 records from the database. The results of your SELECT query will be stored in an array, and you will have to iterate through them using a loop. This loop could read the day and timeslot from the record, and store it into an appropriate array. Later, you could then reference that new array in the way you want. I'll try to put together an approximate example below.
<?php
slotData = array();//Store your results here the way you want to, see down below
$sql="SELECT * FROM committee_employee_schedules WHERE fac_id = $user_id";
$result= mssql_query($sql,$conn);
while($row = mssql_fetch_row($result)) {
$day = $row['day'];//Guessing your column name here
$time = $row['time_of_day'];//again, guessing your time here
$slotData[$day][$time] = $row;
//this all assumes "$day" looks like "monday", "tuesday", etc.
//also assumes "$time" looks like "8:00AM", "9:30PM", etc.
}
//now that data is in array the way you want, reference it later
//Assume you are currently trying to populate Monday at 8am position in calendar...
$curDay = 'monday';
$curTime = '8:00AM';
$data = $slotData[$curDay][$curTime];
//Yeay! "$data" now has all of the information for Monday at 8am.
?>
The bottom line is, iterate through your database result set and move the data into an appropriate slot of a different array, depending on where it should go. Then later, reference that different array however you like without worrying about iterating through ALL of the original records each time. Solved.

Categories