I created a sort of (available / unavailable) for staff to store the start and end times/dates of each working day.
Here are my goals:
After their personal id is being scanned, they will see their own picture. Also the database will do the following:
Database checks or there is any record for the current date.Yes = update stop time and date. No = Create new entry.
Code:
if (isset($_POST['action'])) {
$queryRegistration = "SELECT id, number, startdate FROM timeRegistration";
$resultRegistration = mysqli_query($conn, $queryRegistration);
while($row = mysqli_fetch_assoc($resultRegistration)) {
if ($row['number'] == $staffNumber) {
if ($row['startdate'] == $currentDate) {
echo $row['number'].' '.$row['id'];
echo '<div class="boxPersons">My Picture</div>';
}
}
}
}
Goal 1: Does not work. As it creates more divs. How can I manage it only creates one div?
Goal 2: I want to update or create it with functions like:
function newEntryDate() {
$sql = 'INSERT INTO timeRegistration (id, number, startdate, enddate, starttime, endtime, value) VALUES (NULL, "'. $staffNumber .'", "'. $currentDate .'", "", "'. $currentTime .'", "", "")';
return $sql;
}
Question: How can I make sure this works within my script? I don't know how to start.
Do something like this.
if your query is retrieving more than 1 row set a limit in query.
it is better to not use if statement in while loop.
if (isset($_POST['action'])) {
$queryRegistration = "SELECT id, number, startdate FROM timeRegistration where startdate =".$currentDate." AND number=".$staffNumber." limit 1;";
$resultRegistration = mysqli_query($conn, $queryRegistration);
$i=0;
while($row = mysqli_fetch_assoc($resultRegistration)) {
echo '<div class="boxPersons">My Picture</div>';
$i++;
}
if($i>0){
newEntryDate();
}
Related
My code is big and I can't just pull out few lines to show my problem so I am going to explain it by using imaginary code to simplify it.
Let's say I have to-do list as table and I've defined activity and time. I don't want to have duplicate rows so I created function to prevent it.
function check_date($day, $time) {
include 'db_connect.php';
$sql = "SELECT day, dan FROM todo ";
$sql .= "WHERE day = $day AND time = '{$time}'";
$result = mysqli_query($conn, $sql) or trigger_error(mysqli_error());
if(mysqli_num_rows($result) >= 1) {
$row = mysqli_fetch_assoc($result);
return 1;
} else {
return 0;
}
}
Call on function in main file:
if(check_termin_sala($day, $time)) {
$errors['busy'] = "You are busy.";
}
And query:
if(empty($errors) {
$query = "INSERT INTO todo (";
$query .= "day, time, activity";
$query .= ") VALUES (";
$query .= "'{$day}', '{$time}', '{$activity}')";
$result = mysqli_query($conn, $query);
if(!$result) {
die("Failed." . mysqli_error($conn));
}
}
Now I want update my row by changing just activity field, but fields day and time are unchanged so when I submit update I get error because exact day and time are already inserted. What should I do to exclude this check function affecting current row date and time?
I hope you will understand me. :)
I am building a car parking application in which different users have different numbers of parking spots. This number is set by an administrator in a database. The user can input a numberplate which then will be added to a database as well. What I want is that when a user has occupied all the spots, that he will not be able to insert any more number plates.
However, now I have the following code at the moment:
if(isset($_POST['number_plate'])){
$numberPlate = $_POST['number_plate'];
$user_id = $_SESSION['id'];
$query = mysql_query("SELECT `parking_spots` FROM `login` WHERE `id` = ".$user_id." ");
$row = mysql_fetch_assoc($query);
$totalNumberOfSpots = $row['parking_spots'];
$occupiedNumberOfSpots = 0;
$sql = "INSERT INTO amsterdam (numberplate, user_id) VALUES ('$numberPlate','$user_id')";
if(mysql_query($sql))
{
echo 'numberplate added';
$occupiedNumberOfSpots++;
if($occupiedNumberOfSpots == $totalNumberOfSpots)
{
echo "There are no more spots avialable";
}
}
else
{
echo 'Something went wrong!';
}
}
But when I echo the $occupiedNumberOfSpots variable it keeps returning 1 and does not increment every time I add numberplate.
How can I solve this issue?
It is because You are running the same code each time You add a plate to your db.
this:
$occupiedNumberOfSpots = 0;
should be taken from db as well. I guess it should be like that:
$totalNumberOfSpots = 100; // for example
$occupiedNumberOfSpots = $row['parking_spots']; // taken from db
instead of:
$totalNumberOfSpots = $row['parking_spots'];
$occupiedNumberOfSpots = 0;
I've recently implemented a custom liking and disliking feature for my comics site. I'd like to give users the ability to "Take back" their selection by "unclicking" the like or dislike button.
My function works by:
1) Passing button value (id = 'like' or id = 'dislike') via Jquery to
php script
2) script will first check if an ip exists in the database against
that given comic id... if not it will insert user's IP and current
comic ID... if it does, it originally said "you've already voted"... but now to implement "unliking", I will just have it run a delete query
3) then it will get total current likes for that comic id and
increment.
The way I think it can be done is if the user presses the button again, I basically run the opposite query... delete that user's vote from the table given that comic id... then decrement total likes for that image in the comics table.
So my questions are,
1) Is doing an insert query if they press a button once, then a delete
query if they "deselect" that same choice the best way to implement
this? Couldn't a user spam and overload the database by continuously
pressing the like button, thereby constantly liking and unliking?
Should I just implement some sort of $_SESSION['count'] for that ID?
2) If I'm storing a certain IP... what happens if several uniques
users happen to use the same computer at... let's say a netcafe... it
will always store that user's IP. Is storing against the IP the best
way to go?
Code if you need a reference:
<?php
include 'dbconnect.php';
$site = $_GET['_site'];
$imgid = intval($_GET['_id']);
$input = $_GET['_choice'];
if ($site == "artwork") {
$table = "artwork";
}
else {
$table = "comics";
}
$check = "SELECT ip, tablename, imgid FROM votes WHERE ip = '".$_SERVER['REMOTE_ADDR']."' AND tablename = '$table' AND imgid = $imgid";
$result = $mysqli->query($check);
if ($result->num_rows == 0) {
//Insert voter's information into votes table
$sql = "INSERT INTO
votes (ip, tablename, imgid)
VALUES
(\"".$_SERVER['REMOTE_ADDR']."\", \"$table\", $imgid)
ON DUPLICATE KEY UPDATE
imgid = VALUES(imgid)";
if (!$mysqli->query($sql)) printf("Error: %s\n", $mysqli->error);
/*while ($row = $result->fetch_assoc()) {
echo "you've inserted: " . $row['ip'] . ", " . $row['tablename'] . ", " . $row['imgid'] . ".";
}*/
$result = $mysqli->query("SELECT like_count, dislike_count FROM $table WHERE id = $imgid");
//put the counts into a list
list($likes, $dislikes) = $result->fetch_array(MYSQLI_NUM);
if ($input == "like") {
$sql = "UPDATE $table SET like_count = like_count + 1 WHERE id = $imgid";
$mysqli->query($sql);
$likes++;
}
else if ($input == "dislike") {
$sql = "UPDATE $table SET dislike_count = dislike_count + 1 WHERE id = $imgid";
$mysqli->query($sql);
$dislikes++;
}
}
else { //"unlike" their previous like for that given image id
$sql = "DELETE FROM
votes
WHERE (ip, tablename, imgid) =
(\"".$_SERVER['REMOTE_ADDR']."\", \"$table\", $imgid)";
if (!$mysqli->query($sql)) printf("Error: %s\n", $mysqli->error);
$result = $mysqli->query("SELECT like_count, dislike_count FROM $table WHERE id = $imgid");
//put the counts into a list
list($likes, $dislikes) = $result->fetch_array(MYSQLI_NUM);
if ($input == "like") { //remove like
$sql = "UPDATE $table SET like_count = like_count - 1 WHERE id = $imgid";
$mysqli->query($sql);
$likes--;
}
else if ($input == "dislike") {
$sql = "UPDATE $table SET dislike_count = dislike_count - 1 WHERE id = $imgid";
$mysqli->query($sql);
$dislikes--;
}
}
echo "Likes: " . $likes . ", Dislikes: " . $dislikes;
mysqli_close($mysqli);
?>
1) I would say yes, use a count feature to limit the number of attempts they can hit the button in succession. Probably wouldn't have much trouble unless they hit really high numbers, I believe a simple loop would do fine.
2) I would not store just the IP. I would try and use something more than just the IP as an Identifier, like the IP and the session cookie - that way it's unique. However on the look back to the server you would have to parse the entry from the db. Or perhaps the mac address. I'm not sure if you have access to that or not. How can I get the MAC and the IP address of a connected client in PHP?
I'm sure there's another way but conceptually that's how I see it working.
I'm making an auction type website that as you can imagine is supposed to delist products as they expire. the expiration is simply stored as MySQL datatype DATE.
so check_items.php:
<?php
function check_items()
{
$con = mysql_connect('localhost','heh','heh');
mysql_select_db('heh_db',$con);
$q = mysql_query("select last_check from ran_last",$con) or die("Check ran_last 1");
$r = mysql_fetch_assoc($q);
//if((time()-strtotime($r['last_check'])) >(60*60*17))//check only once every 17 hours
if(true)
{
$q2 = mysql_query("select * from Item where expired=0");
$remove = array(); $count=0;
while($row = mysql_fetch_assoc($q2))
{
if(strtotime($row['time_expire'])<time())
{
echo("strtotime: ".strtotime($row['time_expire'])." time: ".time());
$remove[$count] = $row['ItemID'];
$count++;
}
}
mysql_free_result($q2);
foreach($remove as $next)
{
echo($next);
$q3 = mysql_query(sprintf("select * from Item where ItemID='%s'",$next)) or die("check items outer query foreach");
$r3 = mysql_fetch_assoc($q3);
$q4 = mysql_query(sprintf("update Item set expired='1' where ItemID='%s'",$r3['ItemID']));
if(isset($r3['bidderID']))
{
$f1 = mysql_query(
sprintf("insert into notifications(userID,item_name,ItemID,type,info) values('%s','%s','%s','%s','%s')",
$r3['bidderID'],
$r3['item_name'],
$r3['ItemID'],
"BUY",
sprintf("You have won the bidding for this item. Contact the seller for details",
$r3['userID'],
$r3['ItemID'])
),$con
);
$f2 = mysql_query(
sprintf("insert into notifications(userID,item_name,ItemID,type,info) values('%s','%s','%s','%s','%s')",
$r3['userID'],
$r3['item_name'],
$r3['ItemID'],
"SELL",
sprintf("User has won the bidding for your item. You are encouraged to contact each other",$r3['bidderID'],
$r3['ItemID'])
),$con
);
}
else
{
$f1 = mysql_query(
sprintf("insert into notifications(userID,item_name,ItemID,type,info) values('%s','%s','%s','%s','%s')",
$r3['userID'],
$r3['item_name'],
$r3['ItemID'],
"SELL",
sprintf("Unfortunately no one bid on your item. You can view expired items from your userpage and re-upload",
$r3['userID'])
),$con
);
}
mysql_free_result($q3);
}
$done = mysql_query("insert into ran_last values()");
}
mysql_free_result($q);
}
?>
The script, fully functional, stores the last time it did an update and should only run once every 17 hours. Right now it runs whenever the function is called. Basically whenever I list a product it automatically gets delisted.
Uh, why are you doing it this way? you can do the filtering in PHP and save yourself a LOT of hassle:
SELECT ItemID
FROM Item
WHERE (expired = 0) AND (time_expire < (SELECT last_check FROM last_ran))
Plus, you're not even checking for this value when you do the real expiry check:
if(strtotime($row['time_expire'])<time())
^^^^^^--- shouldn't this be $r['last_check']?
*Here is what I am trying to acheive: *
Basically I have a form where people can submit events to our database. In the CMS I have a page which displays a record of the number of events.
*Here is what I have: *
After the button is clicked, this script is called:
if($subject_type == 'Event') {
$query = "SELECT town, update_id, event_validex ";
$query .= "FROM dev_town ";
$query .= "LEFT JOIN updates ON dev_town.town_id = updates.town ";
$query .= " WHERE sitename = '".SITENAME."'";
$query .= " AND month = " .date('m')." AND year =" .date('Y');
$querys = $this->tep_db_query($query);
$rows = $this->tep_db_fetch_array($querys);
extract($rows); //extract rows, so you don't need to use array
$eventid = $event_validex + 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
This works fine, however I cant seem to solve the next bit
This is the Problem
As you can see, it checks the database for the current month and adds it, this is providing that the sitename and that month are there, not a site and another month.
How would I get it to add the row in IF the sitename and month are not there?
I have been manually adding the months in now so that it works, and I am sure you can agree that's a ball ache.
Cheers peeps
if you want to check if site A + Month 11 exists do a select query against it and store the number of rows returned in a variable. ( $exists = mysql_num_rows("your query here"); )
then do an if statement against the $exists variable and proceed as you wish
if($exists) {
// update
} else {
// add
}
$insert = "INSERT INTO updates ('town','month','year','event_validex') VALUES ('".$town."','". date('m')."','". date('Y')."','1')";
$eventid = 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
}
}
this is what I have for the else statement there, however it will add one to the value if its there but will not add a new entry if its isnt.. ?
I don't see exactly how your method "checks the database for the current month and adds it "; I'll just assume that the tep_db_perform() method of your class handles this somehow.
(uhk! n00bed it; rest of the post was somehow chopped off?) Since you're already hitting the database with the select with the intent of using the data if a record is found, then you could use the resultset assigned to $rows as a means of checking if a record exists with SITENAME and Month.
See below:
if($subject_type == 'Event') {
// build query to check the database for sitename, month and year.
$query = "SELECT town, update_id, event_validex ";
$query .= "FROM dev_town ";
$query .= "LEFT JOIN updates ON dev_town.town_id = updates.town ";
$query .= " WHERE sitename = '".SITENAME."'";
$query .= " AND month = " .date('m')." AND year =" .date('Y');
// Execute Query(wrapper for $result = mysql_query I guess?)
$querys = $this->tep_db_query($query);
// Get a resultset from database. --> you could merge this into one method with $this->tep_db_query
$rows = $this->tep_db_fetch_array($querys);
if(count($rows) > 0) {
extract($rows); //extract rows, so you don't need to use array --> I try to stay away from extract() as it makes for random variables being created.
$eventid = $event_validex + 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
} else {
// insert new record into database
// updated with code to execute insert SQL query.
$insert = "INSERT INTO updates ('town','month','year','event_validex') VALUES ('".$town."','". date('m')."','". date('Y')."','1')";
$result = $this->tep_db_query($query);
}
....
}
If I've misunderstood something, please let me know, happy to work through it with you.
Hope this helps. :)