Freelancer Help
Freelancer Help

Reputation: 181

How can I update the column rather then adding another value to it?

So I've created a form on my website, it has one input and when the user fills it it store it in the datebase table, it stores what user wrote.

Now whenever I again type something it adds just one more value to the column and I want to replace the one that is already added. So what I want is when I type for example "Datebase" it will be stored in the MySQL table, but again when I type "Datebase change" in the same input it will just the update the current value and it will be changed from "Datebase" to "Datebase change". So I dont want to add more values I just need this one input which will change what it is on column on every submit.

My code:

<?php 

$title = 'Admin Panel - Edit';
include '../config.php';

$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);

// Attempt insert query execution
$sql = "INSERT INTO content (heading) VALUES ('$heading')";
if(mysqli_query($link, $sql)){
    echo "Records inserted successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

?>

<form action="edit.php">
    <input type="text" name="heading" id="heading" />
    <input type="submit" value="Submit" name="submit" />
</form>

Upvotes: 0

Views: 117

Answers (1)

David
David

Reputation: 218818

INSERT adds a new row to the table. UPDATE updates existing rows. So you might do something like this:

UPDATE content SET heading = ?

(Note: I'm using a parameter placeholder here. While escaping input the way you currently do is a good idea, it's not the correct approach. Query parameters are still safer and more stable in general. This is a good place to start for that.)

Note however that, without a WHERE clause, this will replace every record in the table. Though it sounds like you only ever want there to be one record in the table and so this is your actual desired behavior, is that correct? If so then I suppose a simple approach in terms of logical steps might be:

  • Read from the table.
  • If a row exists, update.
  • Else, insert.

But this ends up querying the database twice, when with the right data model you only need to do it once. If your table has a simple int primary key, not auto-increment, then you could do something like this:

INSERT INTO content (id, heading) VALUES(1, ?) ON DUPLICATE KEY UPDATE heading = ?

What this would do is explicitly insert a hard-coded primary key of 1. Or, if that key already exists in the table (meaning you've already inserted your one intended record) then it updates that record.

Upvotes: 2

Related Questions