php - My PDO Insert data not working -


i wanted add data type in inputs database current code wont work. code tutorials i've watched in youtube. problem not adding data inputed database.

index.php

<?php  require_once('header.php'); ?> <html lang="en"> <head> </head> <body> <form method="post" action="index.php">  name: <input type="text" id="name" name="name" /><br /> age: <input type="text" id="age" name="age" /><br /> address: <input type="text" id="address" name="address" /><br /> <input type="radio" name="gender" id="gender" value="male" />male <input type="radio" name="gender" id="gender" value="female" />female<br /> <input type="submit" value="add" /> </form> </body> </html> 

header.php:

<?php $host = "localhost"; $user = "root"; $pass = ""; $db = "test";  $dbc = new pdo("mysql:host=" . $host . ";dbaname=" . $db, $user, $pass);  if(isset($_post['name'])){     $name = $_post['name'];     $age = $_post['age'];     $address = $_post['address'];     $gender = $_post['gender'];     $q = "insert students(name, age, address, gender) values(:name, :age, :address, :gender);";     $query = $dbc->prepare($q);     $results = $query->execute(array(         ":name" => $name,         ":age" => $age,         ":address" => $address,         ":gender" => $gender     )); } ?> 

did small cleanup here. noticed extant ; @ end of insert into query, removed that. also, using bindparam instead of passing array. should work.

if(isset($_post['name'])){      $name = isset($_post['name']) ? $_post['name'] : null;     $age = isset($_post['age']) ? $_post['age'] : null;     $address = isset($_post['address']) ? $_post['address'] : null;     $gender = isset($_post['gender']) ? $_post['gender'] : null;      $q = "insert students(name, age, address, gender) values(:name, :age, :address, :gender)";      $query = $dbc->prepare($q);     $query->bindparam(':name', $name);     $query->bindparam(':age', $age);     $query->bindparam(':address', $address);     $query->bindparam(':gender', $gender);      $results = $query->execute();  } 

but looking @ code there ways can refine more:

if(isset($_post['name'])){      $q = "insert students(name, age, address, gender) values(:name, :age, :address, :gender)";      $query = $dbc->prepare($q);      // set array of post values.     $post_array = array('name','age','address','gender');      // loop through post values, set string & assign string via bindparam.     foreach ($post_array $post_value) {       $$post_value = isset($_post[$post_value]) ? $_post[$post_value] : null;       $query->bindparam(':' . $post_value, $post_value);     }      $results = $query->execute();  } 

the main refinement did take of $_post values & place them in array. loop through array , act on values.


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -