Jump to content

[SOLVED] UPDATE a table using a list of fields in a $variable


mrherman

Recommended Posts

Greetings!

 

How might I go about this...? ???

 

I want to generate a list of field names into a string variable, and then I want to update the MySQL table by assigning all of these fields to a NULL value.

 

(I've tried literally dozens of combinations, searched the documentation for examples, and followed up with Google, but I have not been successful.)

 

Something like...

 

$fields = "f1,f2,f3......f50" ;

$sql = "UPDATE $mytable SET $fields = NULL" ;

$results = mysql_query($sql) ;

 

Thanks for any pointers on this!

Have you ever considered data normalization?

 

http://dev.mysql.com/tech-resources/articles/intro-to-normalization.html

 

 

try

<?php
$fields = "f1,f2,f3,f50" ;
$farray = explode(',', $fields);

$sql = "UPDATE $mytable SET " ;

foreach ($farray as $f)
{
    $sql .= "\n$f = NULL";
}

echo '<pre>', $sql, '</pre>';    // inspect the query

$results = mysql_query($sql) ;

?>

BINGO!! By George, Sir, you have it!

 

Thank ya, thank ya, thank ya!!  I never would have achieved it!

 

And, oh yes, a little normalization would be in line...The table actually has 400+ fields now and I bet it will end up with 500 or so.  Not exactly a textbook model.  (Well, perhaps the "bad" example.)

 

Your help is much appreciated.

 

Dave

BINGO!! By George, Sir, you have it!

 

 

Oops! Not quite. I forgot the commas

<?php
$fields = "f1,f2,f3,f50" ;
$farray = explode(',', $fields);

$sql = "UPDATE $mytable SET \n" ;

foreach ($farray as $k=>$f)
{
    $farray[$k] = "$f = NULL";
}
$sql .= join(",\n", $farray);

echo '<pre>', $sql, '</pre>';    // inspect the query

$results = mysql_query($sql) ;

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.