-1

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();
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Dominik
  • 1,265
  • 1
  • 16
  • 27
  • 2
    I've copied the relevant code to into the question. Please understand it is more difficult for people to visit an external resource to get your code, and further, **when** that link breaks (not if, *when*), this question will have no value to future visitors. – random_user_name Jan 08 '17 at 14:55
  • `$newfilename` is defined where/how? seems file-related. – Funk Forty Niner Jan 08 '17 at 14:56
  • Your code is wide open to [SQL Injection attacks](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – random_user_name Jan 08 '17 at 14:56

2 Answers2

0

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.

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
0

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.

German Lashevich
  • 2,193
  • 27
  • 38