Jump to content

Keep Null Value If Not Input


yangkai9999

Recommended Posts

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

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

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

Archived

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

×
×
  • Create New...