Timestamp to get current time/date - php

I need simple code using PHP to get the current date/time using TIMESTAMP and insert this into a database.
I have a field called "ArrivalTime" within a database as TIMESTAMP.
EDIT:
<?php
$con = mysql_connect("localhost","root","") or die('Could not connect: ' . mysql_error());
mysql_select_db("a&e", $con) or die('Could not select database.');
// validate
$time = time(); $date = date('Y-m-d H:i:s',$time);
$sql="INSERT INTO Patient(Forename, Surname, Gender, Date_Of_Birth, Address, Patient_History, Illness, Priority, Arrival_Time)
VALUES('$patient_name', '$patient_lastname', '$gender', '$date', '$address', '$history', '$illness', '$priority', '$time')";
mysql_query($sql,$con) or die('Error: ' . mysql_error());
echo "1 record added";
// close connection
mysql_close($con);
?>
Many thanks

main.php
<?php
require('connect.php');
$time = time();
$sql = "INSERT INTO yourtablename (ArrivalTime) Values ('$time')";
mysql_query($sql);
?>
P.S: in the sql statement i'm sure you'll need to put other things in the other fields ,so you just replace the one above by this:
$sql = "INSERT INTO yourtablename (field1, field2, ArrivalTime) Values ('$value1','$value2','$time')";
connect.php
<?php
$error = "Couldn't connect";
$connect = mysql_connect("localhost","username","password") or die($error);
mysql_select_db("yourdatabase") or die($error);
?>

The query will be:
INSERT INTO mytable(ArrivalTime) VALUES(UNIX_TIMESTAMP())

mysql has a function UNIX_TIMESTAMP() for getting a Unix timestamp as an unsigned integer.
Example:
mysql> SELECT UNIX_TIMESTAMP();
-> 1196440210
So you can use this sql query:
insert into tableName(ArrivalTime) values(UNIX_TIMESTAMP())

Related

PHP to mySQL - duplicating entry when finding insert ID

I'm having an issue with my PHP form submission to MySQL - it's a multi_query insert that is supposed to feed two tables. Everything was working fine, but I recently set up a foreign key relationship and something in the process of getting the mysqli_insert_id for the entry to the parent table causes the first entry to be entered twice in that table - to use the table names from my code below, the master table entry is being inserted twice, and the local table entry is inserted once with the $master_id of the first master entry. I really only have a functional understanding of PHP - can someone explain why this is happening and how I can fix it so that the entry is inserted only once into each table?
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$date = $_POST['date'];
$time = $_POST['time'];
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
$accuracy = $_POST['accuracy'];
$species = $_POST['species'];
$sql = "INSERT INTO master (date, time, latitude, longitude, accuracy, species, source)
VALUES ('$date', '$time', '$latitude', '$longitude', '$accuracy', '$species', 'source A');";
mysqli_query($conn, $sql);
$master_id = mysqli_insert_id($conn);
$sql .= "INSERT INTO local (Master_ID, date, time, latitude, longitude, accuracy, species)
VALUES ('$master_id', '$date', '$time', '$latitude', '$longitude', '$accuracy', '$species');";
if ($conn->multi_query($sql) === TRUE) {
$conn->close();
header("Location:http://d-bird.org/thank%20you.html");
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sql .= "INSERT INTO local (Master_ID, date, time, latitude, longitude, accuracy, species)
VALUES ('$master_id', '$date', '$time', '$latitude', '$longitude', '$accuracy', '$species');";
should be
$sql = "INSERT INTO local (Master_ID, date, time, latitude, longitude, accuracy, species)
VALUES ('$master_id', '$date', '$time', '$latitude', '$longitude', '$accuracy', '$species');";
without the dot concatenation for $sql
You are adding the second insert to the first.
changing
$sql .= "INSERT INTO local (Master_ID, date, time, ...
to
$sql = "INSERT INTO local (Master_ID, date, time, ...
should fix your issue.

SQL query is empty?

This php is suposed to send five attributes {id, description, email, price, shape} to the sales table in the salesinformation database.
<?php
define('DB_NAME', 'salesinformation');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Cannot connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('Cannot use ' . DB_NAME . ': ' . mysql_error());
}
$value = $_POST['description'];
$value2 = $_POST['email'];
$value3 = $_POST['price'];
$value4 = $_POST['shape'];
$sql = mysql_query("INSERT INTO sales (id, description, email, price, shape) VALUES ('', '$value', '$value2', '$value3', '$value4')");
if (!mysql_query($sql)){
die('Error: ' . mysql_error());
}
mysql_close();
?>
If I echo $value it prints out the correct information that I filled in my html form (So the part that extracts values from the HTML is working atleast). I run xampp and created the database with PhpMyAdmin, and when this PHP runs all I get is Error: Query was empty and nothing is added to the database at all.
What makes the mysql_query empty?
EDIT: I had missed a ' sign at one of the values.
Now instead I get this error message
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 '1' at line 1
Question: What makes the mysql_query empty?
It's you, who calls mysql_query without a real query:
$sql = mysql_query("INSERT INTO sales (id, description, email, price, shape) VALUES ('', '$value', '$value2', '$value3', '$value4')");
if (!mysql_query($sql)){ // <---- look here
die('Error: ' . mysql_error());
}
What we see in your code is that you pass $sql to mysql_query which isn't a valid query and you can check it with var_dump($sql);
Remove the ID column from your query. Assuming you made made it a INDEX (and AUTO_INCREMENT) probably:). You can either remove it out the fieldlist, or instead of the '' put a NULL there :).

