PHP: Reset MySQL database tables at the beginning of the month [duplicate] - php

This question already has an answer here:
How do I get PHP errors to display?
26 answers
Reference - What does this error mean in PHP?
32 answers
I wrote a page in php and html. After entering data such as name and presence at an event, they are inserted into a table in a database. I need the "presence" column to be reset on the first day of the month, being ready to receive new attendance data.
How could I ensure that, when the date is equal to 01 / month / year, the "attendance" column will be reset?
Here is the code with which I tried, but obviously it doesn't work:
<?php
$luca = "Presente";
$mysqli = new mysqli('localhost', 'root', 'password');
if ($mysqli->connect_error) {
die('Errore di connessione (' . $mysqli->connect_errno . ')' . $mysqli->connect_error);
}
// Creo il database
$mysqli->query("CREATE DATABASE presenze");
// Seleziono il database
$mysqli->query("USE presenze");
$mysqli->query("CREATE TABLE 'presenze'
( 'id' INT ( 5 ) NOT NULL AUTO_INCREMENT,
'nome' VARCHAR(30) NOT NULL ,
'cognome' VARCHAR(30) NOT NULL ,
'presenze' TEXT NOT NULL)");
$query = "INSERT INTO presenze (nome, cognome, presenza, id) VALUES ('Luca', 'Gamerro', '$luca', '1')";
if (!$mysqli->query($query)):
die($mysqli->error);
endif;
if (date() == '01/**/**'):
$query = $mysqli->prepare("DELETE FROM presenze WHERE id = 1");
$query->bind_param('i', $id);
$result = $query->execute();
endif;
?>
Thank you!

You can use MySQL Scheduled Event. Just enter this query to your database either by a PHP or direct SQL command.
CREATE EVENT your_event ON SCHEDULE
EVERY 1 MONTH
STARTS '2016-05-01 00:00:00'
ON COMPLETION PRESERVE ENABLE
DO
DELETE * FROM table_name WHERE id = 1

Related

Insert data to table then insert the newly added id to the foreign key [duplicate]

The 'id' field of my table auto increases when I insert a row. I want to insert a row and then get that ID.
I would do it just as I said it, but is there a way I can do it without worrying about the time between inserting the row and getting the id?
I know I can query the database for the row that matches the information that was entered, but there is a high change there will be duplicates, with the only difference being the id.
$link = mysqli_connect('127.0.0.1', 'my_user', 'my_pass', 'my_db');
mysqli_query($link, "INSERT INTO mytable (1, 2, 3, 'blah')");
$id = mysqli_insert_id($link);
See mysqli_insert_id().
Whatever you do, don't insert and then do a "SELECT MAX(id) FROM mytable". Like you say, it's a race condition and there's no need. mysqli_insert_id() already has this functionality.
The MySQL function LAST_INSERT_ID() does just what you need: it retrieves the id that was inserted during this session. So it is safe to use, even if there are other processes (other people calling the exact same script, for example) inserting values into the same table.
The PHP function mysql_insert_id() does the same as calling SELECT LAST_INSERT_ID() with mysql_query().
As to PHP's website, mysql_insert_id is now deprecated and we must use PDO. To do this with PDO, proceed as following:
$db = new PDO('mysql:dbname=database;host=localhost', 'user', 'pass');
$statement = $db->prepare('INSERT INTO people(name, city) VALUES(:name, :city)');
$statement->execute( array(':name' => 'Bob', ':city' => 'Montreal') );
echo $db->lastInsertId();
As #NaturalBornCamper said, mysql_insert_id is now deprecated and should not be used. The options are now to use either PDO or mysqli. NaturalBornCamper explained PDO in his answer, so I'll show how to do it with MySQLi (MySQL Improved) using mysqli_insert_id.
// First, connect to your database with the usual info...
$db = new mysqli($hostname, $username, $password, $databaseName);
// Let's assume we have a table called 'people' which has a column
// called 'people_id' which is the PK and is auto-incremented...
$db->query("INSERT INTO people (people_name) VALUES ('Mr. X')");
// We've now entered in a new row, which has automatically been
// given a new people_id. We can get it simply with:
$lastInsertedPeopleId = $db->insert_id;
// OR
$lastInsertedPeopleId = mysqli_insert_id($db);
Check out the PHP documentation for more examples: http://php.net/manual/en/mysqli.insert-id.php
I just want to add a small detail concerning lastInsertId();
When entering more than one row at the time, it does not return the last Id, but the first Id of the collection of last inserts.
Consider the following example
$sql = 'INSERT INTO my_table (varNumb,userid) VALUES
(1, :userid),
(2, :userid)';
$sql->addNewNames = $db->prepare($sql);
addNewNames->execute(array(':userid' => $userid));
echo $db->lastInsertId();
What happens here is that I push in my_table two new rows. The id of the table is auto-increment. Here, for the same user, I add two rows with a different varNumb.
The echoed value at the end will be equal to the id of the row where varNumb=1, which means not the id of the last row, but the id of the first row that was added in the last request.
An example.
$query_new = "INSERT INTO students(courseid, coursename) VALUES ('', ?)";
$query_new = $databaseConnection->prepare($query_new);
$query_new->bind_param('s', $_POST['coursename']);
$query_new->execute();
$course_id = $query_new->insert_id;
$query_new->close();
The code line $course_id = $query_new->insert_id; will display the ID of the last inserted row.
Hope this helps.
Try like this you can get the answer:
<?php
$con=mysqli_connect("localhost","root","","new");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO new values('nameuser','2015-09-12')");
// Print auto-generated id
echo "New record has id: " . mysqli_insert_id($con);
mysqli_close($con);
?>
Have a look at following links:
http://www.w3schools.com/php/func_mysqli_insert_id.asp
http://php.net/manual/en/function.mysql-insert-id.php
Also please have a note that this extension was deprecated in PHP 5.5 and removed in PHP 7.0
I found an answer in the above link http://php.net/manual/en/function.mysql-insert-id.php
The answer is:
mysql_query("INSERT INTO tablename (columnname) values ('$value')");
echo $Id=mysql_insert_id();
Try this... it worked for me!
$sql = "INSERT INTO tablename (row_name) VALUES('$row_value')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
$msg1 = "New record created successfully. Last inserted ID is: " . $last_id;
} else {
$msg_error = "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Another possible answer will be:
When you define the table, with the columns and data it'll have. The column id can have the property AUTO_INCREMENT.
By this method, you don't have to worry about the id, it'll be made automatically.
For example (taken from w3schools )
CREATE TABLE Persons
(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (ID)
)
Hope this will be helpful for someone.
Edit: This is only the part where you define how to generate an automatic ID, to obtain it after created, the previous answers before are right.

PHP/MySQL insert row then get 'id'

The 'id' field of my table auto increases when I insert a row. I want to insert a row and then get that ID.
I would do it just as I said it, but is there a way I can do it without worrying about the time between inserting the row and getting the id?
I know I can query the database for the row that matches the information that was entered, but there is a high change there will be duplicates, with the only difference being the id.
$link = mysqli_connect('127.0.0.1', 'my_user', 'my_pass', 'my_db');
mysqli_query($link, "INSERT INTO mytable (1, 2, 3, 'blah')");
$id = mysqli_insert_id($link);
See mysqli_insert_id().
Whatever you do, don't insert and then do a "SELECT MAX(id) FROM mytable". Like you say, it's a race condition and there's no need. mysqli_insert_id() already has this functionality.
The MySQL function LAST_INSERT_ID() does just what you need: it retrieves the id that was inserted during this session. So it is safe to use, even if there are other processes (other people calling the exact same script, for example) inserting values into the same table.
The PHP function mysql_insert_id() does the same as calling SELECT LAST_INSERT_ID() with mysql_query().
As to PHP's website, mysql_insert_id is now deprecated and we must use PDO. To do this with PDO, proceed as following:
$db = new PDO('mysql:dbname=database;host=localhost', 'user', 'pass');
$statement = $db->prepare('INSERT INTO people(name, city) VALUES(:name, :city)');
$statement->execute( array(':name' => 'Bob', ':city' => 'Montreal') );
echo $db->lastInsertId();
As #NaturalBornCamper said, mysql_insert_id is now deprecated and should not be used. The options are now to use either PDO or mysqli. NaturalBornCamper explained PDO in his answer, so I'll show how to do it with MySQLi (MySQL Improved) using mysqli_insert_id.
// First, connect to your database with the usual info...
$db = new mysqli($hostname, $username, $password, $databaseName);
// Let's assume we have a table called 'people' which has a column
// called 'people_id' which is the PK and is auto-incremented...
$db->query("INSERT INTO people (people_name) VALUES ('Mr. X')");
// We've now entered in a new row, which has automatically been
// given a new people_id. We can get it simply with:
$lastInsertedPeopleId = $db->insert_id;
// OR
$lastInsertedPeopleId = mysqli_insert_id($db);
Check out the PHP documentation for more examples: http://php.net/manual/en/mysqli.insert-id.php
I just want to add a small detail concerning lastInsertId();
When entering more than one row at the time, it does not return the last Id, but the first Id of the collection of last inserts.
Consider the following example
$sql = 'INSERT INTO my_table (varNumb,userid) VALUES
(1, :userid),
(2, :userid)';
$sql->addNewNames = $db->prepare($sql);
addNewNames->execute(array(':userid' => $userid));
echo $db->lastInsertId();
What happens here is that I push in my_table two new rows. The id of the table is auto-increment. Here, for the same user, I add two rows with a different varNumb.
The echoed value at the end will be equal to the id of the row where varNumb=1, which means not the id of the last row, but the id of the first row that was added in the last request.
An example.
$query_new = "INSERT INTO students(courseid, coursename) VALUES ('', ?)";
$query_new = $databaseConnection->prepare($query_new);
$query_new->bind_param('s', $_POST['coursename']);
$query_new->execute();
$course_id = $query_new->insert_id;
$query_new->close();
The code line $course_id = $query_new->insert_id; will display the ID of the last inserted row.
Hope this helps.
Try like this you can get the answer:
<?php
$con=mysqli_connect("localhost","root","","new");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO new values('nameuser','2015-09-12')");
// Print auto-generated id
echo "New record has id: " . mysqli_insert_id($con);
mysqli_close($con);
?>
Have a look at following links:
http://www.w3schools.com/php/func_mysqli_insert_id.asp
http://php.net/manual/en/function.mysql-insert-id.php
Also please have a note that this extension was deprecated in PHP 5.5 and removed in PHP 7.0
I found an answer in the above link http://php.net/manual/en/function.mysql-insert-id.php
The answer is:
mysql_query("INSERT INTO tablename (columnname) values ('$value')");
echo $Id=mysql_insert_id();
Try this... it worked for me!
$sql = "INSERT INTO tablename (row_name) VALUES('$row_value')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
$msg1 = "New record created successfully. Last inserted ID is: " . $last_id;
} else {
$msg_error = "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Another possible answer will be:
When you define the table, with the columns and data it'll have. The column id can have the property AUTO_INCREMENT.
By this method, you don't have to worry about the id, it'll be made automatically.
For example (taken from w3schools )
CREATE TABLE Persons
(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (ID)
)
Hope this will be helpful for someone.
Edit: This is only the part where you define how to generate an automatic ID, to obtain it after created, the previous answers before are right.

How to use INSERT statement AND retrieve the primary key with SELECT LAST_INSERT_ID(); statement in PHP at the same time? [duplicate]

The 'id' field of my table auto increases when I insert a row. I want to insert a row and then get that ID.
I would do it just as I said it, but is there a way I can do it without worrying about the time between inserting the row and getting the id?
I know I can query the database for the row that matches the information that was entered, but there is a high change there will be duplicates, with the only difference being the id.
$link = mysqli_connect('127.0.0.1', 'my_user', 'my_pass', 'my_db');
mysqli_query($link, "INSERT INTO mytable (1, 2, 3, 'blah')");
$id = mysqli_insert_id($link);
See mysqli_insert_id().
Whatever you do, don't insert and then do a "SELECT MAX(id) FROM mytable". Like you say, it's a race condition and there's no need. mysqli_insert_id() already has this functionality.
The MySQL function LAST_INSERT_ID() does just what you need: it retrieves the id that was inserted during this session. So it is safe to use, even if there are other processes (other people calling the exact same script, for example) inserting values into the same table.
The PHP function mysql_insert_id() does the same as calling SELECT LAST_INSERT_ID() with mysql_query().
As to PHP's website, mysql_insert_id is now deprecated and we must use PDO. To do this with PDO, proceed as following:
$db = new PDO('mysql:dbname=database;host=localhost', 'user', 'pass');
$statement = $db->prepare('INSERT INTO people(name, city) VALUES(:name, :city)');
$statement->execute( array(':name' => 'Bob', ':city' => 'Montreal') );
echo $db->lastInsertId();
As #NaturalBornCamper said, mysql_insert_id is now deprecated and should not be used. The options are now to use either PDO or mysqli. NaturalBornCamper explained PDO in his answer, so I'll show how to do it with MySQLi (MySQL Improved) using mysqli_insert_id.
// First, connect to your database with the usual info...
$db = new mysqli($hostname, $username, $password, $databaseName);
// Let's assume we have a table called 'people' which has a column
// called 'people_id' which is the PK and is auto-incremented...
$db->query("INSERT INTO people (people_name) VALUES ('Mr. X')");
// We've now entered in a new row, which has automatically been
// given a new people_id. We can get it simply with:
$lastInsertedPeopleId = $db->insert_id;
// OR
$lastInsertedPeopleId = mysqli_insert_id($db);
Check out the PHP documentation for more examples: http://php.net/manual/en/mysqli.insert-id.php
I just want to add a small detail concerning lastInsertId();
When entering more than one row at the time, it does not return the last Id, but the first Id of the collection of last inserts.
Consider the following example
$sql = 'INSERT INTO my_table (varNumb,userid) VALUES
(1, :userid),
(2, :userid)';
$sql->addNewNames = $db->prepare($sql);
addNewNames->execute(array(':userid' => $userid));
echo $db->lastInsertId();
What happens here is that I push in my_table two new rows. The id of the table is auto-increment. Here, for the same user, I add two rows with a different varNumb.
The echoed value at the end will be equal to the id of the row where varNumb=1, which means not the id of the last row, but the id of the first row that was added in the last request.
An example.
$query_new = "INSERT INTO students(courseid, coursename) VALUES ('', ?)";
$query_new = $databaseConnection->prepare($query_new);
$query_new->bind_param('s', $_POST['coursename']);
$query_new->execute();
$course_id = $query_new->insert_id;
$query_new->close();
The code line $course_id = $query_new->insert_id; will display the ID of the last inserted row.
Hope this helps.
Try like this you can get the answer:
<?php
$con=mysqli_connect("localhost","root","","new");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO new values('nameuser','2015-09-12')");
// Print auto-generated id
echo "New record has id: " . mysqli_insert_id($con);
mysqli_close($con);
?>
Have a look at following links:
http://www.w3schools.com/php/func_mysqli_insert_id.asp
http://php.net/manual/en/function.mysql-insert-id.php
Also please have a note that this extension was deprecated in PHP 5.5 and removed in PHP 7.0
I found an answer in the above link http://php.net/manual/en/function.mysql-insert-id.php
The answer is:
mysql_query("INSERT INTO tablename (columnname) values ('$value')");
echo $Id=mysql_insert_id();
Try this... it worked for me!
$sql = "INSERT INTO tablename (row_name) VALUES('$row_value')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
$msg1 = "New record created successfully. Last inserted ID is: " . $last_id;
} else {
$msg_error = "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Another possible answer will be:
When you define the table, with the columns and data it'll have. The column id can have the property AUTO_INCREMENT.
By this method, you don't have to worry about the id, it'll be made automatically.
For example (taken from w3schools )
CREATE TABLE Persons
(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (ID)
)
Hope this will be helpful for someone.
Edit: This is only the part where you define how to generate an automatic ID, to obtain it after created, the previous answers before are right.

MYSQL + PHP : “error in SQL syntax” when updating table using array and variables [duplicate]

This question already has an answer here:
How can I prevent SQL injection in PHP?
28 answers
I am a new developer and am trying to update a MYSQL table with modified user data after accepting a cc payment.
I have taken all the values that need to be updated or inserted into each table and it seems like the arguments are all correct... but the tables are not updating and I am getting the following error message:
Notice: Undefined variable: msqli in /home/ban50/public_html/app/return.php on line 74
Notice: Trying to get property of non-object in
/home/public_html/app/return.php on line 74
Error No: 0 - MySQL error You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the
right syntax to use near '' at line 1
Query: UPDATE `users` SET membership_id='1', mem_expire='' WHERE username=Blev80
#0 {main}
The code that I am using is as follows:
This is the standard "straight forward" variables. The $_POST[] variables are those that I receive from the payment gateway as an (array):
$host="localhost"; // Host name
$dbusername="Blev80"; // Mysql username
$password="MYPASS"; // Mysql password
$db_name="Blev80DB"; // Database name
$tbl_name="users"; // Table name
$mname=$_POST['li_0_product_id']; //membership/product ID
$appusername=$_POST['username'];//Users "Username"
$amch = $_POST['li_0_price']; //purchase price
$amtot = $_POST['total']; //total price
$curr = 'USD'; //currency
$muid = $_POST['userid']; // USER ID
I then am trying to insert the END DATE of the purchase - I thought to use the strtotime (+ 1 month ) logic here:
$duration = $_POST['li_0_recurrence']; //recurrence calculation
$eDate =strtotime('+$duration'); //the END date of the purchase
$memexpire = $eDate ; // my reference for the table (this may be a redundant step but it helps me to think in this way
for testing purposes I echo'd the End Date:
echo $eDate;
I ASSUME the above is working but I cant verify whats going on yet since I seem to have a problem in the code below:
$data = array(
'txn_id' => time(),
'membership_id' => $mname,
'user_id' => $muid,
'rate_amount' => $amch,
'tax' => '0',
'coupon' => '0',
'total' => $amtot,
'ip' => $_SERVER['REMOTE_ADDR'],
'date' => "NOW()",
'pp' => "2CO",
'currency' => 'ZAR',
'status' => 1);
if ($_POST['credit_card_processed'] === 'Y') {
//connect to DB
$mysqli = new mysqli("$host", "$dbusername", "$password", "$db_name");
//build queries
$query = "UPDATE `users` SET membership_id='$mname', mem_expire='$eDate' WHERE username=$appusername";
$mins = "INSERT INTO payments ($data)";
//run queries
$mysqli->query($query);
$mysqli->query($mins);
//error checking
if ($mysqli->error) {
try {
throw new Exception("MySQL error $mysqli->error <br> Query:<br> $query", $msqli->errno);
} catch(Exception $e ) {
echo "Error No: ".$e->getCode(). " - ". $e->getMessage() . "<br >";
echo nl2br($e->getTraceAsString());
}
}
else {
echo "Thanks database updated";
}
}
else {
echo "Credit card payment failed";
}`
So I have 2 issues
1) The error notice on line 74 references my error checking component
throw new Exception("MySQL error $mysqli->error <br> Query:<br> $query", $msqli->errno);
2) Something is wrong with the MYSQL syntax and the tables are not updating.
I have tried enclosing the table references in backticks, but I still get the message.
I have tried changing the mysqli->error to mysqli(error)
I have been to numerous SO questions and answers and have incorporated code where it seems to be necessary
-- I honestly don't know what else to try - I have been looking at the same 80 lines of code for 2 days now :)
Any help or feedback would be hugely appreciated!
Your update query $query = "UPDATEusersSET membership_id='$mname', mem_expire='$eDate' WHERE username=$appusername" translates to something like
UPDATE `users`
SET membership_id='mname', mem_expire='2045-08-09'
WHERE username=some_username
------------------------------------^
You are missing ' around your $appusername.
$query = "UPDATE `users` SET `membership_id` = '{$mname}', `mem_expire` = '{$eDate}' WHERE `username` = '{$appusername}"
Don't need quotes around parameters here, because there is no concatenation of strings.
$mysqli = new mysqli("$host", "$dbusername", "$password", "$db_name");

Session ID does not appear as a field in phpmyadmin

I am hoping one of you PHP/SQL experts can help me. I am creating a table in database and I have written the following PHP file which contains SQL functions (the full coding is not given below):
<?php
session_start();
$sessionID = $_SESSION['sessionID'];
if($sessionID == "")
{
$sessionID = $_SERVER['REMOTE_ADDR'] . " " . date("Y-m-d H:i:s",time());
$_SESSION['sessionID']=$sessionID;
}
// all the codes relating to connection to database here
$sql = "ALTER TABLE Countries
ADD COLUMN (
`SessionID` VARCHAR2(30) NOT NULL,
`Landarea` SMALLINT(5) NOT NULL ,
`Manpower` SMALLINT(5) NOT NULL,
`GrossNationalProduct SMALLINT(12) NOT NULL);";
$sql = "UPDATE Countries
SET `Landarea` = '$landra',
`Manpower` = '$manpow',
`GrossNationalProduct` = '$gnp'
where sessionID = '$sessionID'";
But when I try to run the code on the browser, I keep getting the message:
Error: Unknown column 'sessionID' in 'where clause'
This has happened 5 times already. Could someone please tell me how I can correct my code so that one of the fields in the database has the sessionID ?

Resources