0

So I am sorry as I feel I ask stupid questions a lot. I am learning as I go but getting there.

I've created a basic HTML form and with the help of a previous answer I've made the PHP and MySQL query. However when I submit the form the input values from the form come up as column names rather than the information to be updated in the row.

In simple terms when the form is submitted if the input is to change first name from James to Josh the error message is:

"Error updating record: Unknown column 'Josh' in 'field list'"

I though in my SQL query below it would pick up the column name as first_name but this is obviously not happening.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Users";

//Create variables
$first_name=$_POST['first_name'];
$last_name=$_POST['last_name'];
$ID=$_POST['ID'];

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 

$sql = "UPDATE Users SET first_name=$first_name, last_name=$last_name WHERE 
ID=$ID";

if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}

$conn->close();
?>
James
  • 190
  • 2
  • 4
  • 13
  • Possible Duplicate https://stackoverflow.com/questions/1346209/unknown-column-in-field-list-error-on-mysql-update-query – Agam Banga Jun 10 '17 at 17:55
  • I did read through that but doesn't seem to cover the issue I'm getting. My problem is the form input is changing the expected column name in the SQL query. So where the column name is first_name and I want to UPDATE it as Josh it's actually looking for the column name Josh. – James Jun 10 '17 at 17:59
  • You don't have the quotes on $first_name and other fields. String should be wrapped in quotes – Agam Banga Jun 10 '17 at 18:01
  • Are you kidding me? lol is that literally it? Thank you so much! – James Jun 10 '17 at 18:02
  • Yup!! That will fix the issue. Happy to help – Agam Banga Jun 10 '17 at 18:04
  • 1
    Your query is wide open for SQL injection! Do a google search on "php mysqli parameterized statements" . – Drew Jun 10 '17 at 18:07
  • Hi Drew, I'm well aware but thank you for pointing it out, this is just on a localhost whilst I test a system, if/when it goes live on the web I'm going to go through all that. – James Jun 10 '17 at 18:09
  • If you start using parameterized statements from the beginning, you can't forget one when you think you have changed all queries. – Arjan Jun 10 '17 at 19:19

1 Answers1

0

I don't know PHP, but I suspect that your problem is that you arent't quoting the value in your update statment. So try something like:

"UPDATE Users SET first_name='$first_name', last_name='$last_name' WHERE ID=$ID"
TimGJ
  • 1,584
  • 2
  • 16
  • 32