Php Post to two tables in Mysql

I'm trying to POST to two tables at the same time. I'm trying to get the DonorID to display in to another table under $description. I'm able to just write any text in the $description, but I need it to be dynamic not static, which is what the text is. I have two tables; the first is accounting and the second is donations. I'm trying to alter the $description='Donation from Donor'; and have the donor that made the transaction be listed where the Donor is. Any suggestions would be greatly appreciated.
Here is my code:
<?php
$dbserver = "localhost";
$dblogin = "root";
$dbpassword = "";
$dbname = "";
$date=$_POST['date'];
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$middleinitial=$_POST['middleinitial'];
$organization=$_POST['organization'];
$donorid=$_POST['donorid'];
$paymenttype=$_POST['paymenttype'];
$nonmon=$_POST['nonmon'];
$event=$_POST['event'];
$Income=$_POST['Income'];
$account='Revenue';
$description='Donation from Donor';
$transactiontype='Income';
$Expense='0.00';
$con = mysql_connect("$dbserver","$dblogin","$dbpassword");
if (!$con)
{
die('Could not connect to the mySQL server please contact technical support
with the following information: ' . mysql_error());
}
mysql_select_db("$dbname", $con);
$sql = "INSERT INTO donations (date, firstname, middleinitial, lastname,
organization, donorid, paymenttype, nonmon, Income, event)
Values
('$date','$firstname','$middleinitial','$lastname','$organization',
'$donorid','$paymenttype','$nonmon','$Income','$event')";
$sql2 = "INSERT INTO accounting (date, transactiontype, account,
description, Income, Expense)
VALUES ('$date','$transactiontype','$account','$description','$Income','$Expense')";
mysql_query($sql2);
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
header( 'Location: http://localhost/donations.php' ) ;
?>
As i said i would personaly use mysqli for new project, here a sample of you code with mysqli:
$dbserver = "localhost";
$dblogin = "root";
$dbpassword = "";
$dbname = "";
$date=$_POST['date'];
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$middleinitial=$_POST['middleinitial'];
$organization=$_POST['organization'];
$donorid=$_POST['donorid'];
$paymenttype=$_POST['paymenttype'];
$nonmon=$_POST['nonmon'];
$event=$_POST['event'];
$Income=$_POST['Income'];
$account='Revenue';
$description='Donation from Donor';
$transactiontype='Income';
$Expense='0.00';
//opening connection
$mysqli = new mysqli($dbserver, $dblogin, $dbpassword, $dbname);
if (mysqli_connect_errno())
{
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "INSERT INTO `donations` (`date`, `firstname`, `middleinitial`, `lastname`, `organization`, `donorid`, `paymenttype`, `nonmon`, `Income`, `event`) Values ('$date','$firstname','$middleinitial','$lastname','$organization', '$donorid','$paymenttype','$nonmon','$Income','$event')";
$sql2 = "INSERT INTO `accounting` (`date`, `transactiontype`, `account`, `description`, `Income`, `Expense`) VALUES ('$date','$transactiontype','$account','$description','$Income','$Expense')";
$query1 = $mysqli->query($sql) or die($mysqli->error.__LINE__);
$query2 = $mysqli->query($sql2) or die($mysqli->error.__LINE__);
//closing connection
mysqli_close($mysqli);
header( 'Location: http://localhost/donations.php' ) ;
UPDATE
you can add donorid simply placing both vars in the query like:
$sql2 = "INSERT INTO `accounting` (`date`, `transactiontype`, `account`, `description`, `Income`, `Expense`) VALUES ('".$date."','".$transactiontype."','".$account."','".$donorid . " " . $description."','".$Income."','".$Expense."')";
this way i just separate donorid and description with a space but you can add anything you want to in plain text:
'".$donorid . " - " . $description."'
After this
$sql = "INSERT INTO donations (date, firstname, middleinitial, lastname,
organization, donorid, paymenttype, nonmon, Income, event)
Values
('$date','$firstname','$middleinitial','$lastname','$organization',
'$donorid','$paymenttype','$nonmon','$Income','$event')";
put
mysql_query($sql);
Please execute the query.
Things I see is ..
First your just executing your $sql2 but not the other $sql statement
Another is while inserting you declared some columns name that is a mysql reserved word (date column)
you should have `` backticks for them..
Refer to this link MYSQL RESEERVED WORDS
additional note: Your query is also vulnerable to sql injection
SQL INJECTION
How to prevent SQL injection in PHP?
Just write after insert on trigger on first table to insert data into another table.
You will have to split $sql2 to 2
1st :-
$sql2 = "INSERT INTO accounting (description) SELECT * FROM donations WHERE donorid='$donorid'"
then another one
"UPDATE accounting SET date='', transactiontype='', account ='', Income='', Expense ='' WHERE description=(SELECT * FROM donations WHERE donorid='$donorid')"
that will take all the information from donoation for the given donorid and list it under description in accounting

