samira
samira

Reputation: 1295

issue when inserting data to database

My code doesn't insert any records to mysql. What is wrong? I am really confused. I have designed a form and I want to read data from text box and send to the database.

<?php
if(isset($_post["tfname"]))
    {
        $id=$_post["tfid"];
        $name=$_post["tfname"];
        $family=$_post["tffamily"];
        $mark=$_post["tfmark"];
        $tel=$_post["tftell"];

$link=mysql_connect("localhost","root","");
if (!$link)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("university",$link);
$insert="insert into student (sid,sname,sfamily,smark,stel) values ($id,'$name','$family',$mark,$tel)";

mysql_query($insert,$link);
    }
mysql_close($link);
?>

Upvotes: 1

Views: 95

Answers (4)

Mohammad Saberi
Mohammad Saberi

Reputation: 13166

You'd better to put quotation mark for id, mark and tel after values in your query. Also as @Another Code said, you must use $_POST instead of $_post in your code. Try this and tell me the result:

<?php
if(isset($_POST["tfname"])) {
   $id=$_POST["tfid"];
   $name=$_POST["tfname"];
   $family=$_POST["tffamily"];
   $mark=$_POST["tfmark"];
   $tel=$_POST["tftell"];

   $link=mysql_connect("localhost","root","");
   if (!$link) {
      die('Could not connect: ' . mysql_error());
   } else {
      mysql_select_db("university",$link);
      $insert="insert into student 
               (sid,sname,sfamily,smark,stel) values 
               ('$id','$name','$family','$mark','$tel')";
      mysql_query($insert,$link) or die (mysql_error());
      mysql_close($link);
   }
} else {
   die('tfname did not send');
}
?>

Use mysql_query($insert,$link) or die (mysql_error()); to fetch the error message.

Upvotes: 2

yuvrajm
yuvrajm

Reputation: 318

change the $insert to:

$insert="insert into student (sid,sname,sfamily,smark,stel) values ($id,'".$name."','".$family."','".$mark."','".$tel."')";

further set ini_set('display_errors',1) so that php displays the error messages as required.

Lastly, whenever doing a mysql query, try to use or die(mysql_error()) in the query so that if somethings wrong with mysql or syntax, we are aware.

$q = mysql_query($query) or die(mysql_error());

Upvotes: -1

Nav Ali
Nav Ali

Reputation: 1230

Try to run the generated sql query in the sql query browser. Get the query by "echo $insert" statement.

Upvotes: 0

Ryan Kempt
Ryan Kempt

Reputation: 4209

With the code you've provided it could almost be anything - to do some tests... have you echo'd something to confirm you are even getting the tfname in POST? Does it select the database fine? Do the fields $id, $mark, and $tel need single quotes around them as well? We need to know more about where the code is not working to provide more help but that snippet appears as though it should be running, in the interim, please use some echo's to narrow down your problem!

Upvotes: 0

Related Questions