I have a database named hrRecords and a table named employee in that table. It has a field named contract_end. In that field, I have the contract info of the employee specifically the duration of said contract (datetime).
What I want to achieve is to check that info to see when the contract is going to come to an end and if it is display a message saying so.
I am very new to php and I tried something but I am totally lost I was wondering if I could get some guidance of some sort thank you for your support:
<?php
$employee1= mysql_real_escape($_GET["employee1"]);
$DataBase = "hrRecords";
mysql_connect("server","username", "password") or die(mysql_error());
mysql_select_db($DataBase) or die(mysql_error());
$query = SELECT contract_end From hrRecords
// current date being compared
if(contract_end== date(Y-m-d) {
echo "something"
}
else {
echo " employe name , Your contract will expire in x amount of days "
}
/* This is the point where everything becomes fuzzy because im thinking there has to be some other way to do this for all the employees */
fist stop using mysql it has been depreciated
use either mysqli or pdo. I will show you how to do it with mysqli
<?php
$employee1= mysql_real_escape($_GET["employee1"]); // i am not sure why you are doing this since you are not using this any where
$DataBase = "hrRecords";
$ServerName = "server";
$UserName = "username";
$Password = "password";
$mysqli = new mysqli($ServerName, $UserName, $Password,$DataBase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// since i don't know all of colum names i am making them up
$stmt= $mysqli->prepare("SELECT contract_end employe_name From hrRecords");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($contract_end, $employe_name)
while($stmt->fetch()) { // this will go thorough all of the records
// current date being compared
if($contract_end== date(Y-m-d) {
echo "something"
} else {
// you need some more code here to find x
echo " $employe name , Your contract will expire in x amount of days "
}
}
i don't know if this will help you at all. you did not have enough info for a better answer
Related
I am working with a coupon code website, it has a products section. Instead of pulling data from API server of shopping sites every time a visitor loads the page, I want to store the data in SQL and use it..
But the data should update every hour or only if an hour is passed.
cron job is not required as I dont want to happen it automatically.
If there is 100 webpage users in an hour, they will get the same data, but when the first user comes after 1 hour time, it should overwrite the products's information in SQL.
I got the following code from w3schools.com and it work fine for saving data in SQL.
I hope some can help me to overwrite data only if it the data older than 1 hour. Otherwise it should act as "data already exists".
<?php
$servername = "localhost";
$username = "nuser";
$password = "pass";
$dbname = "db";
$ProductId = "smartphone";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$check=mysqli_query($conn,"select * from testdb where productid='$ProductId'");
$checkrows=mysqli_num_rows($check);
if($checkrows>0) {
echo "Data Already Exists";
} else {
//insert results from the form input
$sql = "INSERT INTO Flipkart (productid, title, price)
VALUES ('productid','title','price')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();}
?>
The above code saves data in database, it can also detect duplicate data. but I want to add just one more function, which will overwrite data if the current data time is older than 1 hour. database has a TIMESTAMP "reg_date" column, which stores created date and time in YYYY-MM-DD HH:MM:SS format.
I am new to SQL and php, so pardon me if there is any problems with the question...
You can use a cron job.
This is the best explanation with code for PHP I have found so far for cron job:
https://code.tutsplus.com/tutorials/managing-cron-jobs-with-php--net-19428
Problem:
I want to get the MAX "SID" from my Database and add one. I handle the input via an Form that i submit through the HTTP Post Method. I get the current MAX "SID" from my database, then i put the value into an HTML input field and add one. For some reason this just works every other time. So the output i get is:
Try = 1
Try = 1
Try = 2
Try = 2
and so on. Would be nice if someone could point me in the right direction.
PHP get MAX(ID):
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "soccer";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql = "SELECT MAX(SID) FROM spieler";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$lastID = $row["MAX(SID)"];
}
}
mysqli_close($conn);
PHP insert in database:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "soccer";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?><br><?php
$sql = "INSERT INTO spieler VALUES ('$sid', '$name', '$verein',
'$position', '$einsaetze', '$startelf', '$tore',
'$torschuesse', '$eigentore', '$vorlagen', '$elfmeter',
'$verwandelt', '$gegentore', '$gelb',
'$rot', '$fouls', '$zweikampf', '$pass', '$note')";
if(mysqli_query($conn, $sql)){
echo "Success";
}else{
echo "Failed" . mysqli_error($conn);
}
mysqli_close($conn);
HTML & PHP Input Field:
<tr>
<td><input id="SID" name="SID" readonly value="<?php echo $lastID += 1;
?>"></td>
</tr>
Screenshot of the page:
The paragraph "Spieler ID:" is where I put the "SID" so that everytime the page loads the next free ID gets automatically loaded into the input field.
I want to get the MAX "SID" from my Database and add one
No. You don't. You really, really don't.
This is the XY Problem.
You can do it by running a system wide lock and a autonomous transaction. It would be a bit safer and a lot more efficient to maintain the last assigned value (or the next) as a state variable in a table rather than polling the assigned values. But this still ignores the fact that you going to great efforts to assign rules to what is a surrogate identifier and hence contains no meaningful data. It also massively limits the capacity and poses significant risks of both accidental and deliberate denial of service.
To further compound the error here, MySQL provides a mechanism to avoid all this pain out of the box using auto-increment ids.
While someone might argue that these are not portable, hence there may be merit in pursuing another solution, that clearly does not apply here, where your code has no other abstraction from the underlying DBMS.
So I learn PHP, and I want to try to build something like a small monetized url shortener, just for fun! So every time somebody clicks on a users link, one click should be added in the MySQL table (for the user). I tried a lot of scripts but they all don't work.
<html lang="en-US">
<?php
$servername = "***";
$username = "***";
$password = "***";
$dbname = "***";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_query("UPDATE users SET 'hits' = 'hits'+1 WHERE id = 1");
?>
And after then display the clicks in the users dashboard via $row['']... but it doesn't count the clicks when I onload the page... the number in the mysql database does'nt change... what am I doing wrong. Alsom do you have and more professional idea how to do that, cause I know that this isn't a good alternative... I also have something like that , but it doesnt work too...
$user_ip=$_SERVER['REMOTE_ADDR'];
$check_ip = mysqli_query("select userip from pageview where page='1' and userip='$user_ip'");
if(mysqli_num_rows($check_ip)>=1)
{
}
else
{
mysqli_query("insert into pageview values('1','1','$user_ip')");
mysqli_query("update users set 'hits' = 'hits'+1 where id=1 ");
}
If you're used to mysql_query, you need to do this differently, a connection handle is required, no longer implicit. The best way to avoid slipping up on this is to use the object-oriented calling method:
$conn->query(...);
This approach is often substantially less verbose.
I am trying to compare a MySQL table column which I have imported to my script and compare it with a PHP value which I have defined.
I am trying to make an if loop that checks if any of the values in the column are equal to the variable.
// Connect to database containing order information
$servername = "server";
$username = "user";
$password = "pass";
// Create connection
$conn = new mysqli($servername,$username,$password);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
// define variables and set to empty values
$name = $ordernumber = "";
// Load up data from the form
$ordernumber = ($_POST['order_number']);
// Get SQL info
$sql = "SELECT order_number FROM p_orders;";
if ($conn->query($sql) === TRUE)
{
echo "Checked Orders.....";
}
else
{
echo "Failed to check orders, please contact Support for assistance" . $conn->error;
}
// Checking Script
if ($ordernumber === $orders)
{
echo "Order Number Found.... Let's Select a Seat";
}
else
{
echo "Your Order was not found, either you did not order a reservation ticket, have not waited 3 days or you entered the number wrong. If issues persist then please contact Support."
};
The end part of the script should be like this...
$stmt = $mysqli->stmt_init();
if ($stmt->prepare('SELECT order_number FROM p_orders WHERE orderID = ?')) {
$stmt->bind_param('s',$_POST['order_number']); // i if order number is int
$stmt->execute();
$stmt->bind_result($order_number);
$stmt->fetch();
if (!empty($order_number))
echo "Order Number Found.... Let's Select a Seat";
}else {
echo "Your Order was not found...";
}
$stmt->close();
}
$mysqli->close();
...note that the query now looks for only the records that match and note the use of prepared statement to make safe the post variable from SQL Injection.
The reason to collect only the matching items from SQL is otherwise, if you have a million records, the database would return all of them and then PHP will need to loop through them (this can cause maximum execution, memory and other errors). Instead databases where built to look things up like this - note an index on this field would be good and also use of a "youtube style" id is recommended, which is why I've assumed the use of a string for it's instead of a number as the variable minght imply - and it's not the "id" which is good for a number of reasons... I've added a link to explain "youtube style" id which I'll not go into detail here but there is a lot of win in using that :)
UPDATED based on...
http://php.net/manual/en/mysqli-stmt.prepare.php
MySQL prepared statement vs normal query. Gains & Losses
https://www.youtube.com/watch?v=gocwRvLhDf8 (Will YouTube Ever Run Out Of Video IDs?)
Preferably use a WHERE clause searching for the order id and mysqli prepared statement, like below.
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$name = "";
// Load up data from the form
$ordernumber = $_POST['order_number'];
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT COUNT(*) FROM p_orders WHERE orderID=?")) {
/* bind parameters for markers */
$stmt->bind_param("i", $ordernumber ); // "i" if order number is integer, "s" if string
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($counter);
/* fetch value */
$stmt->fetch();
if ($counter>0) { // if order id is in array or id's
echo "Order Number Found.... Let's Select a Seat";
} else {
echo "Your Order was not found, either you did not order a reservation ticket, have not waited 3 days or you entered the number wrong. If issues persist then please contact Support."
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
I am working on an academy website here at www.grmaedu.com
Web Specs: Built on Wordpress with the following plugins, Visual Form Builder Pro & Revolution Slider
So i have managed to do 90% of the work. My query is I want to assign automatic roll numbers to students who are submitting the application form here at www.grmaedu.com/application
Here are the remaining things I want to do:
Automatically assign Roll Number to students "after or on " form submission
Submit the form to the concerned mySql Database, Right now it emails correctly to the designated email address with no issues. All thanks to Visual Form Builder Pro
The date picker field is not working in the application form(I even updated my jQueryUI file)
I hope the provided details are enough for the solution.
I finally figured a way out. Here are the steps which i performed.
I installed a WP Plugin named Contact Form DB. This plugin saves all the form submitted values and stores them in a mySQL database.
I opened up phpmyadmin to see how it was stored and found it in one of the tables. I noticed that each entry had an unique id number. That is what I was trying to do. This plugin made it easier for me.
Then i created a Page template file name rollnumber.php and inserted the following code in
<?php
/* Define Connection properties */
$servername = "localhost";
$username = "grmaedu_wp2";
$password = "******";
$dbname = "grmaedu_wp2";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT entries_id FROM `wp_vfb_pro_entries` ORDER BY entries_id DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$a = $row["entries_id"];
$a++;
echo "<h3>Your Roll Number assigned is: " . $a . "</h3>";
//echo "id: " . $row["entries_id"] . "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
So now when the page loads it automatically fetches the unique id and adds 1 to the last submitted id and voila a new roll number is generated.
Index key is the best option to set as roll number. because it is unique and then you can get user data directly form this id.
<?php
/* Define Connection properties */
$servername = "localhost";
$username = "grmaedu_wp2";
$password = "******";
$dbname = "grmaedu_wp2";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT entries_id FROM `wp_vfb_pro_entries` ORDER BY entries_id DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
echo "<h3>Your Roll Number assigned is: " . mysqli_insert_id() . "</h3>";
//echo "id: " . mysql_insert_id() . "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>