Receiving syntax error with INSERT DATEDIFF - php

I am receiving this error, and not being to insert DATEDIFF into the database. I can't seem to find the problem. I tried checking the syntax. Can anyone help please?
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$pdate = mysqli_real_escape_string($con, $_POST['pdate']);
$mdate = mysqli_real_escape_string($con, $_POST['mdate']);
$amt = mysqli_real_escape_string($con, $_POST['amt']);
$first = mysqli_real_escape_string($con, $_POST['first']);
$last = mysqli_real_escape_string($con, $_POST['last']);
$pid = mysqli_real_escape_string($con, $_POST['pid']);
$cno = mysqli_real_escape_string($con, $_POST['cno']);
$madd = mysqli_real_escape_string($con, $_POST['madd']);
$bene = mysqli_real_escape_string($con, $_POST['bene']);
$swc = mysqli_real_escape_string($con, $_POST['swc']);
$bacc = mysqli_real_escape_string($con, $_POST['bacc']);
$bank = mysqli_real_escape_string($con, $_POST['bank']);
$badd = mysqli_real_escape_string($con, $_POST['badd']);
$bno = mysqli_real_escape_string($con, $_POST['bno']);
$sql="INSERT INTO contacts (
nodays, interest, pdate, mdate, amt, first, last,
pid, cno, madd, bene, swc, bacc, bank, badd, bno
)
VALUES (
DATEDIFF($mdate,$pdate) AS nodays,
(DATEDIFF($mdate,$pdate) * $amt / 365 * 0.1) AS interest,
'$pdate','$mdate','$amt','$first','$last',
'$pid','$cno','$madd','$bene','$swc','$bacc','$bank','$badd','$bno'
)";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "Client record has been added to the database!";
mysqli_close($con);

The problem is that you try to execute 2 queries at the same time - only delimited by comma. That does not work. Seperagte them and execute them one by one.

You are inserting 2 more columns into contacts:
You say INSERT INTO CONTACTS with all the columns, but then you use
SELECT *, DATEDIFF... FROM CONTACTS. So you try to insert more columns into the same table.

I assume you are trying to calculate the nodays and interest as you do the insert, this should work:
INSERT INTO contacts (
nodays, interest, pdate, mdate, amt, first, last,
pid, cno, madd, bene, swc, bacc, bank, badd, bno
)
VALUES (
DATEDIFF($mdate,$pdate),
(DATEDIFF($mdate,$pdate) * $amt / 365 * 0.1),
'$pdate','$mdate','$amt','$first','$last',
'$pid','$cno','$madd','$bene','$swc','$bacc','$bank','$badd','$bno'
);

Related

Change an Insert statement to an update statement in PHP/MySQL

