While to check something in the database [closed] - php

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);

Related

sql loop returns only one result [closed]

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.

Improve performance when copying records from table to another one

Hi buddies :) I was required to create a php code to handle some workers' data stored in DB. I got the desired result but it takes seconds and seconds (seconds and seconds! >.<) to finish, so I'm afraid I'm not doing something in a right way :(
The workers' data is stored in a mysql table (table1), something like this:
I'm given a pair of dates: initial_date (a) and final_date (b), so my goal is to copy the given workers' data in a new table (table2), day by day from a to b. The expected table should be as shown below (this table will be used later as a basis for further operations, which is not part of the question)
It's a requirement to overwrite any existing data between a and b dates, and 'jump' weekends and holidays.
To get my goal, I'm coding this (let's assume that the connection and all that is done and the checkworkingday function is given):
$initialdate = '2016-10-10';
$finaldate = '2016-10-12';
$x = $initialdate;
do {
if (checkworkingday($x) == true) {
$query = mysqli_query($connection,"SELECT name,task FROM table1");
while($row = mysqli_fetch_array($query)) {
$task = $row['task'];
$worker = $row['name'];
$query2 = mysqli_query($connection,"SELECT task FROM table2 WHERE name = '$worker' AND date = '$x'");
$row2 = mysqli_fetch_array($query2);
$existingtask = $row2['task'];
if (!isset($existingtask)) {
mysqli_query($connection,"INSERT INTO table2 (date,name,task) VALUES('".$x."','".$worker."','".$task."')");
} else {
mysqli_query($connection,"UPDATE table2 SET task = '".$task."' WHERE date = '".$x."' AND worker = '".$name."'");
}
}
}
$x = date('Y-m-d', strtotime($x . "+1 day"));
} while ($x <= $finaldate);
Just for 3 days as shown in the example, it takes a long to end; and for several weeks or months it takes very, very long (even max execution time is exceeded depending on dates range!).
I'm a newbie and I know the code is quite 'rustic', but I've revised and checked the code and info out there without getting a better performance. What am I doing wrong? Thanks :)
Instead of looping through the enitre data, try INSERT.. SELECT :
INSERT INTO table2 (date,name,task)
SELECT date,name,task
FROM Table1
WHERE < >;

mysql php if else inside while loop [closed]

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
$sql = mysql_query("SELECT DISTINCT business_region FROM business WHERE business_category='occupation'");
// count the output amount
$businessCount = mysql_num_rows($sql);
if ($businessCount > 0) {
while ($row = mysql_fetch_array($sql)) {
$business_region = $row["business_region"];
$Region_view .= "display value";
}
}
This gives a following result:
Michigan Toronto Ohio Manchester London Sydney Paris
I want to select only Ohio and London
as a variable value as:
$Region_view .
Perhaps I can use if else structure, but I could not get it to work.
i.e. I need to select only Ohio, London
I can do it using joint MySQL statement but it is too slow so I need and ask for a different way.
$sql = mysql_query("SELECT DISTINCT business_region FROM business WHERE business_category ='occupation'");
// count the output amount
$businessCount = mysql_num_rows($sql);
if ($businessCount > 0) {
while($row = mysql_fetch_array($sql)){
$business_region = $row["business_region"];
if ($business_region == 'Ohio' || $business_region == 'London') // added
$Region_view .= $business_region;//changed
}
}

