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
Related
I am currently working on a project which will sell a product to a user, and on checkout completion, the user will enter an email address. I have been trying (but to no avail so far) to use MySQL to put this data into a database. Only in a certain way. I need the input data to use the UPDATE method to be put into an already existing row. This row should match the following criteria. It should not have already been used, the email should not already exist within the database. I have tried so many different pieces of MySQL, I get all sorts from syntax errors to it updating every record in my table, I have gotten as far as it updating just one, but not checking if it already exists. I was hoping for a little insight as to how I can improve!
Code as follows:
<?php
$servername = "localhost";
$username = "Josh";
$password = "10584066";
$dbname = "customers";
// Get email address from input form
$Email = $_GET['keyword'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE list SET Email='$Email' , In_Use='1' WHERE In_Use='0' LIMIT 1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
header('Location: /liteservers/logon/wood.php');
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
So, as you can see. The code is working almost as intended, I just want it to also check to see IF the email is already in the database and if it is, perhaps add the time that it attempted to record a new email within the same row as the already found existing email. I hope this actually makes sense if you need any more info that I haven't provided, let me know!
Use INSERT ON DUPLICATE KEY UPDATE syntax and mysql_affected_rows will tell you if its and insert or update.
I am trying to design a scoreboard for a project for my local youth club and would like to be able to click a button onto a wordpress page that will run a PHP script to update a value by 1 in a sql db table, then i can grab the value and display it else where.
Not too worried about passwords being used in scripts at this will only be used within the local network that nobody else has access to, have looked around and found a few bits of code but im not able to actually get it working, here's what i've got so far.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "sot";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = UPDATE wp_sotstats SET CaptainChest=CaptainChest+1 WHERE id=1
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The database name is 'sot' the table i want to update is called 'wp_sotstats' and the field within the table is 'CaptainChest' i only need this to really work with just the one entry which the id is '1'
Any thoughts?
$sql = UPDATE wp_sotstats SET CaptainChest=CaptainChest+1 WHERE id=1
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
Is not creating record, it updating it. For me, I will take current value from database as Select, then do ++ to it and do Update query.
$sql = UPDATE wp_sotstats SET CaptainChest=CaptainChest+1 WHERE id=1
Please wrap it in quotes and finish statement with semicolon
I want to insert time into MySQL and retrieve it then compare with current time.
Despite of the fact, a plenty of questions regarding to this topic, after hours of searching, most of them answered with mySQL Queries only or how to format timestamp. It is really hard to find out for my case. but I guess my problem differs. I cannot even start with the retrieved datum.
The idea is that when a data posted, it checks the last_update_time in DB with country_code. If last_update_time is within an hour, it just retrieve the time and other data. and If the the time difference is over an hour, it updates the row in DB.
The server is located on a remote site so the timezones are different.And using php 7 and mySQL 5.7
The inserting time into DB in a timezone specified works well, the last_updated_time field type is DATETIME in MySQL.
function insertData($countryCode) {
// Create connection
$conn = new mysqli(DBHOST, DBUSER, DBPASSWORD, DBNAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
date_default_timezone_set('Asia/Seoul');
$currentTime = date("Y-m-d H:i:s");
$sql = "INSERT INTO my_table (country_code, last_updated_time)
VALUES ('$countryCode', '$currentTime')";
if (mysqli_query($conn, $sql)) {
echo "INSERT Succeeded";
}else {
echo "Failed INSERT";
}
$conn->close();
}
and later I need to compare the old time(saved time) with current time when a page refreshes. I expect people from several timezones so I set date_default_timezone_set().
function compareTime($countryCode){
$conn = new mysqli(DBHOST, DBUSER, DBPASSWORD, DBNAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT last_updated_time FROM my_table WHERE country_code = '$countryCode'";
$savedTime = mysqli_query($conn, $sql);
if($savedTime->num_rows == 0) {
echo 'does not exist';
} else {
date_default_timezone_set('Asia/Seoul');
$currentTime = date("Y-m-d H:i:s");
$oldtime = strtotime($savedTime);
$timeDiffInSec = intval(strtotime($currentTime) - $oldtime) % 60;
$formattedOldTime = date("Y-m-d H:i:s",$oldtime);
echo '<p>Current Time: '.$currentTime.'</p>';
echo '<p>Old Time: '.$formattedOldTime.'</p>';
echo '<p>Time Difference: '.$timeDiffInSec.'</p>';
// Do the job only after 1 hour
if ($timeDiffInSec > 60 && $currentTime > $oldtime) {
// Do the job and update DB
}
}
$conn->close();
}
compareTime('us');
The problem I have is that I don't know how to properly get the saved time from mySQL in PHP. I cannot print the old time on the webpage or compare those two time.
Although the saved time looks like 2017-12-26 17:07:37 when I see via myPhpAdmin, those echos print like below.
Current Time: 2018-01-01 06:35:55
Old Time: 1970-01-01 09:00:00
Time Difference: 55
Even echo $savedTime; prints nothing. How can I resolve this? Thank you in advance.
$savedTime is a query result, you should fetch the results later on.
Try this:
$oldtime = strtotime(mysqli_fetch_array($savedTime)[0]);
By the way, as Funk Forty Niner reminded me on the comments, you should consider to use prepared statements to avoid SQL injection attacks. Have a look on the link, it's worth it.
I'm fairly new to stack overflow. i am creating a site were you type text in to 2 text boxes and it sends it to a database. i need it then to tell me what the id of that was save it as a session and then upload it to another database. sounds confusing. but I'm stuck of one part. its viewing the result thats from just that user. i have tried just showing the the last id of the last uploaded but it can be very unreliable if multiple people are trying to upload data and know there exact session. I'm also having trouble linking the session with the id. below is the code for the forum saving to the database. I'm pretty confident with sending the id of that users inputed data to another database. I'm just stuck on finding that users inputed texts id and creating a session holding the id number
<?php
header("Location:myscorenum.php");
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "score";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
session_start();
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "working";
}else{
//3.2 When the user visits the page first time, simple login form will be displayed.
}
$value = $_POST['name'];
$value1 = $_POST['description'];
$sql = "INSERT INTO all_scores (name, description) VALUES ('$value','$value1')";
if ($conn->query($sql) === TRUE) {
echo "<a href=https://twitter.com/angela_bradley>My Twitter</a>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
ill have the processing to inset to another database in another file. I'm confident with uploading a specific session.
any questions don't hesitate to message me. thanks for your kind help.
You can use this:
mysqli::$insert_id -- mysqli_insert_id — Returns the auto generated id used in the last query
Like: echo $conn->insert_id;
Since you call it on $conn which is a mysqli instance that already has a connection, it will return your last inserted id, irregardless of other activities on the db (other queries do not affect the correctness of the output)
I edited my answer. This is the final part of your code and I've just added one line of code to it. Look if this is what you're looking for.
If this isn't working than make sure your database id field is AI.
if ($conn->query($sql) === TRUE) {
$id=$conn->insert_id; //this is where you get the last inserted id.
echo "<a href=https://twitter.com/angela_bradley>My Twitter</a>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
To use a session and set the ->insert_id to a session variable and use it in any other page, you can do this:
if ($conn->query($sql) === TRUE) {
session_start();
$_SESSION['id']=$conn->insert_id;
echo "<a href=https://twitter.com/angela_bradley>My Twitter</a>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
and now in any other page do this to retrieve the session variable:
session_start();
$id=$_SESSION['id'];
here you go and you get the id.
Are you still confused?
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