I have this query to count the number of forms that are submitted by a certain user
$sql="SELECT `ID` FROM `kform` WHERE `ID`='$ID'";
$result = $conn->query($sql);
$k=0;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$k++;
}
}
plus I have this php script that is basically check a certain date (which is included in each form) and prints valid if it is within this fiscal year
$endYear = 2017;
while($endYear <= 2025) {
$end = $endYear.'/06/30';
$endDate = DateTime::createFromFormat('Y/m/d', $end);
$initDate = DateTime::createFromFormat('Y/m/d', $end);
$initDate = $initDate->sub(new DateInterval('P1Y')) -> add(new DateInterval('P1D'));
$ddb = $row2['Date'];
$dateFromDB = DateTime::createFromFormat('Y-m-d', $ddb);
if ($dateFromDB >= $initDate && $dateFromDB <= $endDate) {
echo "valid\n";
echo "\tStartDate->\"".$initDate->format("Y-m-d")."\"\n";
echo "\tEndDate->\"".$endDate->format("Y-m-d")."\"\n";
echo "\tDateFromDatabase->\"".$dateFromDB->format("Y-m-d")."\"\n";
}
$endYear++;
}
Now what I was trying to do is to combine these two functions together, the idea behind that is to count only the forms that are in this fiscal year, any older forms should not be counted. I tried different ways to combine them but it gave me different errors every time, So is it even possible to do so?
Go on from that:
function isValidYear($dategiven){
$endYear=2017;
while($endYear<=2025) {
$end = $endYear.'/06/30';
$endDate = DateTime::createFromFormat('Y/m/d', $end);
$initDate = DateTime::createFromFormat('Y/m/d', $end);
$initDate = $initDate->sub(new DateInterval('P1Y'))->add(new DateInterval('P1D'));
$ddb = $dategiven;
$dateFromDB = DateTime::createFromFormat('Y-m-d', $ddb);
if ($dateFromDB>=$initDate && $dateFromDB<=$endDate) {
return true;
}
$endYear++;
}
return false;
}
And
$sql="SELECT `ID` FROM `kform` WHERE `ID`='$ID'";
$result = $conn->query($sql);
$k=0;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if(isValidYear($row['datefield'])){
$k++;
}
}
Note: Your $sql selects only the ID field. You have to at Date
$sql="SELECT * FROM `kform` WHERE `ID`='$ID'";
Related
I'm trying to get multiple bookings from my database for a hotel project
when i tried to get the bookings from my database i only recieved one booking it should display/select multiple bookings.
This is my php code:
(formulier.php)
<?php
$dt1 = $_POST['date1'];
$dt2 = $_POST['date2'];
$query = "SELECT * FROM dt_tb WHERE dt BETWEEN '$dt1' AND '$dt2'";
$result = mysqli_query($connect,$query);
if (mysqli_num_rows($result)) {
while($row = $result->fetch_assoc()) { include_once 'source.php';
}
echo "<br>formulier.php";
echo "<br>check-in: $dt1 <br>check-out: $dt2";
}
else {
die;
}
?>
And this is my other php code: (source.php)
<?php
$dt1 = $_POST['date1'];
$dt2 = $_POST['date2'];
$query = "SELECT * FROM dt_tb WHERE dt BETWEEN '$dt1' AND '$dt2'";
$result = mysqli_query($connect,$query);
if (mysqli_num_rows($result)) {
while($row = $result->fetch_assoc()) {
}
echo "source.php";
echo "<br>check-in: $dt1 <br>check-out: $dt2";
}
else {
die;
}
?>
this is my database: (dt_tb)
https://gyazo.com/966efdf144a8cd1a74fa04a8127cd8f4
This is what i receive: (Website)
https://gyazo.com/1384bdafb5055f5777a40e88baccdbdd
I know my code is messed up badly and tried to solve it for quite some time.
I don't know why you need two files. You can join them to single loop.
<?php
$dt1 = !empty($_POST['date1']) ? $_POST['date1'] : null;
$dt2 = !empty($_POST['date2']) ? $_POST['date2'] : null;
if (!$dt1 || !$dt2) {
throw new Exception("No dates passed!");
}
$query = "SELECT * FROM dt_tb WHERE dt BETWEEN '$dt1' AND '$dt2'";
$result = mysqli_query($connect, $query);
if (mysqli_num_rows($result)) {
while($row = $result->fetch_assoc()) {
echo "check-in: {$row['dt']}<br/>";
echo "check-out: {$row['dt2']}<br/>";
echo "<br/>";
}
} else {
echo "No bookings found between {$dt1} and {$dt2}";
die();
}
?>
What was wrong:
require_once is called only for first iteration, no further calls was made. It's used mostly when including classes or some configs, that must be included only once in whole logic.
You try to echo your data outside loop inside source.php
You echo passed parameters to server, but not actual database record entries. Changed $dt1 to $row['dt'] and $dt2 to $row['dt2']
You repeated the query in both files! Why?
As you typed, you don't need to include 2 lines! , you can add them directly:
$dt1 = $_POST['date1'];
$dt2 = $_POST['date2'];
$query = "SELECT * FROM dt_tb WHERE dt BETWEEN '$dt1' AND '$dt2'";
$result = mysqli_query($connect,$query);
if (mysqli_num_rows($result)) {
while($row = $result->fetch_assoc()) {
echo "source.php";
echo "<br>check-in: $dt1 <br>check-out: $dt2";
}
echo "<br>formulier.php";
echo "<br>check-in: $dt1 <br>check-out: $dt2";
}
else {
die;
}
I know that the error says that format isn't a valid code, but I used it before and it worked fine. So I hope someone knows a code to replace it with or now how to fix it.
require_once 'config.php';
$checker = "SELECT StartTime FROM ap21_Teachers WHERE Mentor_Class = 'I2C'";
$checker2 = "SELECT EndTime FROM ap21_Teachers WHERE Mentor_Class = 'I2C'";
$checker3 = "SELECT Minutes FROM ap21_Teachers WHERE Mentor_Class = 'I2C'";
$result1 = mysqli_query($mysqli, $checker);
$result2 = mysqli_query($mysqli, $checker2);
$minutes = mysqli_query($mysqli, $checker3);
$starttime = new DateTime($result1);
$endtime = new DateTime($result2);
while($starttime <= $endtime)
{
echo "<option value='".$starttime->format('H:i:s')."'>".$starttime->format('H:i:s')."</option>";
$starttime = date_add($starttime, date_interval_create_from_date_string($minutes, ' min'));
}
echo " </select>";
and above I grab the vars out of the database
The problem is mysqli_query returns a mysqli_result which you need to read before using:
require_once 'config.php';
$checker = "SELECT StartTime, EndTime, Minutes FROM ap21_Teachers WHERE Mentor_Class = 'I2C'";
$result = mysqli_query($mysqli, $checker); //Execute query
if (!$result) { //Result may be false if there's an error
echo "Error getting result";
}
$row = mysqli_fetch_assoc($result); //Put first result in an array
if (!$row) { // $row will be false if there's no result
echo "No data found";
}
//Notice how the array entry keys match the columns in the query.
$starttime = new DateTime($row["StartTime"]);
$endtime = new DateTime($row["EndTime"]);
$minutes = $row["Minutes"];
while($starttime <= $endtime)
{
echo "<option value='".$starttime->format('H:i:s')."'>".$starttime->format('H:i:s')."</option>";
$starttime = date_add($starttime, date_interval_create_from_date_string($minutes, ' min'));
}
echo " </select>";
I just asked a question earlier, but now i have formatted it into a function that does not return any value.
This is my code:
echo GetHours($UID, $DAY, $MONTH, $YEAR);
function GetHours($UserId, $Day, $Month, $Year){
//filter queries:
//YEAR:
if($Year==FALSE){
$Y = "";
} else {
$Y = " AND Year = '$Year'";
}
//MONTH:
if($Month==FALSE){
$M = "";
} else {
$M = " AND Month = '$Month'";
}
//DAY:
if($Day==FALSE){
$D = "";
} else {
$D = " AND Day = '$Day'";
}
$Query = mysql_query("SELECT SUM(TotalHrs)
FROM WorkLog
WHERE UserId = '$UserId'$D$M$Y");
$Data = mysql_fetch_array($Query);
return $Data;
}
Now, i do know that mysql_ functions are depreciated, but its required for this application at the moment.
My current problem is that this function does not return anything after using GET parameters to test.
Any solutions to this?
EDIT
I have changed the last lines to: return json_encode($Data); and now the screen shows: {"0":"8","SUM(TotalHrs)":"8"}
Always check that mysql_query() has not returned an error! Specially if you are building your query from parts generated from inputs that may or may not be present.
This should at least identify any errors in the SQL.
function GetHours($UserId, $Day, $Month, $Year){
//filter queries:
//YEAR:
if($Year==FALSE){
$Y = "";
} else {
$Y = " AND Year = '$Year'";
}
//MONTH:
if($Month==FALSE){
$M = "";
} else {
$M = " AND Month = '$Month'";
}
//DAY:
if($Day==FALSE){
$D = "";
} else {
$D = " AND Day = '$Day'";
}
$Query = mysql_query("SELECT SUM(TotalHrs)
FROM WorkLog
WHERE UserId = '$UserId'$D$M$Y");
if ( ! $Query ) {
// just debug code, should be amended for a live site situation
echo mysql_error();
return 'Its broken';
}
$Data = mysql_fetch_array($Query);
return $Data;
}
I figured out that the data i get returned was an array by doing echo json_encode(GetHours($UID, $DAY, $MONTH, $YEAR));
My finished code that works:
<?php
include 'assets/db_connect.php';
//Function to get total from WorkLog:
$DAY = $_GET['day'];
$MONTH = $_GET['month'];
$YEAR = $_GET['year'];
$UID = $_GET['id'];
echo GetHours($UID, $DAY, $MONTH, $YEAR);
function GetHours($UserId, $Day, $Month, $Year){
//filter queries:
//YEAR:
if($Year==FALSE){
$Y = "";
}
else{
$Y = " AND Year = '$Year'";
}
//MONTH:
if($Month==FALSE){
$M = "";
}
else{
$M = " AND Month = '$Month'";
}
//DAY:
if($Day==FALSE){
$D = "";
}
else{
$D = " AND Day = '$Day'";
}
$Query = mysql_query("SELECT SUM(TotalHrs) FROM WorkLog WHERE UserId = '$UserId'$D$M$Y");
$Data = mysql_fetch_array($Query);
return $Data['SUM(TotalHrs)'];
}
i would like to store data from a form into 2D array
but it seems to have problem inserting data into the array.
if i were to echo $orderArray[0][$count2] it seems to work
but if i were to echo $orderArray[1][$count2] there will be error
$dateArray = array();
$orderArray = array(array());
$amountArray = array(array());
$count = 0;
$count2 = 0;
foreach ($_POST['export'] as $date){
$dateArray[$count] = $date;
include "/storescript/connect_to_mysql.php";
$sql = mysql_query("SELECT * FROM ordera WHERE orderDate = '$date' ORDER BY orderid ASC");
$productCount = mysql_num_rows($sql); // count the output amount
if ($productCount > 0) {
while($row = mysql_fetch_array($sql)){
$orderArray[$count][$count2] = $row["orderAmount"];
$amountArray[$count][$count2] = $row["itemAmount"];
$count2++;
}
}
$count++;
}
I would reduce the code to this:
// connect here
include "/storescript/connect_to_mysql.php";
// make date list safe for querying
$dates = join(',', array_map(function($date) {
return sprintf("'%s'", mysql_real_escape_string($date));
}, $_POST['export']);
// run query
$sql = "SELECT * FROM ordera WHERE orderDate IN ($dates) ORDER BY orderid";
$res = mysql_query($sql) or die("Error in query");
// collect results
while ($row = mysql_fetch_array($res)) {
$orders[$date][] = $row['orderAmount'];
$amounts[$date][] = $row['itemAmount'];
}
// do stuff with results
foreach ($orders as $date => $orderAmounts) {
print_r($orderAmounts);
print_r($amounts[$date]);
}
Also, please learn about PDO or mysqli; the old mysql_ functions are deprecated.
I try to make a diagram with RGraph(JS). I have a user counter on my site. And now I want to make a user-statistic with this diagram.
However I created a list which should be used for every query (made a form to choose month and year).
My problem is that the code doesnt enter the loop to create the new values (Day and Count).
Any idea?
Here the code:
$days = 0;
$day_value = array();
//check months which have 30 days
if (in_array($month, array(4,6,9,11))) {
$days = 30;
}
//leapyear?
if ($month == 2) {
if ($year%4 == 0) {
$days = 29;
} else {
$days = 28;
}
}
//Count users for each day
for ($i=1; $i<=$days; $i++) {
$sql = "SELECT
Anzahl
FROM
Counter
WHERE
YEAR(Datum) = '".$year."' AND
MONTH(Datum) = '".$month."' AND
DAYOFMONTH(Datum) = '".$i."'";
if (!$result = $db->query($sql)) {
return $db->error;
}
$row = $result->fetch_assoc();
$day_value[$i] = (int)$row['Anzahl'];
}
//delete list for new month/year
$sql = "DELETE
FROM
Statistics
";
if (!$result = $db->query($sql)) {
return $db->error;
}
//Create list with values for each day
for ($j=1; $j<=$days; $j++) {
$sql = "INSERT INTO
Statistics(Day,Count)
VALUES
(?, ?)";
$stmt = $db->prepare($sql);
if (!$stmt) {
return $db->error;
}
$stmt->bind_param('ii', $j, $day_value[$j]);
if (!$stmt->execute()) {
return $stmt->error;
}
$stmt->close();
}
$days is set to 0, it only changes if $months is 2,4,6,9,11 so for every other value of $month $days will be 0 and not enter the for loop.
if (in_array($month, array(4,6,9,11))) {
//code
}
elseif ($month == 2) {
//code
}
else{
//code
}