Update row if exists [duplicate] - php

This question already has answers here:
Insert into a MySQL table or update if exists
(12 answers)
Closed 6 years ago.
In my PHP script I save data to database (hash, sala).
I want to update hash if sala is exists (update hash in same row).
How to change in my script?
$sala = $_POST['sala'];
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else{
echo "Polaczono";
}
$sql = "INSERT INTO instructions (hash, sala)
VALUES ('$newfilename', '$sala')";
if ($conn->query($sql) === TRUE) {
echo "Dane dodano prawidłowo";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();

You can use INSERT ... ON DUPLICATE KEY syntax to update the value if key already exists, e.g.:
INSERT INTO instructions (hash, sala) VALUES("A", "B") ON DUPLICATE KEY UPDATE
hash = "C";
Here is the documentation.

Use this query instead:
$sql = "INSERT INTO instructions (hash, sala)
VALUES ('$newfilename', '$sala')
ON DUPLICATE KEY UPDATE hash='$newfilename'";
Also you need to create UNIQUE KEY on column sala.
And don't forget about SQL injection attack as you been told before.

Related

(MYSQL) How to insert a record only if it doesn't exist in a table

Hi maybe this question has already been answered but nothing has been helpful.
I'm using Mysql and I want to insert some data in a table but i want to check for duplicated records before inserting .
I'm very confused about how to achieve this.
I need to check if "RFC==$Expediente AND Diagonal ==10 or Diagonal==20" and show something like "Record already Exist",
or insert all the data if record doesn't exist
this is my script :
<?php
$Person_name=$_POST['Person_name'];
$Expediente=$_POST['Expediente'];
$Sexo=$_POST['Sexo'];
$Edad=$_POST['Edad'];
$Domicilio=$_POST['Domicilio'];
$numero=$_POST['Numero'];
$colonia=$_POST['Colonia'];
$Ciudad=$_POST['Ciudad'];
$Parentesco=$_POST['Parentesco'];
$ClinicaAds=$_POST['ClinicaAds'];
$Dependencia=$_POST['Dependencia'];
$Entidad=$_POST['Entidad'];
$Foraneo=isset($_POST['Foraneo']) ? 1 : 0;
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "issste";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = " INSERT INTO paciente (RFC, Nombre, Sexo, FechaNacimiento, Calle, NumeroDomiciliario, Colonia, Ciudad, Dependencia, ClinicaAdscrip, Entidad, Foraneo, Diagonal)
SELECT '$Expediente', '$Person_name', '$Sexo', '$Edad', '$Domicilio', '$numero', '$colonia', '$Ciudad', '$Dependencia', '$ClinicaAds', '$Entidad', '$Foraneo', '$Parentesco' FROM paciente
WHERE NOT EXIST(
SELECT RFC, Diagonal FROM paciente WHERE RFC = '$Expediente' AND Diagonal='10' OR Diagonal='20') LIMIT 1 ";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
when i run my program i get this error
"you have an error in your sql syntax check the manual that corresponds to your mysql server version"
Modified your query, try something like this:
INSERT INTO paciente (RFC, Nombre, Sexo, FechaNacimiento, Calle, NumeroDomiciliario,
Colonia, Ciudad, Dependencia, ClinicaAdscrip, Entidad, Foraneo, Diagonal)
SELECT '$Expediente', '$Person_name', '$Sexo', '$Edad', '$Domicilio', '$numero',
'$colonia', '$Ciudad', '$Dependencia', '$ClinicaAds', '$Entidad', '$Foraneo',
'$Parentesco'
WHERE NOT EXISTS( SELECT RFC, Diagonal FROM paciente
WHERE RFC = '$Expediente' AND Diagonal='10' OR Diagonal='20' LIMIT 1 )

PHP inserting XML prices into SQL table - SQL syntax error [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I'm new on StackOverflow. Hope I'm doing the questioning correctly.
I'm trying to insert data from an external XML (URL) into an SQL table, but I get:
Error: INSERT INTO 'table_name' ('price')VALUE ('5.95')
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 ''BBB' ('price')VALUE ('5.95')' at line 1
I'm able to ECHO and PRINT values from the XML and also able to INSERT non-xml values into the table. The code I'm using is:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$xml=simplexml_load_file("external_xml_url") or die("Error: Cannot create object");
foreach ($xml->product as $row) {
$price = $row -> price;
$sql = "INSERT INTO 'table_name' ('price')"
. "VALUES ('$price')";
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Would be great if someone can help me out on this one. I've the feeling I'm pretty close...
As far as I know, with MariaDB you have to use Backticks to "qoute" an object's name.
Try it like this:
$sql = "INSERT INTO `table_name` (`price`) VALUES ('$price')";
If you do not deal with dangerous object names you might use just
$sql = "INSERT INTO table_name (price) VALUES ('$price')";
If you got your price properly then you should check your query
Ex.
INSERT INTO table_name (price) VALUES ('$price')

How to use SET and INSERT in one php variable?

This is not duplicated question, since I am asking how to use SET and INSERT in one PHP variable, there no any questions about AUTO_INCREMENT...
I have below page:
<?php
function genWO(){
$dbtype = "MySQL";
$username = "user";
$password = "pass";
$hostname = "10.10.10.10";
$dbname = "TABLES";
//connection to the database
$conn = new mysqli($hostname, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$insertNewWONum = "SET #MAX_WO = (SELECT max(WO_NUM) + 1 from GENERIC_TABLES.WO_NUMBERS); INSERT INTO GENERIC_TABLES.WO_NUMBERS (WO_NUM, WO_REQUESTOR) values (#MAX_WO, `test`)";
if ($conn->query($insertNewWONum) === TRUE) {
echo "New record created successfully". "<br>";
} else {
echo "Error: " . $insertNewWONum . "<br>" . $conn->error;
}
$getWONum = "SELECT LPAD(max(WO_NUM) ,6,0) as NEW_WO_NUM from GENERIC_TABLES.WO_NUMBERS";
$result = $conn->query($getWONum);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "New WO Number: " . $row["NEW_WO_NUM"]. "<br>";
}
} else {
echo "0 results";
}
//close the connection
$conn->close();
}
?>
Since it is not allowed to use INSERT and SELECT for the same table in one query, I am trying to set variable and use it in INSERT query:
$insertNewWONum = "SET #MAX_WO = (SELECT max(WO_NUM) + 1 from GENERIC_TABLES.WO_NUMBERS); INSERT INTO GENERIC_TABLES.WO_NUMBERS (WO_NUM, WO_REQUESTOR) values (#MAX_WO, `test`)";
But it doesnt work, though it works fine if I am using this query in terminal.
Can anyone let me know how to achieve it please?
Since it is not allowed to use INSERT and SELECT for the same table in one query
All issues with your approach aside of course you can use INSERT and SELECT in one statement
INSERT INTO WO_NUMBERS (WO_NUM, WO_REQUESTOR)
SELECT COALESCE(MAX(WO_NUM), 0) + 1, 'Test'
FROM WO_NUMBERS;
Here is SQLFiddle demo.
Now what you need to realize is that your approach is unsafe for concurrent access. If this code is executed from two or more sessions simultaneously some or all of them may generate the same number effectively breaking your application.
Use AUTO_INCREMENT instead.
CREATE TABLE WO_NUMBERS
(
WO_NUM INT PRIMARY KEY AUTO_INCREMENT,
WO_REQUESTOR VARCHAR(32)
);
INSERT INTO WO_NUMBERS (WO_REQUESTOR) VALUES ('Test');
Here is SQLFiddle demo.
If for some reason you can't use AUTO_INCREMENT directly (and I honestly don't see why you couldn't) i.e. you need to add prefixes or augment the generated id/code in some way you can look this answer.

How to prevent inserting duplicate records?

I want to make my PHP check if something with the same specific data already exists in my database table.
I have a database called test with a table called users.
This is where I would like to check if a row steamid already exists with the same $steamid number.
<?php
// Datebase infomation
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$steamid = $steamprofile['steamid'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create data
$sql = "INSERT INTO users (steamid)
VALUES ('$steamid')";
if (!$conn->query($sql) === TRUE) {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
you need to add a PRIMARY KEY or a UNIQUE constraint on the steamid column.
after deleting all the duplicates, then you can run this command:
ALTER TABLE users ADD PRIMARY KEY(steamid)
then your query will fail if you attempt to insert a duplicate steamid into the users table.
as #Jeremy mentioned, you can use REPLACE, but this also only works if you have a PRIMARY KEY or UNIQUE constraint on the column. this is the preferred method if you have additional columns aside from the steamid that you want to store in the database table because it will update those values. however, since your query as stated in the question INSERT INTO users (steamid) VALUES ('$steamid') only contains the one field, then it's not of much consequence unless you want to catch the conditional error of an attempted duplicate record, in which case you should stick to the INSERT statement.

UPDATE if exists else insert [duplicate]

This question already has answers here:
How can I do 'insert if not exists' in MySQL?
(11 answers)
Closed 7 years ago.
What is the correct format for UPDATE if exists else insert in this situation - I have managed to do update and insert separately but need them together?.
What I want is that - if the date exists then it gets updated to fullday, and if it doesn't exist then a new row with the new details gets inserted.
$date = (isset($_POST['date']) ? $_POST['date'] : null);
$reservationType = (isset($_POST['reservation-type']) ? $_POST['reservation-type'] : null);
$connect = new mysqli($servername, $username, $password, $dbname);
// check connection
if ($connect->connect_error) {
die("connection failed: ". $connect->connect_error);
}
$sql = "SELECT * FROM reservations";
$result = $connect->query($sql);
if ($result -> num_rows > 0) {
while ($row = $result->fetch_assoc()) {
if ($date == $row['date_of_reservation']) {
"UPDATE reservations SET reservationType = 'FULLDAY' WHERE date_of_reservation='$date'";
}
else {
"INSERT INTO reservations (date_of_reservation, reservationType) VALUES ('$date', '$reservationType')";
}
}
}
From the manual:
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;

Categories