-1

How to get updated a single column by giving the input.Here is my code.

$sql="UPDATE isourcetest SET hostname='".$_POST['fname']."', 
IP='".$_POST['Iname']."', location='".$_POST['Lname']."', 
network='".$_POST['nname']."', OSversion='".$_POST['oname']."', 
RAM='".$_POST['rname']."',CPUcore='".$_POST['cname']."',
CPUspeed='".$_POST['cpname']."', 
Hardwaremodel='".$_POST['hname']."'
WHERE hostname='".$_POST['fname']."'";

But here if i try to update a column the entire row will be updated. Please suggest a solution.I am new in sql.

Mudassir Hasan
  • 28,083
  • 20
  • 99
  • 133
abhi
  • 55
  • 1
  • 1
  • 6
  • See about prepared statements. – Strawberry Sep 06 '16 at 10:17
  • 1
    Either build the query dynamically, based upon the input. Or make sure that all the input is included (including data identical to that being updated). – Strawberry Sep 06 '16 at 10:21
  • ***NEVER*** put user / POST / GET data directly into a SQL query like this. Read up on `Escaping SQL inputs` and `Prepared Statements` . – Martin Sep 15 '16 at 09:19

4 Answers4

1

You only need to write an update of one column, for example of hostname:

$sql="UPDATE isourcetest SET hostname='".$_POST['fname']."' 
WHERE hostname='".$_POST['fname']."'";
Tedo G.
  • 1,556
  • 3
  • 17
  • 29
0

Use COALESCE()

$sql="UPDATE isourcetest SET hostname=COALESCE('".$_POST['fname']."', hostname), 
IP=COALESCE('".$_POST['Iname']."', IP),.....etc

WHERE hostname='".$_POST['fname']."'";

Let me know if it works

Community
  • 1
  • 1
Rohit Dhiman
  • 2,691
  • 18
  • 33
0

try this..

$sql="UPDATE isourcetest SET ";
if($_POST['fname'] != '')
$sql."hostname='".$_POST['fname']."',"; 
.
.
if($_POST['hname'] != '')
$sql."Hardwaremodel='".$_POST['hname']."',";

rtrim($sql,',');

$sql."WHERE hostname='".$_POST['fname']."'";
Vishal Gupta
  • 124
  • 6
0

Below code worked for me.

if($_POST['fname'])
{
$sql="UPDATE tablename SET hostname='".$_POST['fname']."' WHERE hostname='".$_POST['fname']."'";
if (!mysql_query($sql,$db))
  {
  die('Error: ' . mysql_error());
  }

}
.
.
.
if($_POST['hname'])
{
$sql="UPDATE tablename SET Hardwaremodel='".$_POST['hname']."' WHERE hostname='".$_POST['fname']."'";
if (!mysql_query($sql,$db))
  {
  die('Error: ' . mysql_error());
  }

}

Thank you all for the support.

Martin
  • 22,212
  • 11
  • 70
  • 132
abhi
  • 55
  • 1
  • 1
  • 6
  • Stop using MySQL_ as soon as possible and research using `MySQLi_` and or `PDO`. MySQL_ is flawed, unsafe, and Deprecated. Also do not insert POSTed or GET data directly into SQL queries as you can't trust it. – Martin Sep 15 '16 at 09:21