View Full Version : PHP code working but Database field is empty

11-25-2011, 06:13 AM
This is my Code which just take names from customer and place it in databases.What i am seeing is that the code working fine,Showing echo message also but in database i created 2 field 1 auto incremented id and other for name.the id is generated but the name field remains blank..please help me.


$link = mysql_connect("localhost","root","");
if (! $link) {
die('cannot connect: ' .mysql_error() ) ;
$db_selected = mysql_select_db ("adform",$link );
die('cannot use :' .mysql_error() ) ;

$value = $_POST['firstname'];

$sql ="INSERT INTO demo (firstname) VALUES ('$value')" ;

if(!mysql_query($sql) ) {
die ('Error :' . mysql_error());
echo "record added to database ";
mysql_close ($link);

11-25-2011, 08:12 AM
Do you have the HTML? Also remember to use mysql_escape_string() function around your $_POST/$_GET variables.

Make sure column name is correct, check table name, etc. Make sure the name value for the input box is actually 'firstname'.

11-25-2011, 08:20 AM
ya i have HTML

<form method="post" action="demo.php">

<p>First Name <input type="text" name="firstname" /></p>

<input type="Submit" value="Submit" /> </form>


I checked the php code bt nothing is putted in firstname column.it is kept empty though id is generating .
please help me

11-25-2011, 09:25 AM
Try changing

if(!mysql_query($sql) ) {
die ('Error :' . mysql_error());

mysql_query($sql,$link) or die(mysql_error());

and see what you get.

And please don't cross post ... you've already asked this question in the MySQL forum (http://www.codingforums.com/showthread.php?t=244648).

11-25-2011, 10:49 AM
1.First of all i want to give a thanks to you..Code now working fine after doing your step.Can u please tell me why dis thing happened ?

2.How to write this code so that my code becomes SQL injected free.putting mysql_real_escape_stringdoesnot helping me? can u please check dat one

$value = mysql_real_escape_string($_POST['Firstname']);

11-25-2011, 11:11 AM
Please stop using large colored text in your posts.

Can u please tell me why dis thing happened ?

A call to mysql_query needs both the query to be done and the database the query should be done against. You forgot to include the database in your original code.

2How to write this code so that my code becomes SQL injected free.putting mysql_real_escape_string does not helping me?

$value = mysql_real_escape_string($_POST['Firstname']);

That is the correct way but you don't have to create a separate variable. Simply do it when you're building your query string.

$sql ="INSERT INTO demo (firstname) VALUES ('" . mysql_real_escape_string($_POST['firstname']) . "')" ;

It likely wasn't working as you expected because your variable name was incorrect. You used firstname in your form but Firstname when you were using mysql_real_escape_string.