Unable to update database using php

I have a the following code for inputing data in a database..i specifically echoed the values to see whether they have correct values or not...they have correct values but the values i get in the database are totally different.
Here is my code
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("sm_sample");
$source=$_POST['source'];
$username=$_POST['username'];
$location=$_POST['location'];
$category=$_POST['category'];
$complaint=$_POST['complaint'];
$status=$_POST['status'];
$date=$_POST['date'];
echo $source.$username.$location.$category.$complaint.$status.$date;
$sql="INSERT INTO sample VALUES(ID=NULL,source='$source',username=
'$username', location='$location', category='$category',complaint=
'$complaint',date='$date',status='$status')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
echo "<BR>";
echo "<a href='usercom1.php'>View result</a>";
mysql_close($con)
?>
the values i get in the database r like this:
List data from mysql
Source Username Location Category Complaint Date Status Update
0 Singapore 0 0000-00-00 Pending Edit
The correct syntax:
$sql="INSERT INTO `sample`(`ID`,`source`,`username`, `location`,`category`,`complaint`,`date`,`status`)
VALUES (0, '$source','$username','$location','$category','$complaint','$date','$status')";
later edit ... you are using wrong mysql_query and connection syntax
$con = mysql_connect("localhost","root","") or die('database connection?');
mysql_select_db("sm_sample", $con) or die('wrong database?');
// and for $_POST you sould use mysql_real_escape_string
$source = mysql_real_escape_string($_POST['source']);
// ........................................
$sql="INSERT INTO `sample`(`ID`,`source`,`username`, `location`,`category`,`complaint`,`date`,`status`)
VALUES (0, '$source','$username','$location','$category','$complaint','$date','$status')";
mysql_query($sql) or die('Error: '.mysql_error().': '.mysql_errno());
// ........................................
mysql_close($con);
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
echo ('Could not connect: ' . mysql_error());
}
mysql_select_db("sm_sample",$con);
$source=$_POST['source'];
$username=$_POST['username'];
$location=$_POST['location'];
$category=$_POST['category'];
$complaint=$_POST['complaint'];
$status=$_POST['status'];
$date=$_POST['date'];
echo $source.$username.$location.$category.$complaint.$status.$date;
$sql="INSERT INTO sample ('source','username','location','category','complaint','status') VALUES('$source','$username','location','category','complaint','status' )";
if (!mysql_query($sql))
{
echo ('Error: ' . mysql_error());
}
echo "1 record added";
echo "<BR>";
echo "<a href='usercom1.php'>View result</a>";
mysql_close($con);
?>
First thing you do not have to add id if it is auto increment and date if it uses current timestamp and one more thing that never use die(); , use echo instead.
You should provide only VALUES of data with no column names:
$sql="INSERT INTO sample VALUES(ID, '$source', '$username', '$location', '$category', '$complaint', '$date', '$status')";
Also if you have only one DB connection you can not to define $con variable in mysql_query(). Like this: mysql_query($sql).
The problem is with the following line:
<?php
$sql="INSERT INTO sample VALUES(ID=NULL,source='$source',username='$username', location='$location', category='$category',complaint=
'$complaint',date='$date',status='$status')";
?>
If you check the result in the database, you'll see that the values are getting in the wrong order, use this instead:
<?php
$sql="INSERT INTO sample(ID, source, username, location, category, complaint, date, status) VALUES(NULL, '$source', '$username', '$location', '$category', '$complaint','$date','$status')";
?>
PLEASE read what Albireo posted in his comment. Your code is extremely vulnerable.

PHP/mySQLi not querying

<?php
$ip = $_SERVER['REMOTE_ADDR'];
$date = date("d/m/y : H:i:s", time());
$dbc = mysqli_connect('localhost', 'root', 'derp', 'derpdb')
or die("Database connection fried.");
$query = "INSERT INTO ipstore (tstamp, ip), " .
"VALUES ('$date', '$ip')";
mysqli_query($dbc, $query);
mysqli_close($dbc);
?>
Can anyone tell me what's wrong with this code? It's meant to store the users IP/date they requested the page in the database. I've tried replacing localhost with 127.0.0.1, no luck. It doesn't bring a message, so it must be connected, however when it comes to querying it just doesn't do it. And it doesn't give a warning. I've checked the DB, nothings there.
Also don't worry, nothing sensitive is there ;)
Thanks
$query = "INSERT INTO ipstore (tstamp, ip), " . "VALUES ('$date', '$ip')";
You are not supposed to use a comma after specifying columns - try
$query = "INSERT INTO ipstore (tstamp, ip) VALUES ('$date', '$ip')";
try it this way
$query = mysql_query("INSERT INTO ipstore (tstamp,ip) VALUES ('$date', '$ip')") or die(mysql_error()); if($query) {echo 'Success'; esle { echo 'Failed'; }
And you will get success for sure

Categories