Greetings everyone

i'm working on small project on php and MySQL and i just start to learn them

i write a code that allow me to add new field in my table with default value but i wanted to ask can i make the field added to the table with default value but for the records with value '1' in the previous field it add other value

e.i

my table contain

names 1/1/2011 "the new field that the code will add"

john 1 A
mark 0 P
kate 1 A

so if the previous field have 1 it will add A as default value if it have 0 it will add P as default value


my code

<?php


$host="localhost"; 
$username="root";  
$password="";  
$db_name="el"; 



mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("DB not found");


$myusername=$_POST['myusername']; 



$datf= gmdate(DATE_RFC822);
@mysql_query("ALTER TABLE `attendace_info_old` ADD `$datf` varchar(255)DEFAULT 'A'") or die(mysql_error());



?>

so
i want to add only one field this field will be filled automatically so if the previous field record contain 0 it will be filled as A if it contain 1 it will be filled as P


hope there are a way to make this because i finished everything only this step still for me

Recommended Answers

All 3 Replies

Member Avatar for diafol

Why do you need two fields if they do the same thing? If 1 = A and 0 = P, they equate to the same thing. You're effectively duplicating fields.

you don't understand me my friend

i want to add only one field and i write my old code that add 0 as default value

i want to add only one field this field will be filled automatically so if the previous field contain 0 it will be filled as A if it contain 1 it will be filled as P

Member Avatar for diafol

No I think I do understand. I just don't get why need A and P if you have 0 and 1 which to all intents and purposes do the same thing.

However, if you insist on going down this route. For existing records, run this once:

$r = mysql_query("UPDATE table SET field3 = IF(field2 = 1,'P', 'A')");

For new records,

//get $int from passed variable (0 or 1)
$str = ($int == 1) ? 'P' : 'A';
$r = mysql_query("INSERT INTO table SET field2 = $int, field3 = '$str'");

I don't think you can set up conditional default values. perhaps you could do something with triggers or stored procedures, but I think the php method is easier.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.