Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I'm doing a triple loop to insert values on an array (dataArray[]).
The first one, search for workers
The second one is a "for" for each day of the week
The last one look if the person works this day.
I don't know why it show me only 1 result....
If I change the order (first $sql) it shows me another entry.
// display loop
$sql = "SELECT workers.id, workers.surname, workers.name
FROM workers,employment_contract
WHERE employment_contract.fk_company_teams_id='".$teamID."'
AND employment_contract.fk_workers_id=workers.id
AND employment_contract.initial_date<'".$beginingDate."'
AND (employment_contract.final_date>".$beginingDate."
OR employment_contract.final_date='0000-00-00-00:00:00')
ORDER BY workers.surname ASC";
$stmt = $db->prepare($sql);
$i=-1;
$dataArray;
if($stmt->execute()){
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$i++;
// datas in array
$nameInitial = substr($row['name'], 0, 1).'.';
// inserting worker name on array
$dataArray[$i]['workerName']=$nameInitial.' '.$row['surname'];
$workerID = $row['id'];
$totalTime = new DateTime('0000-00-00 00:00:00');
for($j=0;$j<7;$j++){
// changing the current date
$incrementation = 'P'.$j.'D';
$currentDate = date_create($beginingDate);
$currentDate->add(new DateInterval($incrementation));
$currentDate = date_format($currentDate, 'Y-m-d');
// sql search for daily timesheet
$sql = "SELECT initial_date,final_date
FROM working_days
WHERE fk_workers_id='".$workerID."'
AND (initial_date >='".$currentDate." 00:00:00.000')
AND (final_date <='".$currentDate." 23:59:59.999')
ORDER BY id ASC";
$stmt = $db->prepare($sql);
$k=1;
if($stmt->execute()){
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
// formatting date for calculation
$time1 = utf8_encode(strftime("%R",strtotime("$row[initial_date]")));
$time2 = utf8_encode(strftime("%R",strtotime("$row[final_date]")));
$initialDate = new DateTime(date($row['initial_date']));
$finalDate = new DateTime(date($row['final_date']));
$time3 = $initialDate->diff($finalDate);
$timeFormatted = $time3->format('%H:%I');
$totalTime->add($time3);
// setting the day to implement
if($j==0){$day = 'monday';}
if($j==1){$day = 'tuesday';}
if($j==2){$day = 'wednesday';}
if($j==3){$day = 'thursday';}
if($j==4){$day = 'friday';}
if($j==5){$day = 'saturday';}
if($j==6){$day = 'sunday';}
$arrayBox = $day.$k;
// inserting day value on array
$dataArray[$i][$arrayBox] = $time1.' '.$time2.' <b>'.$timeFormatted.'</b></div><br>';
unset($time1);
unset($time2);
$k++;
}
}
}
$totalTimeFormatted = $totalTime->format('H:i');
// inserting holidays value on array
$dataArray[$i]['holidays'] = 'Vac';
// inserting sum value on array
$dataArray[$i]['sum'] = $totalTimeFormatted;
// if no timesheet is found for the worker we don't show anything
if($totalTimeFormatted==='00:00'){
unset($dataArray[$i]);
}
unset($totalTime);
}
}
I think my dates (dateTime) calculations are not efficient but it's not the problem here.
As mentionned in commentary, I used same variable name for sql statements $stmt.
I corrected it to $stmt1 for the third loop and it's working.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I don't know php at all so sorry for a simple question - I've got the project started by another person so now I'm trying to finish it.
The problem is - I'm making an android app for which I can't make a change without changing a php and this language I don't know.
here's this part :
function getPlaces(){
$result = array();
$sql = "SELECT id, name, short_description, photo_list, selected, recommended, isTOP FROM place
WHERE id IN(SELECT id_place FROM rubric_place WHERE id_rubric IN(SELECT id FROM rubric WHERE name = '".$_REQUEST["rubric"]."')) ORDER BY isTOP DESC";
getConnect();
$query = mysql_query($sql);
if(!$query){
error100();
}else {
$result['code'] = 200;
for ($i = 0; $i < mysql_num_rows($query); $i++) {
$row = mysql_fetch_assoc($query);
$result["places"][$i] = $row;
$sql = "SELECT * FROM rubric WHERE id IN(SELECT id_rubric FROM rubric_place WHERE id_place = ".$row[id].")";
$queryModule = mysql_query($sql);
if($queryModule){
for ($k = 0; $k < mysql_num_rows($queryModule); $k++) {
$rowModule = mysql_fetch_assoc($queryModule);
$result["places"][$i]["rubrics"][$k] = $rowModule;
}
}
$sql = "SELECT SUM(rating)/COUNT(rating) AS rating FROM comment WHERE id_place = ".$row[id];
$queryModule = mysql_query($sql);
if($queryModule){
$rowModule = mysql_fetch_assoc($queryModule);
$result["places"][$i]["rating"] = $rowModule[rating];
}
}
echo json_encode($result, JSON_UNESCAPED_UNICODE);
exit();
}
}
what I need is to make another function that returns in $result a value of "length" of places. I know I can find out length on the other end - in Android's app result, but this particular function will be changed so it will return by 20 results only so I need another function that returns length so plz help
To count the number of characters in a json you can do:
$string = json_encode($result, JSON_UNESCAPED_UNICODE);
$length = strlen($string);
You have to first put the json into a variable to count it, before outputting it.
To count the items in an array before you turn it into a json, you can do:
$length = count($array);
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Ok i have a while loop function in my site that pulls in excel documents and parses them to the database i want to check for duplicates and if duplicate skip it:
$content = file($selectfile1);
$posted_content = array();
list($rownum, $row) = each($content);
$posted_content[0] = explode(",", $row);
array_push($posted_content[0], "ID");
$count = 0;
// iterate each row (1 post)
while (list($rownum, $row) = each($content))
{
$count++;
$cols = "orderid, created_at, updated_at, notification_type, radius, available, expiration, ";
$vals = "";
$cols2 = "equipment_id";
$vals2 = "";
....{parsing data)...
}
i want to write in a script that checks to see if the record is a duplicate and if not enter it.
$sql25 = "SELECT * FROM notifications WHERE origin =" . $origin_id . " user_id =12039";
$rs25 = $conn->Execute($sql25);
if($rs25->RecordCount() == 1 || $rs25->RecordCount() >= 1)
{
here is where i need a command. Can you use? next()
--------------------------------------------------
}
else
{
Insert query
}
You are looking for the continue statement.
From the docs:
continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.
(See http://www.php.net/manual/en/control-structures.continue.php)
example:
<?php
while ( ... ) {
if ($foo = 'bar') {
// skip to the next iteration
continue;
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to check if I have an hour in the database but If I have more than hour in the database it outputs twice, if I have 3 three times...
In this specific case this gives me: 9 (in blue color) and then 9 (in red color)
$result = mysqli_query($con, 'SELECT * FROM consulta
WHERE professional=1
AND client=0');
while ($row = mysqli_fetch_array($result)) {
if ($row['hora']=='09:00:00') { echo '<p class="blue">9</p>'; }
else { echo '<p class="red">9</p>'; }
}
I have a MySql database with columns: id, professional and hour. I have stored 2 hours and this is what I get if I echo $row['hora'] 09:00:00 and 10:00:00
In this case the if should give me just 9 in blue because it is in the database. I do not understand why it happens. How can I solve this?
This is the structure of the MySql database:
Presumably you are building up a calendar or the like.
The query you are using is returning all rows (and you are looping over each row, regardless of the hour). If you want to check if specific hours exist you could build up an array of hours:
$result = mysqli_query($con, 'SELECT * FROM consulta
WHERE professional=1
AND client=0');
$hours = array();
while ($row = mysqli_fetch_array($result)) {
$hours[$row['hora']] = $row;
}
Now to check a specific hour we can do:
if (!empty($hours['09:00:00'])) {
echo '<p class="blue">9</p>';
}else {
echo '<p class="red">9</p>';
}
Edit: Explanation
In the first loop we are building up an array. This will look like:
$hours = array(
'08:00:00' => $dataForThisRow,
'09:00:00' => $dataForThisRow
);
In the above '08:00:00' is called a key. Each key is a time that was found in the database.
To check if there is an entry in the database for our time we can check if there is a non empty key. Hence we use:
if(!empty($hours['09:00:00'])
This if will run if $hours has a key with the value '09:00:00'. If there is no key then the other part of the if will run.
You are comparing with this value: 09:00:00, but the database seems to have stored this other: 9:00:00
Change your sql query like below:
$query = "SELECT TIME_FORMAT(hora,'%H:%i:%S') FROM consulta
WHERE professional=1
AND client=0";
$result = mysqli_query($con, $query);
I have a php script for conducting online test. while taking test, I am using post method to get the answers in the action page.The answers are passed as an array with question id and the selected option value(true or false/the answers the candidate entered like that).Then I have to insert the answers marked by the candidate in the database. The code is as shown below:
$student_id=$_POST['name'];
$survey_id=$_POST['survey_id'];
$store = array();
if (isset($_POST['question_id'])) {
foreach ($_POST['question_id'] as $key => $option) {
$option1 = array_filter($option);
print_r($option1);
if (count($option1) > 1) {
$option2 = implode("^", $option1);
$store[] = $option2;
} else {
$value = $option1;
$i = implode(null, $option1);
$store[] = $i;
}
}
print_r($store);
}
$t = new DateTime();
$t->setTimestamp($time = time());
$t->setTimeZone(new DateTimeZone("Asia/Singapore"));
$date = $t->format(DateTime::RFC850);
$SQL = "INSERT INTO answer_table(student_id ,survey_id, ans_1, ans_2, ans_3, ans_4, ans_5, ans_6, ans_7, ans_8, ans_9, ans_10, timestamp) VALUES ('$student_id','$survey_id', '$store[0]', '$store[1]', '$store[2]', '$store[3]', '$store[4]', '$store[5]', '$store[6]', '$store[7]', '$store[8]', '$store[9]', '$date')";
$result = mysql_query($SQL);
If the student answers the test in sequential order(from question number 1 to 10) the code works fine. But when the candidate answers in random manner(first 10 then 5 like that),the table field named,ans_1 will get inserted with answer of question number 10. I need to insert fields with corresponding answers ,(ans_1 with answer of question 1 like that) what ever pattern,the candidate takes test.
Can anyone help me to solve this issue. Thanks in advance.
For achieving you goal.you should store question_id with answers or create another table which store question_id and corresponding answers, with id of answer table.
If you have the question id in the $key variable, you could use
$store[$key] = $option2;
instead of
$store[] = $option2;
With that the first question is the first entry in the array regardless of the order of the answers in the post array.
You can replace $store[] = $option2; with:
$store[$_POST['question_id']] = $option2;
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Dynamically bind mysqli_stmt parameters and then bind result (PHP)
can any one help me on how could I create a dynamic bind_result on PHP.
My query field doesn't know how many fields are there since it was created dynamically (e.g creating year fields base on the date range). below is my script and highlighted on where is the problem.
public function getMarketingReports($datefrom,$dateto)
{
$yearfrom = date("Y", strtotime($datefrom));
$yearto = date("Y", strtotime($dateto));
//create year fields
$concatYear = "";
for($year=$yearfrom;$year<=$yearto;$year++){
$concatYear .= "SUM(IF(c.datecreated='".$year."',IF(LOWER(c.fullTimeEployeeType)='basic hour rate', c.fullTimeEployeeTypeAmount*2080 , c.fullTimeEployeeTypeAmount),0)) ".$year.",";
}
$reportdata = array();
$db = Connection::Open();
$stmt = $db->stmt_init();
if($stmt->prepare("SELECT p.Code `PositionCode`,
p.name `PositionName`,
l.value `Location`,
".$concatYear."
SUM(b.field205) `TotalEmployees`
FROM c1 c
INNER JOIN b1 b
ON c.registrationid=b.id
INNER JOIN positions p
ON c.positionid=p.id
INNER JOIN lookupvalues l
ON c.location=l.id
WHERE c.`status`!=2
AND c.datecreated BETWEEN ? AND ?
GROUP BY c.positionid,c.location,YEAR(c.datecreated)")){
$datefrom = $datefrom." 00:00:00";
$dateto = $dateto." 23:59:59";
$stmt->bind_param("ss",$datefrom,$dateto);
$stmt->execute();
$stmt->bind_result
(
$positionCode,
$positionName,
$location,
**//getting bind result data here for year fields**
$totalEmployees
);
while($stmt->fetch())
{
$surveydata = array();
$surveydata['positionCode'] = $positionCode;
$surveydata['positionName'] = $positionName;
$surveydata['location'] = $location;
**//storing of data here for year fields**
$surveydata['totalEmployees'] = $totalEmployees;
array_push($reportdata,$surveydata);
}
}
Connection::Close();
return $reportdata;
}
Is it possible? Can anyone help me on how could I solve this problem
To start, your code that generates the year fields has a nice syntax error:
"SUM(IF(c.datecreated='".$year."',IF(LOWER(c.fullTimeEployeeType)='basic hour rate', c.fullTimeEployeeTypeAmount*2080 , c.fullTimeEployeeTypeAmount),0) ".$year.","
The SUM( opening statement is missing a closing parentheses. On top of that, you have a floating ".$year." that isn't part of any of the enclosed methods (though, it could be used as an alias; I'm not used to seeing it without a preceeding AS though - so this could be my mistake). To take a guess, I would say to replace the ".$year." with a ) and that should fix that part:
$concatYear .= "SUM(IF(c.datecreated='".$year."',IF(LOWER(c.fullTimeEployeeType)='basic hour rate', c.fullTimeEployeeTypeAmount*2080 , c.fullTimeEployeeTypeAmount),0)),";
If the $year addition is in fact to be an alias, you could add the closing parentheses immediately before it to close the SUM() function.
Regarding dynamically binding the variables, my ideal solution actually comes from a similar question/answer on SO (this is a direct copy/paste and I take no credit for it, but I do like it =P):
// Get metadata for field names
$meta = $stmt->result_metadata();
// This is the tricky bit dynamically creating an array of variables to use
// to bind the results
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$fields[$var] = &$$var;
}
// Bind Results
call_user_func_array(array($stmt,'bind_result'),$fields);
// Fetch Results
$i = 0;
while ($stmt->fetch()) {
$results[$i] = array();
foreach($fields as $k => $v)
$results[$i][$k] = $v;
$i++;
}
You have to call_user_func_array:
call_user_func_array(array($stmt, "bind_result"), $argArray);
And you fill $argArray this way:
$years = array();
$concatYear = "";
for($year=$yearfrom;$year<=$yearto;$year++){
$concatYear .= "SUM(IF(c.datecreated='".$year."',IF(LOWER(c.fullTimeEployeeType)='basic hour rate', c.fullTimeEployeeTypeAmount*2080 , c.fullTimeEployeeTypeAmount),0) ".$year.",";
// track the years you need
$years[] = $year;
}
...
//you prepare all the vars here
$argArray = array(
$positionCode,
$positionName,
$location
);
//loop the years
foreach($years as $y)
{
$argArray[] = ${$y};
}
$argArray[] = $annualSalary;
$argArray[] = $totalEmployees;
$argArray[] = $yearOfData;
And you do stuff with years later this way:
...
foreach($years as $y)
{
$surveydata[$y] = ${$y};
}