getting 2 item instead of 1 mysql database [closed]

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 9 years ago.
Improve this question
i have problem i am using below script for merge tables and get data from mysql
$myboxexi=mysql_query('select box.id,box.page_name,box.title,box.connect,box.type,box.uid,box.description,box.image,box.url,box.status,box.date,box.time
from boxes as box left join page_boxes as pages on box.uid=pages.uid and pages.uid="'.$session_id.'"');
while($my_boxi=mysql_fetch_array($myboxexi)){
$title=$my_boxi['title'];
$bid=$my_boxi['id'];
$ptitle=$my_boxi['page_name'];
$connect=$my_boxi['connect'];
$type=$my_boxi['type'];
$iuid=$my_boxi['uid'];
$description=$my_boxi['description'];
$image=$my_boxi['image'];
$url=$my_boxi['url'];
$appr=$my_boxi['status'];
$date=$my_boxi['date'];
$time=$my_boxi['time'];
$myinfo=mysql_query('select * from users where id="'.$iuid.'"');
$my_boxi_info=mysql_fetch_array($myinfo);
$user_id=$my_boxi_info['id'];
$user_name=$my_boxi_info['user_name'];
$thmb=$my_boxi_info['thumb'];
if(strpos($thmb,'https://') !== false) {
$thmbs=$thmb;
}else
{
$thmbs='images/thumbs/'.$thmb;
}
}
its working fine but problem is i am getting double item like if i have 1 item then i get 2 item how can i solve this issue ?
I think you get 2 values because you have for example,element [0] and same element with key=name of column , so use only associatif result :
Change this :
while($my_boxi=mysql_fetch_array($myboxexi)){
//data here.
}
To this :
while($my_boxi=mysql_fetch_array($myboxexi, MYSQL_ASSOC)){
//data here.
}
Or to this
while($my_boxi=mysql_fetch_assoc($myboxexi)){
//data here.
}
mysql_fetch_array() returns a dual-keyed array. e.g.
SELECT foo FROM bar
$row = mysql_fetch_array($result);
will give you the array:
$row = array(
0 => 'value from foo',
'foo' => 'value from foo'
);
Since you're blindly looping on the returned array, you're looking up each of those "duplicate" results. If you only want ONE of the field types, try the dedicated functions, or the optional type argument,e .g
$row = mysql_fetch_assoc($result); // return only string keys
$row = mysql_fetch_array($result, MYSQL_ASSOC); // ditto
Presumably you are getting two items because two pages have the same user/session id that is being passed in:
select box.id, box.page_name, box.title, box.connect,box.type, box.uid, box.description,
box.image, box.url, box.status,b ox.date,box.time
from boxes box left join
page_boxes pages
on box.uid = pages.uid and pages.uid = "'.$session_id.'"'
(To me, it is suspicious that you are setting uid -- which often means "user id" -- to a variable called $session_id, but that is another matter.)
If you only want one, add limit 1 to the end of the query:
select box.id, box.page_name, box.title, box.connect,box.type, box.uid, box.description,
box.image, box.url, box.status,b ox.date,box.time
from boxes box left join
page_boxes pages
on box.uid = pages.uid and pages.uid = "'.$session_id.'"'
limit 1;

Continue numbering PHP [closed]

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 work on a page(.php) that show some information from databases(like article name,article author).I also have a pagination script that work good(the ideea of pagination script is when I press a link the url of the site goes to something like ?page=2)Now I try to numbering the records that I show form databases.But how can I do that?
Pagination script:
$per_pages = 6;
$nrofarticles_query = mysql_query("SELECT COUNT('id') FROM tbl_articles");
$nrdearticole = mysql_result($nrofarticles_query, 0);
$totalpages = ceil($nrdearticole/$per_pages);
$currentpagedisplay = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$firstpair = ($currentpagedisplay - 1) * $per_pages;
I echo record from database like so:
$articles_set = mysql_query("SELECT * FROM tbl_articles LIMIT $firstpair, $per_pages");
while($article = mysql_fetch_array(article_set)){
echo $article['article_name'];
}
So I show 6 records from database on page change show the next 6 records or if is less than 6 show how many remained .How can I numbering the records like this:
?page=1
1 article_name1
2 article_name2
3 article_name3
....
6 article_name6
?page=2
keep going
7 article_name7
8 article_name8
.....
EDIT
I was thinking to something like
<?php
$nrofarticles = 0;
$articles_set = mysql_query("SELECT * FROM tbl_articles LIMIT $firstpair,$per_pages");
confirm($articles_set);
while($article = mysql_fetch_array($articles_set)){
$nrofarticles ++;
}
echo "<ul id=\"id\">";
for($i = $firstpair+1; $i<=$nrofarticles * $currentpagedisplay; $i++){
echo '<li class="nr_id">' .$i. '<sub>#</sub></li>';
}
echo "</ul>";
?>
It's works but only on first 2 page of 3 because I have 16 articles in total - so on last page $firstpair + 1 will be 13 and $nrofarticles * $currentpagedisplay will be 12(4(articles) * 3(page=3)).
Go use a framework. You'll get pagination (and all sorts of extras) for free.

Categories