I'm making an Android app that connects to a database online and lets the user edit the database from the application, I'm new to PHP and MySql but from my research I think I should be using an UPDATE statement, I've written the code below to register new users on the site from a tutorial, but I'd like to change the INSERT statement to an UPDATE statement so that instead of registering a new user, the App updates existing data that I have entered in PHPMYADMIN, could someone show me how to do this? Also, if you require the code for the app mention it in the comments and I'll add it to the question, I don't want to post too much unneccessary code. Thanks in advance.
<?php
require "conn.php";
$patient_name = $_POST["patient_name"];
$check_in_date = $_POST["check_in_date"];
$room_number = $_POST["room_number"];
$bed_number = $_POST["bed_number"];
$notes = $_POST["notes"];
$mysql_qry = "insert into patients(patient_name, check_in_date, room_number, bed_number, notes) values ('$patient_name', '$check_in_date', '$room_number', '$bed_number', '$notes')";
if($conn->query($mysql_qry) === TRUE) {
echo "Insert successful";
}
else{
echo "Error: " . $mysql_qry . "<br>" . $conn->error;
}
$conn->close();
?>
EDIT
The fixed code is below, it now updates records already in the database rather than adding new data.
<?php
require "conn.php";
$patient_name = $_POST["patient_name"];
$check_in_date = $_POST["check_in_date"];
$room_number = $_POST["room_number"];
$bed_number = $_POST["bed_number"];
$notes = $_POST["notes"];
$mysql_qry = "UPDATE patients SET notes='$notes' WHERE patient_name='$patient_name'";
if($conn->query($mysql_qry) === TRUE) {
echo "Insert successful";
}
else{
echo "Error: " . $mysql_qry . "<br>" . $conn->error;
}
$conn->close();
?>
first of all this PHP code is vulnerable to sql injection you should, no need to update your code to use either mysqli prepared statement or PDO prepared statement
secondly the easiest way I know you accomplish your goal would make a unique constraint on some columns and then use a mysql feature ON DUPLICATE UPDATE
for this example I'll assume that the unique fields determining an update instead of an insert are patient_name, check_in_date, room_number, and bed_number (in case john smith was in the same room as john smith in seprate beds) the query to update the table would be like this
ALTER TABLE `patients` ADD UNIQUE `unique_index`(`patient_name`, `check_in_date`, `room_number`, `bed_number`);
so now to address the sql injection bit and the query, I'll update the example to use mysqli statement and will assume patient_name and notes are strings (varchar/nvarchar), room_number and bed_number are integers, and check_in_date is a date
Edit My original answer had a syntax error in the query and also passing variables to the prepared statement below is the updated answer
$mysqliConn = new mysqli("localhost", "my_user", "my_password", "mydatabase");
$stmt = $mysqliConn->prepare("insert into patients
(patient_name, check_in_date, room_number, bed_number, notes)
values (?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE notes=values(notes)");
$patient_name = $_POST["patient_name"];
$check_in_date = $_POST["check_in_date"];
$room_number = $_POST["room_number"];
$bed_number = $_POST["bed_number"];
$notes = $_POST["notes"];
mysqli_stmt_bind_param($stmt, "sdiis",
$patient_name, $check_in_date, $room_number, $bed_number, $notes);
hope this helps
Edit
Regarding the unique key, a unique key means that all fields in the unique key have to be unique when combined so for the example above
if record 1 is
patient_name, check_in_date, room_number, bed_number, notes
'john smith', '3/1/2017' , 413 , 2 , 'patient is sick'
and record two is
'jane doe' , '3/1/2017' , 413 , 2 , 'patient has wound'
these two records will note be duplicates with the above constraint but if you do need to change the constraint you can do the following
DROP the Constraint
ALTER TABLE `patients` DROP INDEX `unique_index`;
Then recreate the constraint like this
ALTER TABLE `patients` ADD UNIQUE `unique_index`(`patient_name`, `check_in_date`, `room_number`);
also if you named your constraint something other than unique_index you can find the key_name by running the following
SHOW INDEX FROM `patients`;
the name will be in the key_name column
additionally you may want to alter the last line of the query to be this in your php if you change the unique constraint so you can change bed number
ON DUPLICATE KEY UPDATE bed_number=values(bed_number), notes=values(notes)
You can also use REPLACE INTO, then you don't have to change the SQL statement. Let MySQL do the work for you.
https://dev.mysql.com/doc/refman/5.7/en/replace.html
<?php
require "conn.php";
$patient_name = $_POST["patient_name"];
$check_in_date = $_POST["check_in_date"];
$room_number = $_POST["room_number"];
$bed_number = $_POST["bed_number"];
$notes = $_POST["notes"];
$mysql_qry = "REPLACE INTO patients(patient_name, check_in_date, room_number, bed_number, notes) VALUES ('$patient_name', '$check_in_date', '$room_number', '$bed_number', '$notes')";
if($conn->query($mysql_qry) === TRUE) {
echo "Insert successful";
}
else{
echo "Error: " . $mysql_qry . "<br>" . $conn->error;
}
$conn->close();
Also, you should really take a look at using PDO with prepared statements and parameters.
https://secure.php.net/manual/en/pdo.prepare.php
Actually I was looking for a small function that converts an INSERT MySQL query to an UPDATE query. So maybe other people were looking for the same and I think this is what the original poster was looking for aswell... I couldnt find any so I made this simple function which works for my needs, ofcourse you will have to make sure your original query is safe from MySQL injection.
It will convert
INSERT INTO aaa (bbb, ccc) VALUES ('111', '222')
to
UPDATE aaa SET ccc='222' WHERE bbb='111'
Use the 2nd variable ($iColumn) to identify the WHERE statement.
function convertInsertToUpdate($sQuery, $iColumn = 1) {
$sNewQuery = "";
$iPos = strpos($sQuery, ' (');
$sTmpTable = substr($sQuery, 0, $iPos);
$iPos = strpos($sTmpTable, 'INSERT INTO ');
$sTmpTable = substr($sTmpTable, $iPos+12);
$iPos = strpos($sQuery, ') VALUES (');
$sTmpValues = substr($sQuery, $iPos+10);
$iPos = strrpos($sTmpValues, ')');
$sTmpValues = substr($sTmpValues, 0, $iPos);
$iPos = strpos($sQuery, '(');
$sTmpColumns = substr($sQuery, $iPos+1);
$iPos = strpos($sTmpColumns, ') VALUES (');
$sTmpColumns = substr($sTmpColumns, 0, $iPos);
$aColumns = explode(', ', $sTmpColumns);
$aValues = explode(', ', $sTmpValues);
if (count($aColumns)>0 && count($aColumns) == count($aValues) && $iColumn < (count($aValues)+1)) {
$sNewQuery = "UPDATE ".$sTmpTable." SET";
$sTmpWhere = "";
$bNotFirst = false;
$iX = 0;
while ($iX<count($aColumns)) {
if ($iColumn == ($iX+1)) {
$sTmpWhere = " WHERE ". $aColumns[$iX]."=".$aValues[$iX];
$iX++;
continue;
}
if ($bNotFirst) {
$sNewQuery .= ",";
}
$sNewQuery .= " ".$aColumns[$iX]."=".$aValues[$iX];
$bNotFirst = true;
$iX++;
}
$sNewQuery .= $sTmpWhere;
}
return $sNewQuery;
}

How to insert record which has foregin key referenced to primary key of another table in PHP Script?

Here is my code-
<?php
session_start();
$con = mysqli_connect("localhost", "root", "", "placement")
or die("Failed to connect MySQL: " . mysqli_error()); // Connecting to MySQL Database
// Variable Declaration
$StateName = mysqli_real_escape_string($con, $_POST["txtStateName"]);
$Description = mysqli_real_escape_string($con, $_POST["txtDescription"]);
$CountryName = mysqli_real_escape_string($con, $_POST["selectCountryName"]);
$CountryId = "SELECT CountryId FROM tbl_country_master WHERE CountryName='$CountryName'";
// Insert Query
$sql = "INSERT INTO tbl_state_master(StateName, Description, CountryId) VALUES ('$StateName', '$Description', '$CountryId')";
if(!mysqli_query($con, $sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
header("Location: frmAddState.php?msg=1");
}
mysqli_close($con);?>
CountryId in tbl_state_master is a foreign key and it is referenced to primary key of tbl_country_master. I'm not able to insert data as I'm getting error.
You never executed the query that's supposed to return the country ID. You just set $CountryId to the SQL string. It should be:
$sql = "SELECT CountryId FROM tbl_country_master WHERE CountryName='$CountryName'";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
if ($row) {
$CountryId = $row['CountryId'];
}
But ou don't need two separate queries, do it in just one:
$sql = "INSERT INTO tbl_state_master(StateName, Description, CountryId)
SELECT '$StateName', '$Description', CountryId
FROM tbl_country_master WHERE CountryName='$CountryName'";

how to save number as 0001 or 0006 in php, mysql database?

i am fetching database value of a column as 0005 , then i am adding 1 to it and save it in the database with a char ABHI but in the database its saved as ABHI6 not ABHI0006. how to do it??
here is the php script
$name = mysqli_real_escape_string($conn, $_POST['name']);
$id = mysqli_real_escape_string($conn, $_POST['id_last']);
$id2=+$id;
$sql="INSERT INTO file (name, unique_id )
VALUES ('$name','$name$id2')";
Use padding for the string
$name = mysqli_real_escape_string($conn, $_POST['name']);
$id = mysqli_real_escape_string($conn, $_POST['id_last']);
$id2 = "$name".str_pad(++$id, 4, "0", STR_PAD_LEFT);
$sql="INSERT INTO file (name, unique_id )
VALUES ('$name','$id2')";
See refrence here
Try with this
$id = "ABHI1";
$IncrementID = substr($id, -1) +1;
echo substr_replace($id,$IncrementID,-1);
Out put
ABHI2

Multiple insert issue

When I use this code, I get one record for each id stored in the users table. Instead, I want to be able to insert only 1 record each time, the one that matches the logged users id.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$acname = mysqli_real_escape_string($con, $_POST['ACName']);
$btu = mysqli_real_escape_string($con, $_POST['BTU']);
$space = mysqli_real_escape_string($con, $_POST['Space']);
$energyclass = mysqli_real_escape_string($con, $_POST['EnergyClass']);
$sql="INSERT INTO aircondition (id, ACName, BTU, Space, EnergyClass)
SELECT id, '$acname', '$btu', '$space', '$energyclass'
FROM users";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
header('location:aircondition.php');
mysqli_close($con);
?>
You must have a where clause in your select statement
$sql="INSERT INTO aircondition (id, ACName, BTU, Space, EnergyClass)
SELECT id, '$acname', '$btu', '$space', '$energyclass'
FROM users WHERE usernamecolumn= currentusername ;

Can't insert with sql the date which i picked from calendar

I am trying to do a project from university and I can't figure out how to insert the date which I pick from calendar function. I have tried a couple of things, but I get 0000-00-00 or the current date: 2014-06-08.
<?php
$con=mysqli_connect("","","","");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$checkin = mysqli_real_escape_string($con, $_POST['checkin']);
$checkout = mysqli_real_escape_string($con, $_POST['checkout']);
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
$title = mysqli_real_escape_string($con, $_POST['title']);
$roomtype = mysqli_real_escape_string($con, $_POST['roomtype']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$phone = mysqli_real_escape_string($con, $_POST['phone']);
$checkout = date("Y-m-d");
$sql="INSERT INTO reservation (checkin, checkout, firstname, lastname, title, roomtype, email, phone)
VALUES ('$checkin', '$checkout', '$firstname','$lastname', '$title', '$roomtype', '$email', '$phone')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "Your booking has been completed";
mysqli_close($con);
header("Location: ");
exit;
?>
$checkout = date("Y-m-d");
The function give you the current date in the format "Y-m-d" That is the first reason why you get the current date and because you save the current date after you did : $checkout = mysqli_real_escape_string($con, $_POST['checkout']); you override the date you get with $_POST['checkout']
You should do this:
$checkout = mysqli_real_escape_string($con, $_POST['checkout']);
$checkout = date_format(date_create($checkout), 'Y-m-d');
The problem is probably with your html form. HTML5 allows for an easy date picker:
<input type="date" name="checkin">
<input type="date" name="checkout">
You dont need value="DD/MM/YY" and onfocus and those other arguments. If a date input is left empty it will return nothing. The input also outputs the date as a unix timestamp I believe

Categories