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!
Related
I have a PHP script that helps me to make some financial reports like capital, profits, total sold item, total item in store between 2 dates:
$result[] = 0;
$res[] = 0;
$fetchStat[]=0;
if(isset($_POST['generate_capital']))
{
$from_d = $_POST['from_d'];
$to_d = $_POST['to_d'];
$stat = "SELECT sum(sell_quantity*(sell_price-init_price)) AS 'rebeh', sum(init_price*(quantity-sell_quantity)) AS 'capital', sum(sell_price*sell_quantity) AS 'profits', sum(quantity) AS 'total_item', sum(sell_quantity) AS 'total_sell' FROM purchases WHERE date_now BETWEEN :d1 AND :d2";
$stmtStat = $conn->prepare($stat);
$stmtStat->bindValue(':d1', $from_d);
$stmtStat->bindValue(':d2', $to_d);
$execStat = $stmtStat->execute();
$fetchStat= $stmtStat->fetchAll();
}
Now, the same query in MySQL workbench will give me a specific result:
SELECT sum(sell_quantity*(sell_price-init_price)) AS 'rebeh',
sum(init_price*(quantity-sell_quantity)) AS 'capital', sum(sell_price*sell_quantity) AS 'profits',
sum(quantity) AS 'total_item',
sum(sell_quantity) AS 'total_sell'
FROM purchases WHERE date_now BETWEEN '2016-02-02' AND '2016-05-09'
The result is:
And the same query in the PHP script with the same date range will give me other values:
I've changed the Arabic keywords with English ones so you can see the difference.
Any help is appreciated.
EDIT: Adding var_dump result for 2 dates
As it stands, it appears that the most likely cause is that your date formats have the month and day in the wrong order, for the 2nd of February, that doesn't matter, but for the 9th of May, it would become the 5th of September.
Now, the reason that the data for the 9th of May isn't included when you run the query directly is because a date is actually midnight on that date, making it exclusive of that date when it comes at the end of a between.
It's possible there is something else, so if this doesn't work, try echoing out all your values at every point, until you know exactly what is being run, and it should become clear.
To clarify, when using '/' in a date, MySQL uses the following format:
'%d/%m/%Y'
Which would explain why it works if you enter a string into your text box.
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'];
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!
Having some difficulty pinpointing exactly what is wrong with this block of code. I am expecting it to run through a loop a set number of times and update some rows in the table tbl_games with some values received from the form.
I have tried running the code in phpMyAdmin without variables, which works fine (updates specified row). I assume the problem is something to do with the string in $insert_q.
gamecount will always be an int<30, game_ID will be a unique primary key integer value in tbl_games.
A little background: this code is part of a bigger project - which is centered around football games. An admin adds games to tbl_games (coded and finished), this current file now displays games to the admin which are unplayed (scores for team1 and team2 are NULL) and gives them a space to input scores for each team. This code takes those 2 scores, and the game_ID and updates each row.
It's having no effect on the DB rows though. Please point me in the right direction.
<?php
$lim=$_SESSION['gamecount'];
for ($i=1; $i<$lim; $i++) {
$game_ID = ${"_SESSION['game".$i."_ID']"};
$score_team_1 = ${"_REQUEST['".$i."_team1-score']"};
$score_team_2 = ${"_REQUEST['game".$i."_team2-score']"};
$insert_q = "UPDATE tbl_games SET team1_score = '$score_team_1', team2_score = '$score_team_2' WHERE game_ID = '$game_ID';";
mysql_query($insert_q);
}
session_destroy();
?>
I think the problem is with this line.
$game_ID = ${"POST['game".$i."_ID']"};
It should be something like this.
$game_ID = ${"_POST['game".$i."_ID']"}; or
$game_ID = $_POST['game'.$i.'_ID']; //much cleaner
You need to make use of the mysql reporting. Get it to output any errors, and affected rows. While you may think affected rows will be none, it might not be (always good to check when debugging just so you check everything).
Does your PHP error log have any warnings or other notices that might point to your query being an issue etc?
What is the value you're updating (echo out the var/session) and what is the DB value (look at it in phpmyadmin or mysql command line).
Could be there's nothing to update.
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.