简体   繁体   中英

update mysql table with php if statement

I have a table with a int column named ssn and a column called male.

Now i want to update the male column with either 1 or 0 depending on the second last digit being odd or even in the ssn column.

$sql = "SELECT * FROM db";
$result = $DBH->prepare($sql); 
$result->execute(); 
foreach($result as $row) {
$male = $row['ssn'];
$male = substr($male, -2, 1);
    if ( $male & 1 ) {
                          $gender = 1;//odd
                         }else
                         {
                          $gender = 0;};

$results= $DBH->prepare("UPDATE loandb_enkatsvardb SET male = $gender ")or die(mysql_error());
$results->execute();

The error I recieve after loading for a long time is "Internal Server Error".

I also tried "insert ignore on duplicate" where it only saved "1's" in the male column regardless of what the ssn column contained.

Cheers

There is no WHERE clause on your query, so each execution of that UPDATE statement is going to update all rows in the table. Your UPDATE should really be of the form WHERE unique_id = id_value .

But rather than bother with all that fetching and all the individual updates, you could get the same thing done MUCH more efficiently in one fell swoop with one statement:

UPDATE loandb_enkatsvardb SET male = SUBSTR(ssn,-2,1) MOD 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM