Updating more than 1 field at a time

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

tonytimms
New php-forum User
New php-forum User
Posts: 2
Joined: Thu Mar 21, 2013 3:15 am

Updating more than 1 field at a time

Postby tonytimms » Thu Mar 21, 2013 3:23 am

Hi, this is my first post. I am learning PHP and have the following simple script for updating the mysql database.

<html>
<head>
<title>Update a Record in MySQL Database</title>
</head>
<body>

<?php
if(isset($_POST['update']))
{
$dbhost = 'localhost';
$dbuser = 'myuser';
$dbpass = 'pasword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}

$ID = $_POST['ID'];
$field1 = $_POST['field1'];
$field2 = $_POST['field2'];
$field3 = $_POST['field3'];
$field4 = $_POST['field4'];

$sql = "UPDATE table1 ".
"SET field1 = $field1 ".
"WHERE ID = $ID" ;

mysql_select_db('j30ctts_mydb1');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">ID</td>
<td><input name="ID" type="text" id="ID"></td>
</tr>
<tr>
<td width="100">Field1</td>
<td><input name="field1" type="text" id="field1"></td>
</tr>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="update" type="submit" id="update" value="Update">
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>

My question is how can I get it to update more than one field? How do I change the following to allow me to do this? I have tried all kinds of options without success.

$sql = "UPDATE table1 ".
"SET field1 = $field1 ".
"WHERE ID = $ID" ;

Regards

seandisanti
php-forum Fan User
php-forum Fan User
Posts: 838
Joined: Mon Oct 01, 2012 12:32 pm

Re: Updating more than 1 field at a time

Postby seandisanti » Thu Mar 21, 2013 3:45 pm

There are a few ways to do this. The easiest way is to make 2 arrays, one of the original values, and one of the post values, use array_merge() to mash them together. Then have your update statement just update EVERY field. The ones that didn't change will still be updated with their current value, but that won't hurt anything, and the ones that change will get the new values (as long as you put the arrays in the proper order in your array_merge())


Return to “PHP coding => General”

Who is online

Users browsing this forum: No registered users and 3 guests