Ad

Dynamic Form Insert Database

- 1 answer

My whole signup page code is here. Link

I'm trying to add this dynamic fields to the signup page code.

<script>

 var i = 1;
 function addKid(){
    if (i <= 6){
      i++;
 var div = document.createElement('div');
 div.style.width = "44%";
 div.style.height = "26px";
 div.style.color = "white";
 div.setAttribute('class', 'myclass');
 div.innerHTML = 'Child : <input type="text" name="child_'+i+'" > Ages : <input type="text" name="ages_'+i+'"><input type="button" id="add_kid()" onClick="addKid()" value="+" /><input type="button" value="-" onclick="removeKid(this)">';
 document.getElementById('kids').appendChild(div);
 }
 }
 function removeKid(div) {
     document.getElementById('kids').removeChild( div.parentNode );
 i--; }

         <div id="kids">
     Child : <input id="child_1" type="text" onfocus="emptyElement('status')" onkeyup="restrict('mwhen')" maxlength="50">

      Ages :  <input id="ages_1" type="text" onfocus="emptyElement('status')" onkeyup="restrict('mwhen')" maxlength="10"><input type="button" id="add_kid()" onClick="addKid()" value="+" />
       </div>

I can get the "child_1 / chi" and "ages_1 / ags" insert into my database. no problem.

When I try to create a extra dynamic field in my signup, "child_2 and ages_2"..... then I can't get that info from "child_2 and ages_2" insert into my database.

Can some one tell me what I'm doing wrong since I can't get that info into my database.? Am I suppose to call "child_2 / chi2" and "ages_2 / ags2" for something els before it will work.?

if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once("php_includes/db_conx.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = $_POST['p'];
$g = preg_replace('#[^a-z]#', '', $_POST['g']);
$chi = preg_replace('#[^a-z.,-/ ]#i', '', $_POST['chi']);
$ags = preg_replace('#[^0-9.]#i', '', $_POST['ags']);
$chi2 = preg_replace('#[^a-z.,-/ ]#i', '', $_POST['chi2']);
$ags2 = preg_replace('#[^0-9.]#i', '', $_POST['ags2']);
$c = preg_replace('#[^a-z ]#i', '', $_POST['c']);
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql); 
$u_check = mysqli_num_rows($query);
// -------------------------------------------
$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
$query = mysqli_query($db_conx, $sql); 
$e_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if($u == "" || $e == "" || $p == "" || $g == "" || $chi == "" || $ags == "" || $chi2 == "" || $ags2 == "" || $c == ""){

..

        $sql = "INSERT INTO users (username, email, password, gender, child_1, ages_1, child_2, ages_2, country, ip, signup, lastlogin, notescheck)       
            VALUES('$u','$e','$p_hash','$g','$chi','$ags','$chi2','$ags2','$c','$ip',now(),now(),now())";
    $query = mysqli_query($db_conx, $sql); 
    $uid = mysqli_insert_id($db_conx);

..

function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "email"){
    rx = /[' "]/gi;
} else if(elem == "username"){
    rx = /[^a-z0-9]/gi;
} else if(elem == "child_1"){
    rx = /[^a-z.,-/ ]/gi;
} else if(elem == "ages_1"){
    rx = /[^0-9.]/gi;
} else if(elem == "child_2"){
    rx = /[^a-z.,-/ ]/gi;
} else if(elem == "ages_2"){
    rx = /[^0-9.]/gi;
} 
tf.value = tf.value.replace(rx, "");

} ..

function signup(){
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var c = _("country").value;
var chi = _("child_1").value;
var ags = _("ages_1").value;
var chi2 = _("child_2").value;
var ags2 = _("ages_2").value;
var g = _("gender").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == "" || c == "" || chi == "" || ags == "" || chi2 == "" || ags2 == "" || g == ""){

..

        }
    ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&chi="+chi+"&ags="+ags+"&chi2="+chi2+"&ags2="+ags2+"&g="+g);
}

..

Ad

Answer

kindly save your child and age in array and pass it in ajax. so that you can loop the child and age as given below and insert it into table.

