On duplicate gives syntax error and does not work - php

I'm trying to add products to a database from an XML file and when there's a duplicate article number I want to just update the stock level.
I'm still learning PHP and MySQL and I've read numerous post on this forum but I just can't get it to work.
So what I did is this:
$xml = simplexml_load_file("a-link-to-downloaded_products.xml") or die("Error: Cannot create object");
foreach ($xml->children() as $row) {
$article_code = $row->artikelnummer;
$brand = $row->merk;
$name_nl = $row->naam;
$ean = $row->ean;
$stock = $row->voorraad_aanwezig;
$sql = "INSERT INTO `products` (article_code,brand,name_nl,ean,stock) VALUES ('" . $article_code . "','" . $brand . "','" . $name_nl . "','" . $ean . "','" . $stock . "') ON DUPLICATE KEY UPDATE `stock` = VALUES(`$stock`)";
$result = mysqli_query($db, $sql);
..... etc .....
}
Above gives me an error saying
Unknown column '1' in 'field list'
or
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '1)' at line 1
Because of that second error I assume that it has something to do with ON DUPLICATE KEY UPDATE stock = VALUES($stock)" However I tried a lot of different variations but I just can't get it to work! I used backticks, quotes etc. Almost anything I can think of.

Just replace this:
ON DUPLICATE KEY UPDATE `stock` = VALUES(`$stock`)
With:
ON DUPLICATE KEY UPDATE `stock` = VALUES(`stock`)
Explanation: the VALUES() construct in the ON DUPLICATE UPDATE clause is used to reference a column value that is passed in the INSERT clause.
Important note: anyone on SO will tell you that you should really consider using prepared statement and parameterized queries, in order to make your queries safer and more efficient.

Related

ON DUPLICATE KEY UPDATE - Not updating

