yangkai9999 Posted November 2, 2009 Report Share Posted November 2, 2009 Hello,I wrote a very simple PHP code to insert record into MySQL database. So far, it works.But I found a bug in the program. when I left a blank at a field and insert the data into DB, the field will automatic bacome 0 (for numeric field) or blank (in chr field). But I realy want to keep it as null. How should I modify my code to do that?Thank you,code:<?php$p_id=$_POST["p_id"];$v1=$_POST["v1"];$v2=$_POST["v2"];$v3=$_POST["v3"];$v4=$_POST["v4"];mysql_connect("localhost","root","Openit4me");mysql_select_db("mytest") or die( "Unable to select database/ this is kai.yang note");//echo $$v1;//echo $$v2;//echo $$v3;//echo $$v4;$query = "INSERT INTO mytest.p2 (p_id, v1, V2, V3, V4) VALUES ('$p_id','$v1','$v2','$v3',$v4);";//echo "$query";if (!mysql_query($query)) { die('Error: ' . mysql_error()); }echo '1 record was added';mysql_close();?> <! this part is go back to add home page><form action="add.htm" method="post"><p><input type="submit" value="add more record" name="add more record" /n> </p></form><BUTTON onclick="window.close();">Finish input</BUTTON> Link to comment Share on other sites More sharing options...
justsomeguy Posted November 3, 2009 Report Share Posted November 3, 2009 You need to construct the query one piece at a time and check each piece. $query = "INSERT INTO mytest.p2 (p_id, v1, V2, V3, V4) VALUES (";if ($p_id != '') $query .= "'{$p_id}',";else $query .= 'NULL,';if ($v1 != '') $query .= "'{$v1}',";else $query .= 'NULL,';...etc$query .= ')'; Link to comment Share on other sites More sharing options...
yangkai9999 Posted November 3, 2009 Author Report Share Posted November 3, 2009 You need to construct the query one piece at a time and check each piece.$query = "INSERT INTO mytest.p2 (p_id, v1, V2, V3, V4) VALUES (";if ($p_id != '') $query .= "'{$p_id}',";else $query .= 'NULL,';if ($v1 != '') $query .= "'{$v1}',";else $query .= 'NULL,';...etc$query .= ')'; Thank you. I'll try that. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now