For password and conform password use js. and validate it in front end itself. save password alone in table that's enough.

try to understand this code and do alterations as required. but i sloved your dynamic child and age problem. run this code

page1.php

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</script></script>
    <script type="text/javascript">
         $(document).ready(function(){
             $("#input_form").submit(function(){
             var querystring = $(this).serialize();
                $.ajax({
            url: 'save_child.php',
            type: "POST",
            data: querystring,
            success: function(data) {
            alert("jhkl");
                    }
            });
                 //$('#result').html(querystring);
                 return false;
                 });
        });
    </script>
    <title>Serialize</title>
</head>
<body>
    <form  id="input_form">
        first name: <input type="text" name="username" id="first name"/><br />
     password: <input type="text" name="password" id="last name"/><br />
        email: <input type="text" name="email" id="email"/><br />
     <div id="kids">
     Child : <input id="child_1" type="text" onfocus="emptyElement('status')" onkeyup="restrict('mwhen')" maxlength="50" name="child[]">

      Ages :  <input id="ages_1" type="text" onfocus="emptyElement('status')" onkeyup="restrict('mwhen')" maxlength="10" name="ages[]"><input type="button" id="add_kid()" onClick="addKid()" value="+" />
       </div>  

       <input type="submit" value="send" name="submit" />
    </form>
    <p id="result"></p>
</body>
</html><script>

 var i = 1;
 function addKid(){
    if (i <= 5){
      i++;
 var div = document.createElement('div');
 div.style.width = "44%";
 div.style.height = "26px";
 div.style.color = "white";
 div.setAttribute('class', 'myclass');
 div.innerHTML = 'Child : <input type="text" name="child[]" > Ages : <input type="text" name="ages[]"><input type="button" id="add_kid()" onClick="addKid()" value="+" /><input type="button" value="-" onclick="removeKid(this)">';
 document.getElementById('kids').appendChild(div);
 }
 }
 function removeKid(div) {
     document.getElementById('kids').removeChild( div.parentNode );
 i--; }
</script>

save_child.php

<?php
$child=$_REQUEST['child'];// child array
$ages=$_REQUEST['ages'];
$InputArray = array();
$conn=mysqli_connect("localhost","root","","tes");// data base connection


$InputArray['username']=$_REQUEST['username'];// get datas and store in a array named InputArray
$InputArray['password']=$_REQUEST['password'];
$InputArray['email']=$_REQUEST['email'];
$i=1;
foreach($child as $val){
$b=$i-1;
$InputArray['child_'.$i]=$val;
$InputArray['age_'.$i]=$ages[$b];
$i++;
}


$sql="CREATE TABLE IF NOT EXISTS `userss` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(30) NOT NULL,
  `email` varchar(20) NOT NULL,
  `password` varchar(20) NOT NULL,
  `country` varchar(20) NOT NULL,
  `child_1` varchar(20) NOT NULL,
  `age_1` varchar(20) NOT NULL,
  `child_2` varchar(20) NOT NULL,
  `age_2` varchar(20) NOT NULL,
  `child_3` varchar(20) NOT NULL,
  `age_3` varchar(20) NOT NULL,
  `child_4` varchar(20) NOT NULL,
  `age_4` varchar(20) NOT NULL,
  `child_5` varchar(20) NOT NULL,
  `age_5` varchar(20) NOT NULL,
  `ip` varchar(60) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ";

    mysqli_query($conn,$sql);
if (count($InputArray) > 0) {
            while (list($key, $val) = each($InputArray)) {
                if(!empty($val)){
                    $fields.= $key . ',';
                    $valset.= "'". $val ."',";
                }
            }
        }   

        $fields = trim($fields, ',');
        $valset = trim($valset, ',');
        $sql = "INSERT INTO userss ($fields) VALUES ($valset)";

        mysqli_query($conn,$sql);
?>

Another one thing I have noted in your code.

$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";

$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";

you have written two query for this. make it single as given

$sql = "SELECT id FROM users WHERE email='$e' and username='$u' LIMIT 1";

Ad
source: stackoverflow.com
Ad