I am having an issue with my code not updating an existing computers data. If i remove the ON Duplicate section the code works fine and adds the data. i have made computer my unique key in my xampp data base. any help would be greatly appreciated.
<?php
$receive = htmlspecialchars($_POST['time']);
list($length, $status, $computer) = split(":", $receive, 3);
include('connection.php');
mysqli_query($dbc, "INSERT INTO screen(computer,status,length)
VALUES('$computer','$status','$length')
ON DUPLICATE KEY UPDATE
status=$status, length=$length");
?>
A better pattern for creating a SQL statement which mitigates some common SQL Injection vulnerabilities. Also note that the special VALUES() function can be used to reference the values that would have been inserted for a column, if the insert had succeeded.
$sql = "INSERT INTO screen(computer,status,length)
VALUES('"
. mysqli_real_escape_string($dbc,$computer)
. "','"
. mysqli_real_escape_string($dbc,$status)
. "','"
. mysqli_real_escape_string($dbc,$length)
. "')
ON DUPLICATE KEY UPDATE
status=VALUES(status), length=VALUES(length)";
mysqli_query($dbc,$sql);

MySQL throws error but works - PhpMyAdmin without error

I am running this query on my MySQL Database - with mysql_query it throws me an error but the data is still properly inserted into the table. If I enter it in PhpMyAdmin it works without error.
INSERT INTO `kommentare` VALUES(NULL,'1','MyName','MyEmail','MyText','2014-08-05');
PHP :
$name = mysql_escape_string($name);
$email = mysql_escape_string($email);
$kommentar = mysql_escape_string($kommentar);
$datum = mysql_escape_string($datum);
$reiseid = str_replace("/", "", $reiseid);
$query = "INSERT INTO kommentare VALUES(NULL,'" . $reiseid . "','" . $name . "','" . $email . "','" . $kommentar . "','" . $datum . "');";
$result = mysql_query($query) or die(mysql_error());
echo $query;
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
How is that possible? I am experienced with MySQL but this wrecks my nerves - it works but says it doesn't?!
UPDATE:
It just happens when I have more than one entry in the table. ANd even if I remove all the ' it gives me the same error, saying I should check near the '
If the first column is a auto-increment primary key, you don't pass it NULL, you pass it DEFAULT:
INSERT INTO kommentare VALUES
(DEFAULT,'$reiseid','$name','$email','$kommentar','$datum');
But really you should instead be naming your columns and skipping those that you don't have a value for:
INSERT INTO kommentare
(reiseid, name, email, kommentar, datum)
VALUES
('$reiseid','$name','$email','$kommentar','$datum');
SOLUTION:
My id has been passed not as 1 but as 1/ for some reason. This caused MySQL to crash although it was not shown to me. I replace the / with "" now and everything works fine!

wrong query inserting value in specific row

I'm trying to execute the following query where I want to add a value in the column firstime in the corresponding row with $netid and mac.
$query="INSERT INTO node WHERE netid='".$netid."' AND mac='" . $_GET['mac'] . "' (firstime) VALUES ('" . $firstcheck . "')";
mysql_query($query, $conn) or die("Error executing query: ".mysql_error($conn));
when I try I get the following error message:
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 'WHERE netid='28' AND mac='24:A4:3C:40:4D:EB' (firstime) VALUES ('2014-01-16 12:0' at line 1
Any Idea??
You cannot use WHERE clause for INSERT query since it makes no sense
Here is a documentation page about its proper syntax: http://dev.mysql.com/doc/refman/5.6/en/insert.html
A scientific guess: what you need is UPDATE
Perhaps you want an update:
update node
set firsttime = '" . $firstcheck . "'
WHERE netid = '".$netid."' AND mac = '" . $_GET['mac'] . "';
insert inserts a new row into the table, not a new value into the row.
update updates a value in a row.
The WHERE conditions must go at after the colums and values declaration.
INSERT INTO node (firstime) VALUES ('" . $firstcheck . "') WHERE netid='".$netid."'
AND mac='" . $_GET['mac'] . "'";
Also use prepared statements and sanitize user submitted data, in order to prevent a SQL INJECTION which is a present and clear threaten.

MySQL syntax error

IM GETTING THIS 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 'release (project_id, start_date, end_date, predicted_velocity,
release_title, )' at line 1
MY PHP FILE:
<?php
include("../db_connect/connect.php");
$project_id = $_POST['project_id'];
$release_title = $_POST['release_id'];
$start_date = $_POST['start_date'];
$end_date = $_POST['end_date'];
$predicted_velocity = $_POST['predicted_velocity'];
$query = "INSERT INTO release (project_id, start_date, end_date, predicted_velocity, release_title, ) VALUES ('" . $predicted_velocity . "','" . $release_title . "','" . $start_date . "','" . $end_date . "','" . $project_id . "', NOW())";
mysql_query($query) or die(mysql_error());
header("location: ../view-project.php?project_id=$project_id");
?>
ANY IDEAS WHY? IM NEW TO THIS!
You have a missing column name, resulting in an orphaned comma.
, )
should be
, MyColumn)
I assume MyColumn is meant to be populated by the NOW() function.
Also, your values are not listed in the same order as the columns, which will cause the query to fail.
To summarize the issues here:
Missing column name (column count must match value count)
Hanging comma
Column order does not match variable order
Code is subject to SQL injection attack
No server-side validation is being done on user input
Extra comma:
[..snip..] predicted_velocity, release_title, ) VALUES
^--- here
You have a stray comma after release_title.
#john_allen You said you got the error message "right syntax to use near 'release (project_id," - that is interesting, because MySQL always starts the example where the syntax error occurs.
If the error was just the incorrect comma after release_title, then the error from MySQL would have been "the right syntax to use near ') VALUES...". That is an error, but not the one that the MySQL parser is hitting first.
There's something else wrong here, and I think it is because you don't have a table called 'release', or at least MySQL can't find your table called 'release' using the credentials you've given it. Check your connection string.

MySQL - Delete a row, how?

Can anyone show me a query in MySQL that would delete rows from all available columns.
I use this to insert rows:
$sql = "INSERT INTO " . KEYS . " // KEYS is a constant
(key, user_id, time, approved)
VALUES ('" . $randkey . "', '" . $user_id . "', '" . $time . "', '0')";
I need the opposite of this now, delete created rows.
delete from <table> where ....
Keep in mind that the delete statement is always for an entire row.
Using similar syntax sql = "DELETE FROM " . KEYS . " WHERE 1=1";
Replace 1=1 with the conditions for the row you want to delete or it will delete all rows.
Also, it's good to get out of the habit of just dropping variables into SQL as soon as possible, because it will open your code up to SQL Injection attacks. Look into using parameterized queries.

Categories