I am trying a new way of inserting data into a SQL. I am getting this error
insert into tracking_clients set / agreement_type = 'Purchase' , existing_client = 'Yes' ,
sales_rep = '1'
Array ( [agreement_type] => Purchase [existing_client] => Yes [sales_rep] => 1
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 '/ agreement_type = 'Purchase' ,
existing_client = 'Yes' , sales_rep = ' at line 2mysql err no : 1064
I use a form with action POST
In my submit page I use the following
//Drawn from Form Information used to Update Database
$sub1 = $_REQUEST['agreement_type'];
$sub2 = $_REQUEST['existing_client'];
$sub3 = $_REQUEST['sales_rep'];
update_lbs($sub1, $sub2, $sub3, $sub4,....); //Not full string posted here
function update_lbs($sub1, $sub2, $sub3, $sub4,.....)
{
global $host;
global $username;
global $password;
global $db_name;
//Insert if dates is required
date_default_timezone_set('Africa/Johannesburg'); //Global Time one for South Africa
$today = date("Y-m-d H:i:s");
$date = date("Y-m-d") ;
$time = date("H:i:s");
$insertSuccessful = false;
$new_msisdn = '0' . substr($msisdn, 2); //Not Sure If this is required in normal SET command
if ($con = mysql_connect($host, $username, $password)) {
if (mysql_select_db($db_name))
//First Database Insert change table name as required
$sql = "insert into tracking_clients set
agreement_type = '".$sub1."' ,
existing_client = '".$sub2."' ,
sales_rep = '".$sub3."',
sub_date = '".$date."'" //Last of the code for SET
;
if (mysql_query($sql, $con)) {
$insertSuccessful = true;
} else {
echo $sql;
print_r($_POST);
echo "\n" . mysql_error($con);
echo "mysql err no : " . mysql_errno($con);
}
I am not sure what would be causing this error at all. I know this question is a common one but reading thru the other awnsers I am not getting the error
you have a tab characters beetween "set" and "agreement_type"
I am assuming you are using mysql here. The insert statement doesn't use set it simply inserts the values.
Something like this:
insert into yourTable (val1, val2, val3)
or
insert into yourTable (col1, col2, col3) values (val1, val2, val3)
not
insert into yourTable set col1=val1 etc...
Related
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;
}
I've been trying to get this INSERT to work correctly, so I worked through the undefined variable and index problems and now I think I am nearly there.
Below is the code:
<?php
session_start();
require "../dbconn.php";
$username = $_SESSION['username'];
$query1 = "SELECT user_table.user_id FROM user_table WHERE user_table.username ='".$username."'";
$query2 = "SELECT department.department_id FROM department, user_table, inventory
WHERE user_table.user_id = department.user_id
AND department.department_id = inventory.department_id";
//Copy the variables that the form placed in the URL
//into these three variables
$item_id = NULL;
$category = $_GET['category'];
$item_name = $_GET['item_name'];
$item_description = $_GET['item_description'];
$item_quantity = $_GET['quantity'];
$item_quality = $_GET['quality'];
$item_status = NULL;
$order_date = $_GET['order_date'];
$invoice_attachment = NULL;
$edit_url = 'Edit';
$ordered_by = $username;
$user_id = mysql_query($query1) or die(mysql_error());
$department_id = mysql_query($query2) or die(mysql_error());
$price = $_GET['price'];
$vat = $_GET['vat%'];
$vat_amount = $_GET['vat_amount'];
$create_date = date("D M d, Y G:i");
$change_date = NULL;
//set up the query using the values that were passed via the URL from the form
$query2 = mysql_query("INSERT INTO inventory (item_id, category, item_name, item_description, item_quantity, item_quality, item_status, order_date,
invoice_attachment, edit_url, ordered_by, user_id, department_id, price, vat, vat_amount, create_date, change_date VALUES(
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$item_quantity."',
'".$item_quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$user_id."',
'".$department_id."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')")
or die("Error: ".mysql_error());
header( 'Location:../myorders.php');
?>
Error:
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 'VALUES( '', 'adasd', 'dsadsa', 'dsad', 'sadsad', '' at line 2
Could anyone please let me know where I am going wrong? :(
Been staring at this for 3-5 hours already :(
You are not actually trying to insert any data into your table. You only craft and assign the query in string form to a variable. You need to use the function mysql_query to actually run the code.
As pointed out you will also have to specify the columns you are inserting data into in the MySQL query if you don't supply data for every column (in the correct order). Here you can look at the MySQL insert syntax.
I would also urge you to look into using the MySQLi or the MySQL PDO extensions for communicating with your MySQL database since the MySQL extension is deprecated. Look here for additional information and comparisons.
Here, you only assign the values to the $query var:
$query = "INSERT INTO inventory VALUES (
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$quantity."',
'".$quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')"
or die("Error: ".mysql_error());
You do not actually run the query.
try:
$query = mysql_query("INSERT INTO inventory (column_name1, column_name 2, column_name3 ... the column name for each field you insert) VALUES (
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$quantity."',
'".$quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')")
or die("Error: ".mysql_error());
Also, you should use mysqli_* or any other PDO as the mysql_* functions are deprecated
If you are not inserting in all columns you need to specify the columns you are going to insert. Like this:
INSERT INTO Table(Column1, Column6) VALUES (Value1, Value6)
You are missing the column names in your INSERT
I have been beating my head against a wall for a few hours now trying to get this to update my DB.
<?
//edit_item_data.php
$con=mysqli_connect("localhost","root","","Inventory");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql= "UPDATE Item
SET Catagory = '$_POST[Catagory]',
Cost = '$_POST[Cost]',
Condition = '$_POST[Condition]',
PurchaseLot_PurchaseLotID = '$_POST[PurchaseLot]',
Location = '$_POST[Location]',
Desc = '$_POST[Desc]',
Notes = '$_POST[Notes]'
WHERE
ItemID = '$_POST[id]'";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
<script type='text/javascript'>
settimeout('self.close()',5000);
</script>
this is the error I'm getting
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 'Condition = New,
PurchaseLot_PurchaseLotID = 1, Location = e' at line 4
I'm running mysql 5.6 and php 5.5. I'm sure its something dumb but I can't for the life of me see what it is.
Well you are hilariously vulnerable to SQL injection doing what you are doing, but the problem is that you aren't enclosing your variables in quotes, e.g:
SET Catagory = '$_POST[Catagory]',
-- etc
Use mysqli_real_escape_string to escape your variables before you put them into your SQL, like this:
SET Catagory = '" . mysqli_real_escape_string($_POST['Catagory'], $con) . "',
You want something like this:
$sql = "UPDATE `Item` SET
`Catagory` = '".mysqli_real_escape_string($_POST['Catagory'],$con)."',
`Cost` = '".mysqli_real_escape_string($_POST['Cost'],$con)."',
........
WHERE `ItemID` = ".intval($_POST['id']);
Side-note, it's spelled "category".
EDIT: If you, like me, can't be arsed to type out such a long function name...
$e = function($str) use ($con) {
return mysqli_real_escape_string($str,$con);
};
Then:
... `Catagory` = '".$e($_POST['Catagory'])."' ...
The real issue was lack of grave accents
SET `Catagory` = '$_POST[Catagory]',
I get the error: Column 'Time' cannot be null when using the query below, it works fine the first time when there is no duplicate but then when trying to update again I get the error: Column 'Time' cannot be null
mysql_query("
INSERT INTO
$table(Username, Time, Videos, Credits)
VALUES
('$user', '$time', '$videos', '$credits')
ON DUPLICATE KEY UPDATE
Time=Time+INTERVAL $time SECOND
Videos=Videos+'$videos',
Credits=Credits+'$credits'
",
$conn
);
Hope you can spot my error as I am new to this, thanks!
Here is some more of my code:
$conn = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
mysql_select_db(DB_NAME, $conn);
// Error checking
if(!$conn) {
die('Could not connect ' . mysql_error());
}
// Localize the GET variables
$user = isset($_GET['username']) ? $_GET['username'] : "";
$time = isset($_GET['time']) ? $_GET['time'] : "";
$videos = isset($_GET['videos']) ? $_GET['videos'] : "";
$credits = isset($_GET['credits']) ? $_GET['credits'] : "";
// Protect against sql injections
$user = mysql_real_escape_string($user);
$time = mysql_real_escape_string($time);
$videos = mysql_real_escape_string($videos);
$credits = mysql_real_escape_string($credits);
$secret = mysql_real_escape_string($secret);
// Insert
$retval = mysql_query("
INSERT INTO
$table(Username, Time, Videos, Credits)
VALUES
('$user', '$time', '$videos', '$credits')
ON DUPLICATE KEY UPDATE
Time = DATE_ADD(IFNULL(Time,now()),INTERVAL '$time' SECOND),
Videos = Videos+'$videos',
Credits = Credits+'$credits'
",
$conn
);
// End Query
if($retval) {
echo "Success! Updated $user with Time: $time - Videos: $videos - Credits: $credits";
} else {
echo "<b>ERROR:</b><br>" . mysql_error();
}
mysql_close($conn);
It should be:
mysql_query("
INSERT INTO
$table(Username, `Time`, Videos, Credits)
VALUES
('$user', '$time', '$videos', '$credits')
ON DUPLICATE KEY UPDATE
Time = DATE_ADD(IFNULL(`Time`,now()),INTERVAL '$time' SECOND)
,Videos = Videos+'$videos'
,Credits = Credits+'$credits'
",
$conn
);
Don't forget to put single quotes around all injected variables, otherwise mysql_real_escape_string will not protect you.
See:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add
If there's no duplicate, then this query will do an insert, and the Time value will be null, as no value was ever set. Null + anything is null, hence the error.
Try ... Time = COALESCE(Time, 0) + INTERVAL $time SECOND or similar to get aroun dit.
This is the error i'm receiving 1064 - 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 ':i:s a), rec_type = '', rec_request = '1', rec_by = 'Victoria', batch_id = UC' at line 1
also i'm aware that I need to escape before inserting. I'm just testing right now.
$importwav="INSERT into names SET
com_id = '".$word_id."',
rec_date = date(d-M-y),
rec_time = date(h:i:s a),
rec_type = '".$rec_type."',
rec_request = '1',
rec_by = '".$data[8]."',
batch_id = UCASE('".$batchid."')
";
INSERT into names SET com_id = '87', rec_date = date(d-M-y),
rec_time = date(h:i:s a), rec_type = '', rec_request = '1',
rec_by = 'Victoria', batch_id = UCASE('Batch004AM')
You're confusing your PHP functions and your MySQL functions.
$importwav="INSERT into names SET
com_id = '".$word_id."',
rec_date = '" . date('d-M-y') . "',
rec_time = '" . date('h:i:s a') . "',
...
And your SQL syntax is FUBAR.
Improper SQL syntax.
INSERT INTO table (col1, col2) VALUES (val1, val2)
date() arguments need to be a string. Try surrounding your date format strings with single quotes (').