ON DUPLICATE KEY UPDATE - Not updating - php

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);

Related

On duplicate gives syntax error and does not work

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.

insert and update in different database in one php

how can i update and insert together
require_once ('database.php');
$name = mysql_real_escape_string ($_REQUEST["name"]);
$course = mysql_real_escape_string ($_REQUEST["course"]);
$email = mysql_real_escape_string ($_REQUEST["email"]);
$contact = mysql_real_escape_string ($_REQUEST["contact"]);
$Date = mysql_real_escape_string ($_REQUEST["Date"]);
$sql = "SELECT * FROM registerlist WHERE name = '" . $name . "'";
$result = mysql_query ($sql, $dbconn);
if (mysql_num_rows ($result) > 0) {
$resultStr = header("Location:blog.php");
} else {
$result = "SELECT * FROM courselist WHERE cname = '" . $course
. "'";
$row=mysql_fetch_row($result);
$sql = "INSERT INTO registerlist (name, Course, Email, Contact,
Date) VALUES ('" . $name . "', '" . $course . "', '" . $email . "', '" .
$contact . "','" . $date . "')";
$result1= mysql_query($sql, $dbconn);
$result =mysql_query("UPDATE courselist SET $Row['slot'] =
'$Row['slot'] - 1 '");
if ($result1) {
$resultStr = header("Location:blog.php");
}
}
echo json_encode($resultStr);
if the person register the course, the course slot will subract by 1 and student document will be insert into registerlist database.
I hope I did understand correctly: You want to update the courselist table at the same time a record was insert into the registerlist table? This can be done using triggers (https://dev.mysql.com/doc/refman/8.0/en/trigger-syntax.html , IF both databases run at the same SQL server) and/or table locks (https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html):
Without trigger
Lock table courselist
Insert the record to registerlist
Update table courselist
Release table courselist
With trigger
You need a trigger that locks the table courselist before writing to the registerlist table, and a trigger that updates courselist and releases the lock after writing to registerlist.
In this case you only insert the record into registerlist from your PHP code, and the table locking and courselist update is being done by the triggers within the SQL server.
In any case you can't write to both tables at the same time, there is no SQL statement to do that. But with locks you can simulate such a behavior.
When defining the target table of a SQL statement, you may prepend the tables database name like databaseName.tableName, if the Connection uses a different database per Default.
But aynber from the comments is absolutely right - you should move away from mysql_* asap!
Edit: This SQL example should show how table locking is working (all information about that can be found in the MySQL documentation from the link above):
LOCK TABLES courselist WRITE;
INSERT INTO registerlist …;
UPDATE courselist …;
UNLOCK TABLES;
You'll Need a WRITE lock, since you're going to write to the table. Other reading, writing or locking statements from other sessions are blocked until you release the lock.
A READ lock would prevent the table from being modified by any session. Writing (and write locking) attempts are blocked until you release the lock and all other READ locks from other sessions are released, too.

Trouble specifying my tablename inside query because of dot notation

I'm having trouble specifying my tablename inside the following query.
$sql = "INSERT INTO db269193_crud.posts (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
The tablename is: db269193_crud.posts. I can't specify the table name as 'posts' because of my hostingprovider. They only allow me to specify it in conjunction with my databasename (which is db269193).
So the table name becomes: db269193(dot)posts. This dot however keeps lighting up in my editor as an incorrect syntax.
I need someone's help to tell me if I specified the table name correctly or if I have to use a variable to hide the dot notation like:
$tablename = 'db269193.crud';
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
You can put the entire name in backticks to escape it:
INSERT INTO `db269193_crud.posts` (post_title, description)
VALUES ('" . $title . "', '" . $description . "')
As for the rest of your statement, I would encourage you to use parameters instead of munging the query string. By putting random strings in the query, you are just inviting syntax errors and SQL injection attacks.
I can't specify the table name as 'posts' because of my hostingprovider. They only allow me to specify it in conjunction with my databasename (which is db269193).
I pretty much doubt that as it would require DB changes which simply make no sense. I assume that it's your fault as you did not select DB to use in the first place. Check how you connect and ensure you provide DB name as well or at least you mysqli_select_db() or equivalent.
$tablename = 'db269193.crud';
You can use backticks when name of table or column conflicts or is reserved word:
$tablename = '`db269193.crud`';
or
$tablename = '`db269193`.`crud`';
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
You are complicating simple strings with unnecessary concatentation. This will work and is less error prone:
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('{$title}','{$description}')";
however you are still seem to be vulnerable to sql injection here. I'd recommend switching to PDO.

data from a json object not inserting into mysql in php foreach loop

I am trying to insert the results from a json array into MySQL using
foreach ($feed->items as $item) {
$query = "insert into data(id,url,keyword)values ($item->id, $item->url,$item->kind)";
$result = mysql_query($query);
echo $result;
}
I have confirmed the database details are OK and the $items are correct.
Can anyone point me in the right direction? I am fairly new to PHP so any help is appreciated.
You need to escape the values in the SQL:
$query = "insert into data(id,url,keyword)values ('" . mysql_real_escape_string($item->id) . "', '" . mysql_real_escape_string($item->url) . "' , '". mysql_real_escape_string($item->kind) . "')";
this adds quotation marks ' around the variables so that the SQL can be parsed at all
This prevents SQL injection.
You need to wrap your variabels in your query :
$query = "insert into data(id,url,keyword)values ('{$item->id}', '{$item->url}', '{$item->kind}')";

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