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!

Link to comment
Share on other sites

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) ;

?>

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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) ;

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.