Referencing PHP array from MSSQL - php

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.

Related

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.

SQL groupping by date and host address

I'm trying to count the unique visitors each day on my website.
This is the script i made:
<?php
require_once 'database.php';
$dateQuery = $db->prepare("SELECT count(*) AS hits FROM tracked GROUP BY DATE(date), hostadrr");
$dateQuery->execute();
$rows = $dateQuery->fetchAll(PDO::FETCH_ASSOC);
$array = array();
foreach ( $rows as $row ) {
$array[] = [(int)$row['hits']];
}
$json = json_encode($array);
echo $json;
?>
This array I get from the json_encode is then this:
[[3],[1],[1],[2],[10],[3],[1],[2]]
It is correct that there are 8 arrays inside an array, this represents each day. But the number inside each array are just the total number on clicks on my website, not grouped by the host address of the user. What am i doing wrong here? The array should be: [[1],[1],[1],[1],[1],[1],[1],[1]] (because i'm testing it on my own computer ;) )
First of all, always try to strip down your code to the minimal problem. For example, don't mix JSON encoding, PHP and MySQL and be astonished, that the result isn't what you look like.
Start with the SQL query:
SELECT count(*) AS hits FROM tracked GROUP BY DATE(date), hostadrr
Did you try to run that on console or in phpMyAdmin? Is the correct result showing up?
I would guess not. Why? Because this query only returns a number of hits without any relation to a date or a host address. So, even though you say that the data is correct for the total hits in a day, you can't even be sure if it is the right order or if it doesn't leave out days without any hits.
Since you do not provide your SQL schema, I can only assume one. But your query should at least look something like this:
SELECT
date AS date,
hostadrr AS host,
count(*) AS hits
FROM
tracked
GROUP BY
DATE(date),
hostadrr
ORDER BY
date ASC
Now, you'll get one line for each date/host combination along with the respective number of hits and you can assign that to an array, i.e.
$array[$row['date']][$row['host]] = (int) $row['hits'];

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!

Return multidimensional array from MySQL query for use in dynamic dropdown field without page reload

The following is the start of the millionth non-functioning attempt, it does not even return distinct results:
<?php
require 'config.php';
$sqlcountryquery = "SELECT distinct country, region, towncity FROM input ORDER BY country, region, towncity";
$resultcountry = $mysqli->query($sqlcountryquery);
while ($rowcountry = $resultcountry-> fetch_assoc()){
echo"<option value=\"{$rowcountry['country']}\">";
echo $rowcountry['country'];
echo "</option>";
}
?>
I feel like I have been close before but gave up in frustration and don't have the code.
My mindset at the moment is that I need to load the results of the query into a multidimensional array as:
COUNTRY -> REGION -> TOWNCITY
then use a while, if loop to build the first field and remove duplicate entries (instead of DISTINCT). then use jQuery and javascript to extract the rest of the values in the array as the parent field changes
First though I need to get that darn array figured out. Does it sound like I'm on the right track? How do I get that array working?

Submitting form with 100 <select>s to database

I have a pretty basic page that shows every five minutes of the day (12:00, 12:05, 12:10, etc). Next to each time is a dropdown <select> with the numbers 1-9. The name of the <select> is the name of the time it corresponds to. The user selects one of the numbers, goes to the next, selects a number, etc. until they get to the bottom and hit submit.
In the database table, each time of the day has its own row, with another field for the number.
How can I submit this form and have it insert the number based on the time of day to the proper row? I can't wrap my head around this for some reason. I don't even need to do validation. This is not a live website.
I think the name of the select should be times[] and the value should be the time.
so in php you can loop through the times[] array and get the row that corresponds to its value. Then update the count accordingly.
<select name="times[]" multiple>
<option value="19:00">1</option>
<option value="19:05">2</option>
</select>
In php psuedo code
foreach ($_GET['times'] as time) {
*sanatize
select row where time = time
update count
}
Assuming you have a table like this:
MyValues
TimeOfDay varchar(50),
Value int
And your posted form data looks like this:
?19:00=1&19:05=2
You will loop through each posted form field and use the key and value of each field to generate an update statement like this:
foreach($_POST as $key => $value)
{
update MyValues set Value = $value where TimeOfDay = $fieldName
}
it seems #dm03514 is good options, but had rather use the $_POST than $_GET, and on the process you can do like this
for($=0;$i<count($_POST['times']);$i++){
#do some action with $_POST['times'][$i]
}

Categories