Jump to content

tobimichigan

Members
  • Posts

    207
  • Joined

  • Last visited

Everything posted by tobimichigan

  1. Your code is wrong. You cannot or its not logical to put db connection within an isset function wrong code: <?php session_start(); if(isset($_POST['submit'])) { $con = mysql_connect("localhost","root",""); $db = mysql_select_db('cms',$con); $email=$_POST['email']; $name=$_POST['name']; $subject=$_POST['subject']; $designation=$_POST['designation']; $num=$_POST['#']; //$add_type=$_POST['add_type']; // echo $q= "select * from contactus where email='".$email."' and password='".$password."' " or die(mysql_error()); $sql = mysql_query($q); $q= "select * from contactus " or die(mysql_error()); $sql = mysql_query("select * from contactus"); //$res=mysql_fetch_object($sql); $rows = mysql_num_rows($sql); } ?> Right code: <?php session_start(); $con = mysql_connect("localhost","root",""); $db = mysql_select_db('cms',$con); if(isset($_POST['submit'])) { $email=$_POST['email']; $name=$_POST['name']; $subject=$_POST['subject']; $designation=$_POST['designation']; $num=$_POST['#']; //$add_type=$_POST['add_type']; // echo $q= "select * from contactus where email='".$email."' and password='".$password."' " or die(mysql_error()); $sql = mysql_query($q); $q= "select * from contactus " or die(mysql_error()); $sql = mysql_query("select * from contactus"); //$res=mysql_fetch_object($sql); $rows = mysql_num_rows($sql); } ?> Preferably include or require_once (dbcon.php) //if isset($_POST) goes here: hope this helps
  2. Any1 in the forum with a better idea?
  3. @ rwhite35 . see this on script.js: jQuery.ajax({ url:"DbManipute.php", type:"POST", data:"actionfunction=editUser&user="+edituser, cache: false, success: function(response){ jQuery('#update_user_sec').html(response); jQuery("#update_user_sec").show(); animating = false; } }); }, //this comes from the custom easing plugin easing: 'easeInOutBack' }); }); jQuery('#userists').on('click','.ajaxdelete',function(){ var user = jQuery(this).attr("user"); jQuery.ajax({ url:"DbManipute.php", type:"POST", data:"actionfunction=deleteUser&user="+user+"&page=1", cache: false, success: function(response){ jQuery('#userists').html(response); jQuery("#msg").html("user deleted"); } }); }); jQuery("#add_user").click(function(){ resetform(); jQuery(document).prop('title', 'Add User'); jQuery("#msg").html(""); if(animating) return false; animating = true; var activesec; for($i=0;$i<section.length;$i++){ if(jQuery(section[$i]).css('display')=="block"){ activesec = section[$i]; break; } } jQuery(".navi_sec").removeClass("active"); jQuery(this).parent().addClass("active"); jQuery(activesec).animate({opacity: 0}, { step: function(now, mx) { //as the opacity of current_fs reduces to 0 - stored in "now" //1. scale previous_fs from 80% to 100% scale = 0.8 + (1 - now) * 0.2; //2. take current_fs to the right(50%) - from 0% left = ((1-now) * 50)+"%"; //3. increase opacity of previous_fs to 1 as it moves in opacity = 1 - now; jQuery(activesec).css({'left': left}); jQuery("#add_user_sec").css({'transform': 'scale('+scale+')', 'opacity': opacity}); }, duration: 800, complete: function(){ jQuery(activesec).hide(); jQuery("#add_user_sec").show(); animating = false; }, //this comes from the custom easing plugin easing: 'easeInOutBack' }); }); jQuery('#update_user_sec').on('click','#updatesubmit',function(){ jQuery(".navi_sec a").removeClass("active"); var signupform = $("#update_user_sec").children("#signup"); var fname = jQuery(signupform).find("#firstname"); var lname = jQuery(signupform).find("#lastname"); var username = jQuery(signupform).find("#username"); var password = jQuery(signupform).find("#password"); var email = jQuery(signupform).find("#email"); var address = jQuery(signupform).find("#address"); var phone = jQuery(signupform).find("#phone"); var monthly_due = jQuery(signupform).find("#monthly_due"); if(validateform(fname,lname,username,password,email,address,phone,mothly_due)){ var formdata = signupform.serialize(); jQuery.ajax({ url:"DbManipute.php", type:"POST", data:formdata, cache: false, success: function(response){ if(response=='updated'){ jQuery("#show_user").trigger("click"); getusers(); jQuery("#msg").html("user Updated"); } } }); } });
  4. @ rwhite35 thanks for your swift response. the submit input type is set to <input type='button' id='updatesubmit' class='submit' value='Update' /> button id updatesubmit in the jquery is supposed to handle the action and the post data, please see the script.js for this.
  5. I have three scripts: a. Dbmanipute.php (contains the update script and other applicable functions) b. index3.php (contains initial forms for adding user) c. db2.php (default db for connection) d. script.js (contains the javascript code for ajax and jquery frames) Target: Using ajax, jquery tech to insert query, update and delete respectively or asynchronously. But after filling the form and I press submit, the contents of the form are held in and no process is made to the database. Please, anyone with a better suggestion is welcome, a.Dbmanipute.php <?php include('db2.php'); if(isset($_REQUEST['actionfunction']) && $_REQUEST['actionfunction']!=''){ $actionfunction = $_REQUEST['actionfunction']; call_user_func($actionfunction,$_REQUEST,$con,$limit,$adjacent); } function saveData($data,$con){ $fname = $data['firstname']; $lname = $data['lastname']; $username = $data['username']; $password = $data['password']; $email = $data['email']; $address = $data['address']; $phone = $data['phone']; $sex = $data['sex']; $monthly_due = $data['monthly_due']; $next_ofkin = $data['next_ofkin']; $nextofkin_address= $data['nextofkin_address']; $nextofkin_phone= $data['nextofkin_phone']; $datetime= $data['datetime']; $date_ofdue= $data['date_ofdue']; $sql = "insert into biodata(firstname,lastname,username,password,email,address,phone,sex,monthly_due,next_ofkin,nextofkin_address,nextofkin_phone,datetime,date_ofdue) values('$firstname','$lastname','$username','$password','$email','$address','$phone','$sex','$monthly_due','$next_ofkin','$nextofkin_address','$nextofkin_phone',NOW(),NOW())"; if($con->query($sql)){ echo "added"; } else{ echo "error".mysqli_error($con); } } function editUser($data,$con){ $bio_id = $data['user']; $bio_id = base64_decode($bio_id); $sql = "select * from biodata where bio_id=$bio_id"; $user = $con->query($sql); if($user->num_rows>0){ $user = $user->fetch_array(MYSQLI_ASSOC); ?> <form name='signup' id='signup'> <div class='row'> <p><label for='username'>First name</label> <input type='text' name='fname' id='firstname' value='<?php echo $user['firstname']; ?>' placeholder='Enter First name' /></p> </div> <div class='row'> <p><label for='lastname'>Last name</label> <input type='text' name='lname' id='lastname' value='<?php echo $user['lastname']; ?>' placeholder='Enter Last name' /></p> </div> <div class='row'> <p><label for='username'>USERNAME</label> <input type='text' name='username' id='username' value='<?php echo $user['username']; ?>' placeholder='Enter Username' /></p> </div> <div class='row'> <p><label for='username'>Password</label> <input type='password' name='password' id='password' value='<?php echo $user['password']; ?>' placeholder='Enter password' /></p> </div> <div class='row'> <p><label for='email'>Email</label> <input type='text' name='email' id='email' value='<?php echo $user['email']; ?>' placeholder='Enter Email' /></p> </div> <div class='row'> <p><label for='username'>Address</label> <textarea name="address" id="address" placeholder="Enter Address"><?php echo $user['address']; ?></textarea></p> </div> <div class='row'> <p><label for='phone'>Phone</label> <input type='text' name='phone' id='phone' value='<?php echo $user['phone']; ?>' placeholder='Phone' /></p> </div> <div class='row'> <p><label for='username'>Sex</label> <select name="sex" disabled="disabled"> <option value="Male">Male</option> <option value="Female">Female</option> </select> </p> </div> <div class='row'> <p><label for='monthly_due'>Monthly Due</label> <input type='text' name='monthly_due' id='monthly_due' value='<?php echo $user['monthly_due']; ?>' placeholder='Monthly_Due' /></p> </div> <div class='row'> <p><label for='next_ofkin'>Next of Kin</label> <input type='text' name='next_ofkin' id='next_ofkin' value='<?php echo $user['next_ofkin']; ?>' placeholder='Next of Kkin' /></p> </div> <div class='row'> <p><label for='username'>Address of Kin</label> <textarea name="nextofkin_address" id="nextofkin_address" placeholder="Enter Address of Kin"><?php echo $user['nextofkin_address']; ?></textarea></p> </div> <div class='row'> <p><label for='phone'>Next of Kin Phone</label> <input type='text' name='nextofkin_phone' id='nextofkin_phone' value='<?php echo $user['phone']; ?>' placeholder='Next of Kin Phone' /></p> </div> </div> <input type="hidden" name="actionfunction" value="updateData" /> <input type="hidden" name="user" value="<?php echo base64_encode($user['id']) ?>" /> <div class='row'> <input type='button' id='updatesubmit' class='submit' value='Update' /> </div> </form> <?php } } function showData($data,$con,$limit,$adjacent){ $page = $data['page']; if($page==1){ $start = 0; } else{ $start = ($page-1)*$limit; } $sql = "select * from biodata order by bio_id asc"; $rows = $con->query($sql); echo $rows = $rows->num_rows; $sql = "select * from biodata order by bio_id asc limit $start,$limit"; $data = $con->query($sql); $str='<tr class="head"><td>Firstname</td><td>Lastname</td><td>Username</td><td>Password</td><td>Email</td><td>Address</td><td>Phone</td><td>monthly_due</td><td></td></tr>'; if($data->num_rows>0){ while( $row = $data->fetch_array(MYSQLI_ASSOC)){ $str.="<tr id='".$row['id']."'><td>".$row['firstname']."</td><td>".$row['lastname']."</td><td>".$row['username']."</td><td>".$row['password']."</td><td>".$row['email']."</td><td>".$row['address']."</td><td>".$row['phone']."</td><td>".$row['monthly_due']."</td><td><input type='button' class='ajaxedit' value='Edit' user='".base64_encode($row['bio_id'])."' /> <input type='button' class='ajaxdelete' value='Delete' user='".base64_encode($row['id'])."' ></td></tr>"; } }else{ $str .= "<td colspan='5'>No Data Available</td>"; } $str = $str."<tr><td colspan='5'>".pagination($limit,$adjacent,$rows,$page)."</tr></tr>"; echo $str; } function updateData($data,$con){ $firstname = $data['firstname']; $lastname = $data['lastname']; $username = $data['username']; $password = $data['password']; $email = $data['email']; $address = $data['address']; $phone = $data['phone']; $monthly_due = $data['monthly_due']; $user = $data['user']; $user = base64_decode($user); $sql = "update biodata set firstname='$fname',lastname='$lname',username='$username',email='$email',address='$address',monthly_due='$monthly_due' where bio_id=$user"; if($con->query($sql)){ echo "updated"; } else{ echo "error"; } } function deleteUser($data,$con,$limit,$adjacent){ $user = $data['user']; $user = base64_decode($user); $sql = "delete from biodata where bio_id=$user"; if($con->query($sql)){ showData($data,$con,$limit,$adjacent); } else{ echo "error"; } } function pagination($limit,$adjacents,$rows,$page){ $pagination=''; if ($page == 0) $page = 1; //if no page var is given, default to 1. echo $prev = $page - 1; //previous page is page - 1 echo $next = $page + 1; //next page is page + 1 echo $lastpage = ceil($rows/$limit); if($lastpage > 1) { $pagination .= "<div class=\"pagination\">"; //previous button if ($page > 1) $pagination.= "<a class='page-numbers' href=\"?page=$prev\">previous</a>"; else{ //$pagination.= "<span class=\"disabled\">previous</span>"; } //pages if ($lastpage < 5 + ($adjacents * 2)) //not enough pages to bother breaking it up { for ($counter = 1; $counter <= $lastpage; $counter++) { if ($counter == $page) $pagination.= "<span class=\"current\">$counter</span>"; else $pagination.= "<a class='page-numbers' href=\"?page=$counter\">$counter</a>"; } } elseif($lastpage > 3 + ($adjacents * 2)) //enough pages to hide some { //close to beginning; only hide later pages if($page < 1 + ($adjacents * 2)) { for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++) { if ($counter == $page) $pagination.= "<span class=\"current\">$counter</span>"; else $pagination.= "<a class='page-numbers' href=\"?page=$counter\">$counter</a>"; } } //in middle; hide some front and some back elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) { for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++) { if ($counter == $page) $pagination.= "<span class=\"current\">$counter</span>"; else $pagination.= "<a class='page-numbers' href=\"?page=$counter\">$counter</a>"; } } //close to end; only hide early pages else { for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++) { if ($counter == $page) $pagination.= "<span class=\"current\">$counter</span>"; else $pagination.= "<a class='page-numbers' href=\"$?page=$counter\">$counter</a>"; } } } //next button if ($page < $counter - 1) $pagination.= "<a class='page-numbers' href=\"?page=$next\">next</a>"; else{ //$pagination.= "<span class=\"disabled\">next</span>"; } $pagination.= "</div>\n"; } return $pagination; } ?> b. index3.php (contains initial forms for adding user) <html> <head> <title>Account</title> <link rel="stylesheet" type="text/css" href="style.css" /> <script src="jquery-1.9.1.min.js" type="text/javascript"></script> <!-- jQuery easing plugin --> <script src="jquery.easing.min.js" type="text/javascript"></script> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" > $(document).ready(function() { $(".account").click(function() { var X=$(this).attr('id'); if(X==1) { $(".submenu").hide(); $(this).attr('id', '0'); } else { $(".submenu").show(); $(this).attr('id', '1'); } }); //Mouseup textarea false $(".submenu").mouseup(function() { return false }); $(".account").mouseup(function() { return false }); //Textarea without editing. $(document).mouseup(function() { $(".submenu").hide(); $(".account").attr('id', ''); }); }); </script> <style> body { background-color; font-family:arial; } div.dropdown { color: #555; margin: 3px -22px 0 0; width: 143px; position: relative; height: 17px; text-align:left; } div.submenu { background: #fff; position: absolute; top: -12px; left: -20px; z-index: 100; width: 135px; display: none; margin-left: 10px; padding: 40px 0 5px; border-radius: 6px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.45); } .dropdown li a { color: #555555; display: block; font-family: arial; font-weight: bold; padding: 6px 15px; cursor: pointer; text-decoration:none; } .dropdown li a:hover{ background:#155FB0; color: #FFFFFF; text-decoration: none; } a.account { font-size: 11px; line-height: 16px; color: #555; position: absolute; z-index: 110; display: block; padding: 11px 0 0 20px; height: 28px; width: 121px; margin: -11px 0 0 -10px; text-decoration: none; background: url(icons/arrow.png) 116px 17px no-repeat; cursor:pointer; } .root { list-style:none; margin:0px; padding:0px; font-size: 11px; padding: 11px 0 0 0px; border-top:1px solid #dedede; } </style> </head> <body> <div id="mhead"><h2>Accounts <span class="red">(SS)</span> </h2></div> <div id="container"> <div style='margin:50px'> <div class="dropdown"> <a class="account" > <span>My Account</span> </a> <div class="submenu" style="display: none; "> <ul class="root"> <li > <a href="#Dashboard" >Dashboard</a> </li> <li > <a href="#Profile" >View Members</a> </li> <li > <a href="#settings">Search for Members</a> </li> <li> <a href="#feedback">Add Essenk Purchase</a> </li> <li> <a href="#feedback">Approve Loan</a> </li> <li> <a href="#feedback">Add New Admin</a> </li> <li> <a href="#feedback">Edit Profile</a> </li> <li> <a href="#signout">Sign Out</a> </li> </ul> </div> </div> </div> <p id="msg"></p> <ul id='navigate'> <li class="navi_sec active"><a id="add_user">Add User</a></li> <li class="navi_sec"><a id='show_user'>All Users</a></li> </ul> <div id="add_user_sec" class="user_section"> <form name='signup' id='signup' method="post"> <div class='row'> <p><label for='username'>First name</label> <input type='text' name='firstname' id='firstname' value='' placeholder='Enter First name' /></p> </div> <div class='row'> <p><label for='lastname'>Last name</label> <input type='text' name='lastname' id='lastname' value='' placeholder='Enter Last name' /></p> </div> <div class='row'> <p><label for='username'>PFNO</label> <input type='text' name='username' id='username' value='' placeholder='Enter Username' /></p> </div> <div class='row'> <p><label for='username'>Password</label> <input type='password' name='password' id='password' value='' placeholder='Enter password' /></p> </div> <div class='row'> <p><label for='email'>Email</label> <input type='text' name='email' id='email' value='' placeholder='Enter Email' /></p> </div> <div class='row'> <p><label for='username'>Address</label> <textarea name="address" id="address" placeholder="Enter Address"></textarea></p> </div> <div class='row'> <p><label for='phone'>Phone</label> <input type='text' name='phone' id='phone' value='' placeholder='Phone' /></p> </div> <div class='row'> <p><label for='username'>Sex</label> <select name="sex"> <option value="Male">Male</option> <option value="Female">Female</option> </select> </p> </div> <div class='row'> <p><label for='monthly_due'>Monthly Due</label> <input type='text' name='monthly_due' id='monthly_due' value='' placeholder='Monthly_Due' /></p> </div> <div class='row'> <p><label for='next_ofkin'>Next of Kin</label> <input type='text' name='next_ofkin' id='next_ofkin' value='' placeholder='Monthly_Due' /></p> </div> <div class='row'> <p><label for='username'>Address of Kin</label> <input type='text' name='next_ofkin' id='next_ofkin' value='' placeholder='Next of Kkin' /> <textarea name="nextofkin_address" id="nextofkin_address" placeholder="Enter Address of Kin"></textarea></p> </div> <div class='row'> <p><label for='phone'>Next of Kin Phone</label> <input type='text' name='nextofkin_phone' id='nextofkin_phone' value='' placeholder='Next of Kin Phone' /></p> </div> <input type="hidden" name="datetime" value="datetime" /> <input type="hidden" name="date_ofdue" value="date_ofdue" /> <input type="hidden" name="actionfunction" value="saveData" /> <div class='row'> <input type='button' id='formsubmit' name="submit" class='submit' value='Submit' /> </div> </form> </div> <div id="show_user_sec" class="user_section"> <table id='userists' cellspacing="0"> </table> </div> <div id="update_user_sec" class="user_section"> </div> </div> <script type="text/javascript" src="script.js"></script> </body> </html> c. db2.php (default db for connection) <?php $limit = 1; $adjacent = 3; $con = mysqli_connect("localhost","root","","ldbs"); if(mysqli_connect_errno()){ echo "Database did not connect"; exit(); } ?> d. script.js (contains the javascript code for ajax and jquery frames) jQuery(document).ready(function(){ jQuery('.user_section').hide(); jQuery('#add_user_sec').show(); var left, opacity, scale; var animating; jQuery("#show_user").click(function(event){ jQuery(document).prop('title', 'Show Users'); jQuery("#msg").html(""); if(animating) return false; animating = true; var section = jQuery(".user_section"); var activesec; for($i=0;$i<section.length;$i++){ if(jQuery(section[$i]).css('display')=="block"){ activesec = section[$i]; break; } } if(jQuery(this).hasClass("active")){ return false; } jQuery(".navi_sec").removeClass("active"); jQuery(this).parent().addClass("active"); //show the next fieldset //hide the current fieldset with style jQuery(activesec).animate({opacity: 0}, { step: function(now, mx) { //as the opacity of current_fs reduces to 0 - stored in "now" //1. scale current_fs down to 80% scale = 1 - (1 - now) * 0.2; //2. bring next_fs from the right(50%) left = (now * 50)+"%"; //3. increase opacity of next_fs to 1 as it moves in opacity = 1 - now; jQuery(activesec).css({'transform': 'scale('+scale+')'}); jQuery("#show_user_sec").css({'left': left, 'opacity': opacity,'transform': 'none'}); }, duration: 800, complete: function(){ jQuery(activesec).hide(); jQuery("#show_user_sec").show(); animating = false; getusers(); }, //this comes from the custom easing plugin easing: 'easeInOutBack' }); jQuery('#userists').on('click','.ajaxedit',function(){ var edituser = jQuery(this).attr('user'); jQuery(document).prop('title', 'Edit User'); if(animating) return false; animating = true; jQuery(".navi_sec").removeClass("active"); //hide the current fieldset with style jQuery("#show_user_sec").animate({opacity: 0}, { step: function(now, mx) { //as the opacity of current_fs reduces to 0 - stored in "now" //1. scale current_fs down to 80% scale = 1 - (1 - now) * 0.2; //2. bring next_fs from the right(50%) left = (now * 50)+"%"; //3. increase opacity of next_fs to 1 as it moves in opacity = 1 - now; jQuery("#show_user_sec").css({'transform': 'scale('+scale+')'}); jQuery("#update_user_sec").css({'left': left, 'opacity': opacity,'transform': 'none'}); }, duration: 800, complete: function(){ jQuery("#show_user_sec").hide(); jQuery.ajax({ url:"DbManipute.php", type:"POST", data:"actionfunction=editUser&user="+edituser, cache: false, success: function(response){ jQuery('#update_user_sec').html(response); jQuery("#update_user_sec").show(); animating = false; } }); }, //this comes from the custom easing plugin easing: 'easeInOutBack' }); }); jQuery('#userists').on('click','.ajaxdelete',function(){ var user = jQuery(this).attr("user"); jQuery.ajax({ url:"DbManipute.php", type:"POST", data:"actionfunction=deleteUser&user="+user+"&page=1", cache: false, success: function(response){ jQuery('#userists').html(response); jQuery("#msg").html("user deleted"); } }); }); jQuery("#add_user").click(function(){ resetform(); jQuery(document).prop('title', 'Add User'); jQuery("#msg").html(""); if(animating) return false; animating = true; var activesec; for($i=0;$i<section.length;$i++){ if(jQuery(section[$i]).css('display')=="block"){ activesec = section[$i]; break; } } jQuery(".navi_sec").removeClass("active"); jQuery(this).parent().addClass("active"); jQuery(activesec).animate({opacity: 0}, { step: function(now, mx) { //as the opacity of current_fs reduces to 0 - stored in "now" //1. scale previous_fs from 80% to 100% scale = 0.8 + (1 - now) * 0.2; //2. take current_fs to the right(50%) - from 0% left = ((1-now) * 50)+"%"; //3. increase opacity of previous_fs to 1 as it moves in opacity = 1 - now; jQuery(activesec).css({'left': left}); jQuery("#add_user_sec").css({'transform': 'scale('+scale+')', 'opacity': opacity}); }, duration: 800, complete: function(){ jQuery(activesec).hide(); jQuery("#add_user_sec").show(); animating = false; }, //this comes from the custom easing plugin easing: 'easeInOutBack' }); }); jQuery('#update_user_sec').on('click','#updatesubmit',function(){ jQuery(".navi_sec a").removeClass("active"); var signupform = $("#update_user_sec").children("#signup"); var fname = jQuery(signupform).find("#firstname"); var lname = jQuery(signupform).find("#lastname"); var username = jQuery(signupform).find("#username"); var password = jQuery(signupform).find("#password"); var email = jQuery(signupform).find("#email"); var address = jQuery(signupform).find("#address"); var phone = jQuery(signupform).find("#phone"); var monthly_due = jQuery(signupform).find("#monthly_due"); if(validateform(fname,lname,username,password,email,address,phone,mothly_due)){ var formdata = signupform.serialize(); jQuery.ajax({ url:"DbManipute.php", type:"POST", data:formdata, cache: false, success: function(response){ if(response=='updated'){ jQuery("#show_user").trigger("click"); getusers(); jQuery("#msg").html("user Updated"); } } }); } }); jQuery('#userists').on('click','.page-numbers',function(){ jQuerypage = jQuery(this).attr('href'); jQuerypageind = jQuerypage.indexOf('page='); jQuerypage = jQuerypage.substring((jQuerypageind+5)); jQuery.ajax({ url:"DbManipute.php", type:"POST", data:"actionfunction=showData&page="+jQuerypage, cache: false, success: function(response){ jQuery('#userists').html(response); } }); return false; }); }); jQuery("#formsubmit").click(function(){ var fname = jQuery("#firstname"); var lname = jQuery("#lastname"); var username = jQuery("#username"); var lname = jQuery("#password"); var email = jQuery("#email"); var address = jQuery("#address"); var phone = jQuery("#phone"); var sex = jQuery("#sex"); var monthly_due = jQuery("#monthly_due"); var next_ofkin = jQuery("#next_ofkin"); var nextofkin_address = jQuery("#nextofkin_address"); var nextofkin_phone = jQuery("#nextofkin_phone"); var datetime = jQuery("#datetime"); var date_ofdue = jQuery("#date_ofdue"); if(validateform(fname,lname,username,lname,email,address,address,phone,sex,phone,sex,monthly_due,next_ofkin, nextofkin_address,nextofkin_phone,datetime,date_ofdue)){ var formdata = jQuery("#signup").serialize(); jQuery.ajax({ url:"DbManipute.php", type:"POST", data:formdata, cache: false, success: function(response){ if(response=='added'){ jQuery("#show_user").trigger("click"); getusers(); jQuery("#msg").html("user added"); } } }); } }); }); function getusers(){ jQuery.ajax({ url:"DbManipute.php", type:"POST", data:"actionfunction=showData&page=1", cache: false, success: function(response){ jQuery('#userists').html(response); } }); } function validateform(fname,lname,username,password,email,address,phone,sex, monthly_due,next_ofkin,nextofkin_address,phone,sex,monthly_due,nextofkin_address,nextofkin_phone, datetime,account_balance,date_ofdue){ var emailfilter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; if (fname.val()=='') { fname.addClass('hightlight'); return false; } else fname.removeClass('hightlight'); if (lname.val()=='') { lname.addClass('hightlight'); return false; } else lname.removeClass('hightlight'); if (username.val()=='') { username.addClass('hightlight'); return false; } else username.removeClass('hightlight'); if (password.val()=='') { password.addClass('hightlight'); return false; } else password.removeClass('hightlight'); if (password.val()=='') { password.addClass('hightlight'); return false; }else if(!emailfilter.test(email.val())){ alert("not a valid email id"); email.addClass('hightlight'); return false; }else address.removeClass('hightlight'); if (address.val()=='') { address.addClass('hightlight'); return false; } else address.removeClass('hightlight'); if (phone.val()=='') { phone.addClass('hightlight'); return false; } else phone.removeClass('hightlight'); if (sex.val()=='') { sex.addClass('hightlight'); return false; } else sex.removeClass('hightlight'); if (monthly_due.val()=='') { monthly_due.addClass('hightlight'); return false; } else monthly_due.removeClass('hightlight'); if (next_ofkin.val()=='') { next_ofkin.addClass('hightlight'); return false; } else next_ofkin.removeClass('hightlight'); if (nextofkin_address.val()=='') { nextofkin_address.addClass('hightlight'); return false; } else nextofkin_phone.removeClass('hightlight'); if (nextofkin_phone.val()=='') { nextofkin_phone.addClass('hightlight'); return false; } else nextofkin_phone.removeClass('hightlight'); if (account_balance.val()=='') { account_balance.addClass('hightlight'); return false; } else account_balance.removeClass('hightlight'); return true; } function resetform(){ var fname = jQuery("#firstname"); var lname = jQuery("#lastname"); var username = jQuery("#username"); var lname = jQuery("#password"); var email = jQuery("#email"); var address = jQuery("#address"); var phone = jQuery("#phone"); var sex = jQuery("#sex"); var monthly_due = jQuery("#monthly_due"); var next_ofkin = jQuery("#next_ofkin"); var nextofkin_address = jQuery("#nextofkin_address"); var nextofkin_phone = jQuery("#nextofkin_phone"); var account_balance = jQuery("#account_balance"); var datetime = jQuery("#datetime"); var date_ofdue = jQuery("#date_ofdue"); fname.val(""); lname.val(""); email.val(""); address.val(""); phone.val(""); sex.val(""); monthly_due.val(""); next_ofkin.val(""); nextofkin_address.val(""); nextofkin_phone.val(""); account_balance.val(""); datetime.val(""); ndate_ofdue.val(""); fname.removeClass("hightlight"); lname.removeClass("hightlight"); email.removeClass("hightlight"); address.removeClass("hightlight"); phone.removeClass("hightlight"); sex.removeClass("hightlight"); monthly_due.removeClass("hightlight"); next_ofkin.removeClass("hightlight"); nextofkin_address.removeClass("hightlight"); nextofkin_phone.removeClass("hightlight"); account_balance.removeClass("hightlight"); datetime.removeClass("hightlight"); ndate_ofdue.removeClass("hightlight"); } Please I need to know why the submit button is not executing insert, update and delete with the script.js
  6. Thanks guys Jacq and .taz, I really appreciate your thoughts and comments and will sure do.
  7. Gooday Coders. Im using php 5.4 with xampp 1.8. Each time I run this script "add+stock.php", the script jumps to line 240 saying header is already defined. Thus referring to the session headers. What can I do to get rid of these header errors? add_stock.php <?php include_once("init.php"); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>NIC - Add Stock Category</title> <!-- Stylesheets --> <link href='http://fonts.googleapis.com/css?family=Droid+Sans:400,700' rel='stylesheet'> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="js/date_pic/date_input.css"> <link rel="stylesheet" href="lib/auto/css/jquery.autocomplete.css"> <!-- Optimize for mobile devices --> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <!-- jQuery & JS files --> <?php include_once("tpl/common_js.php"); ?> <script src="js/script.js"></script> <script src="js/date_pic/jquery.date_input.js"></script> <script src="lib/auto/js/jquery.autocomplete.js "></script> <script> /*$.validator.setDefaults({ submitHandler: function() { alert("submitted!"); } });*/ $(document).ready(function() { $("#supplier").autocomplete("supplier1.php", { width: 160, autoFill: true, selectFirst: true }); $("#category").autocomplete("category.php", { width: 160, autoFill: true, selectFirst: true }); // validate signup form on keyup and submit $("#form1").validate({ rules: { name: { required: true, minlength: 3, maxlength: 200 }, stockid: { required: true, minlength: 3, maxlength: 200 }, cost: { required: true, }, sell: { required: true, } }, messages: { name: { required: "Please Enter Stock Name", minlength: "Category Name must consist of at least 3 characters" }, stockid: { required: "Please Enter Stock ID", minlength: "Category Name must consist of at least 3 characters" }, sell: { required: "Please Enter Selling Price", minlength: "Category Name must consist of at least 3 characters" }, cost: { required: "Please Enter Cost Price", minlength: "Category Name must consist of at least 3 characters" } } }); }); function numbersonly(e){ var unicode=e.charCode? e.charCode : e.keyCode if (unicode!=8 && unicode!=46 && unicode!=37 && unicode!=38 && unicode!=39 && unicode!=40 && unicode!=9){ //if the key isn't the backspace key (which we should allow) if (unicode<48||unicode>57) return false } } </script> </script> </head> <body> <!-- TOP BAR --> <?php include_once("tpl/top_bar.php"); ?> <!-- end top-bar --> <!-- HEADER --> <div id="header-with-tabs"> <div class="page-full-width cf"> <ul id="tabs" class="fl"> <li><a href="dashboard.php" class="dashboard-tab">Dashboard</a></li> <li><a href="view_sales.php" class="sales-tab">Sales</a></li> <li><a href="view_customers.php" class=" customers-tab">Customers</a></li> <li><a href="view_purchase.php" class="purchase-tab">Purchase</a></li> <li><a href="view_supplier.php" class=" supplier-tab">Supplier</a></li> <li><a href="view_product.php" class="active-tab stock-tab">Stocks / Products</a></li> <li><a href="view_payments.php" class="payment-tab">Payments / Outstandings</a></li> <li><a href="view_report.php" class="report-tab">Reports</a></li> </ul> <!-- end tabs --> <!-- Change this image to your own company's logo --> <!-- The logo will automatically be resized to 30px height. --> <a href="#" id="company-branding-small" class="fr"><img src="<?php if(isset($_SESSION['logo'])) { echo "upload/".$_SESSION['logo'];}else{ echo "upload/NIC.png"; } ?>" alt="Point of Sale" /></a> </div> <!-- end full-width --> </div> <!-- end header --> <!-- MAIN CONTENT --> <div id="content"> <div class="page-full-width cf"> <div class="side-menu fl"> <h3>Stock Management</h3> <ul> <li><a href="add_stock.php">Add Stock/Product</a></li> <li><a href="view_product.php">View Stock/Product</a></li> <li><a href="add_category.php">Add Stock Category</a></li> <li><a href="view_category.php">view Stock Category</a></li> <li><a href="view_stock_availability.php">view Stock Available</a></li> </ul> </div> <!-- end side-menu --> <div class="side-content fr"> <div class="content-module"> <div class="content-module-heading cf"> <h3 class="fl">Add Stock </h3> <span class="fr expand-collapse-text">Click to collapse</span> <div style="margin-top: 15px;margin-left: 150px"></div> <span class="fr expand-collapse-text initial-expand">Click to expand</span> </div> <!-- end content-module-heading --> <div class="content-module-main cf"> <?php //Gump is libarary for Validatoin if(isset($_POST['name'])){ $_POST = $gump->sanitize($_POST); $gump->validation_rules(array( 'name' => 'required|max_len,100|min_len,3', 'stockid' => 'required|max_len,200', 'sell' => 'required|max_len,200', 'cost' => 'required|max_len,200', 'supplier' => 'max_len,200', 'category' => 'max_len,200' )); $gump->filter_rules(array( 'name' => 'trim|sanitize_string|mysql_escape', 'stockid' => 'trim|sanitize_string|mysql_escape', 'sell' => 'trim|sanitize_string|mysql_escape', 'cost' => 'trim|sanitize_string|mysql_escape', 'category' => 'trim|sanitize_string|mysql_escape', 'supplier' => 'trim|sanitize_string|mysql_escape' )); $validated_data = $gump->run($_POST); $name = ""; $stockid = ""; $sell = ""; $cost = ""; $supplier = ""; $category = ""; if($validated_data === false) { echo $gump->get_readable_errors(true); } else { $name=mysql_real_escape_string($_POST['name']); $stockid=mysql_real_escape_string($_POST['stockid']); $sell=mysql_real_escape_string($_POST['sell']); $cost=mysql_real_escape_string($_POST['cost']); $supplier=mysql_real_escape_string($_POST['supplier']); $category=mysql_real_escape_string($_POST['category']); $count = $db->countOf("stock_details", "stock_name ='$name'"); if($count>1) { $data='Dublicat Entry. Please Verify'; $msg='<p style=color:red;font-family:gfont-family:Georgia, Times New Roman, Times, serif>'.$data.'</p>';// ?> <script src="dist/js/jquery.ui.draggable.js"></script> <script src="dist/js/jquery.alerts.js"></script> <script src="dist/js/jquery.js"></script> <link rel="stylesheet" href="dist/js/jquery.alerts.css" > <script type="text/javascript"> jAlert('<?php echo $msg; ?>', 'NIC'); </script> <?php } else { if($db->query("insert into stock_details(stock_id,stock_name,stock_quatity,supplier_id,company_price,selling_price,category) values('$stockid','$name',0,'$supplier',$cost,$sell,'$category')")) { $db->query("insert into stock_avail(name,quantity) values('$name',0)"); $msg=" $name Stock Details Added" ; header("Location: add_stock.php?msg=$msg"); }else echo "<br><font color=red size=+1 >Problem in Adding !</font>" ; } } } if(isset($_GET['msg'])){ $data=$_GET['msg']; $msg='<p style=color:#153450;font-family:gfont-family:Georgia, Times New Roman, Times, serif>'.$data.'</p>';// ?> <script src="dist/js/jquery.ui.draggable.js"></script> <script src="dist/js/jquery.alerts.js"></script> <script src="dist/js/jquery.js"></script> <link rel="stylesheet" href="dist/js/jquery.alerts.css" > <script type="text/javascript"> jAlert('<?php echo $msg; ?>', 'NIC'); </script> <?php } ?> <form name="form1" method="post" id="form1" action=""> <table class="form" border="0" cellspacing="0" cellpadding="0"> <tr> <?php $max = $db->maxOfAll("id", "stock_details"); $max=$max+1; $autoid="SD".$max.""; ?> <td><span class="man">*</span>Stock ID:</td> <td><input name="stockid" type="text" id="stockid" readonly maxlength="200" class="round default-width-input" value="<?php echo $autoid; ?>" /></td> <td><span class="man">*</span>Name:</td> <td><input name="name"placeholder="ENTER CATEGORY NAME" type="text" id="name" maxlength="200" class="round default-width-input" value="<?php echo $name; ?>" /></td> </tr> <tr> <td><span class="man">*</span>Cost:</td> <td><input name="cost" placeholder="ENTER COST PRICE" type="text" id="cost" maxlength="200" class="round default-width-input" onkeypress="return numbersonly(event)" value="<?php echo $cost; ?>" /></td> <td><span class="man">*</span>Sell:</td> <td><input name="sell" placeholder="ENTER SELLING PRICE" type="text" id="sell" maxlength="200" class="round default-width-input" onkeypress="return numbersonly(event)" value="<?php echo $sell; ?>" /></td> </tr> <tr> <td>Supplier:</td> <td><input name="supplier" placeholder="ENTER SUPPLIER NAME" type="text" id="supplier" maxlength="200" class="round default-width-input" value="<?php echo $supplier; ?>" /></td> <td>Category:</td> <td><input name="category" placeholder="ENTER CATEGORY NAME" type="text" id="category" maxlength="200" class="round default-width-input" value="<?php echo $category; ?>" /></td> </tr> <tr> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> <input class="button round blue image-right ic-add text-upper" type="submit" name="Submit" value="Add"> (Control + S) <td align="right"><input class="button round red text-upper" type="reset" name="Reset" value="Reset"> </td> </tr> </table> </form> </div> <!-- end content-module-main --> </div> <!-- end content-module --> </div> <!-- end full-width --> </div> <!-- end content --> <!-- FOOTER --> <div id="footer"> <p>Any Queries email to <a href="mailto:sridhar.NIC@gmail.com?subject=Stock%20Management%20System">sridhar.NIC@gmail.com</a>.</p> </div> <!-- end footer --> </body> </html>
  8. Im working with php 5.1.6. With xampp 1.5.14. Im also working on a stock application. If I want to say add stock product (add_stock.php) this error is generated on screen. It seems to refer to a function in ump.class.php Here we go, ump.class.php <?php /** * GUMP - A fast, extensible PHP input validation class * * @author Sean Nieuwoudt (http://twitter.com/SeanNieuwoudt) * @copyright Copyright (c) 2011 Wixel.net * @link http://github.com/Wixel/GUMP * @version 1.0 */ class GUMP { // Validation rules for execution protected $validation_rules = array(); // Filter rules for execution protected $filter_rules = array(); // Instance attribute containing errors from last run protected $errors = array(); // ** ------------------------- Validation Data ------------------------------- ** // public static $basic_tags = "<br><p><a><strong><b><i><em><img><blockquote><code><dd><dl><hr><h1><h2><h3><h4><h5><h6><label><ul><li><span><sub><sup>"; public static $en_noise_words = "about,after,all,also,an,and,another,any,are,as,at,be,because,been,before, being,between,both,but,by,came,can,come,could,did,do,each,for,from,get, got,has,had,he,have,her,here,him,himself,his,how,if,in,into,is,it,its,it's,like, make,many,me,might,more,most,much,must,my,never,now,of,on,only,or,other, our,out,over,said,same,see,should,since,some,still,such,take,than,that, the,their,them,then,there,these,they,this,those,through,to,too,under,up, very,was,way,we,well,were,what,where,which,while,who,with,would,you,your,a, b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,$,1,2,3,4,5,6,7,8,9,0,_"; // ** ------------------------- Validation Helpers ---------------------------- ** // /** * Shorthand method for inline validation * * @param array $data The data to be validated * @param array $validators The GUMP validators * @return mixed True(boolean) or the array of error messages */ public static function is_valid(array $data, array $validators) { $gump = new Gump(); $gump->validation_rules($validators); if($gump->run($data) === false) { return $gump->get_readable_errors(false); } else { return true; } } /** * Magic method to generate the validation error messages * * @return string */ public function __toString() { return $this->get_readable_errors(true); } /** * Perform XSS clean to prevent cross site scripting * * @static * @access public * @param array $data * @return array */ public static function xss_clean(array $data) { foreach($data as $k => $v) { $data[$k] = filter_var($v, FILTER_SANITIZE_STRING); } return $data; } /** * Getter/Setter for the validation rules * * @param array $rules * @return array */ public function validation_rules(array $rules = array()) { if(!empty($rules)) { $this->validation_rules = $rules; } else { return $this->validation_rules; } } /** * Getter/Setter for the filter rules * * @param array $rules * @return array */ public function filter_rules(array $rules = array()) { if(!empty($rules)) { $this->filter_rules = $rules; } else { return $this->filter_rules; } } /** * Run the filtering and validation after each other * * @param array $data * @return array * @return boolean */ public function run(array $data) { $data = $this->filter($data, $this->filter_rules()); $validated = $this->validate( $data, $this->validation_rules() ); if($validated !== true) { return false; } else { return $data; } } /** * Sanitize the input data * * @access public * @param array $data * @return array */ public function sanitize(array $input, $fields = NULL, $utf8_encode = true) { $magic_quotes = (bool)get_magic_quotes_gpc(); if(is_null($fields)) { $fields = array_keys($input); } foreach($fields as $field) { if(!isset($input[$field])) { continue; } else { $value = $input[$field]; if(is_string($value)) { if($magic_quotes === TRUE) { $value = stripslashes($value); } if(strpos($value, "\r") !== FALSE) { $value = trim($value); } if(function_exists('iconv') && function_exists('mb_detect_encoding') && $utf8_encode) { $current_encoding = mb_detect_encoding($value); if($current_encoding != 'UTF-8' && $current_encoding != 'UTF-16') { $value = iconv($current_encoding, 'UTF-8', $value); } } $value = filter_var($value, FILTER_SANITIZE_STRING); } $input[$field] = $value; } } return $input; } /** * Return the error array from the last validation run * * @return array */ public function errors() { return $this->errors; } /** * Perform data validation against the provided ruleset * * @access public * @param mixed $input * @param array $ruleset * @return mixed */ public function validate(array $input, array $ruleset) { $this->errors = array(); foreach($ruleset as $field => $rules) { #if(!array_key_exists($field, $input)) #{ # continue; #} $rules = explode('|', $rules); foreach($rules as $rule) { $method = NULL; $param = NULL; if(strstr($rule, ',') !== FALSE) // has params { $rule = explode(',', $rule); $method = 'validate_'.$rule[0]; $param = $rule[1]; } else { $method = 'validate_'.$rule; } if(is_callable(array($this, $method))) { $result = $this->$method($field, $input, $param); if(is_array($result)) // Validation Failed { $this->errors[] = $result; } } else { throw new Exception("Validator method '$method' does not exist."); } } } return (count($this->errors) > 0)? $this->errors : TRUE; } /** * Process the validation errors and return human readable error messages * * @param bool $convert_to_string = false * @param string $field_class * @param string $error_class * @return array * @return string */ public function get_readable_errors($convert_to_string = false, $field_class="field", $error_class="error-message") { if(empty($this->errors)) { return ($convert_to_string)? null : array(); } $resp = array(); foreach($this->errors as $e) { $field = ucwords(str_replace(array('_','-'), chr(32), $e['field'])); $param = $e['param']; switch($e['rule']) { case 'validate_required': $resp[] = "The <span class=\"$field_class\">$field</span> field is required"; break; case 'validate_valid_email': $resp[] = "The <span class=\"$field_class\">$field</span> field is required to be a valid email address"; break; case 'validate_max_len': if($param == 1) { $resp[] = "The <span class=\"$field_class\">$field</span> field needs to be shorter than $param character"; } else { $resp[] = "The <span class=\"$field_class\">$field</span> field needs to be shorter than $param characters"; } break; case 'validate_min_len': if($param == 1) { $resp[] = "The <span class=\"$field_class\">$field</span> field needs to be longer than $param character"; } else { $resp[] = "The <span class=\"$field_class\">$field</span> field needs to be longer than $param characters"; } break; case 'validate_exact_len': if($param == 1) { $resp[] = "The <span class=\"$field_class\">$field</span> field needs to be exactly $param character in length"; } else { $resp[] = "The <span class=\"$field_class\">$field</span> field needs to be exactly $param characters in length"; } break; case 'validate_alpha': $resp[] = "The <span class=\"$field_class\">$field</span> field may only contain alpha characters(a-z)"; break; case 'validate_alpha_numeric': $resp[] = "The <span class=\"$field_class\">$field</span> field may only contain alpha-numeric characters"; break; case 'validate_alpha_dash': $resp[] = "The <span class=\"$field_class\">$field</span> field may only contain alpha characters & dashes"; break; case 'validate_numeric': $resp[] = "The <span class=\"$field_class\">$field</span> field may only contain numeric characters"; break; case 'validate_integer': $resp[] = "The <span class=\"$field_class\">$field</span> field may only contain a numeric value"; break; case 'validate_boolean': $resp[] = "The <span class=\"$field_class\">$field</span> field may only contain a true or false value"; break; case 'validate_float': $resp[] = "The <span class=\"$field_class\">$field</span> field may only contain a float value"; break; case 'validate_valid_url': $resp[] = "The <span class=\"$field_class\">$field</span> field is required to be a valid URL"; break; case 'validate_url_exists': $resp[] = "The <span class=\"$field_class\">$field</span> URL does not exist"; break; case 'validate_valid_ip': $resp[] = "The <span class=\"$field_class\">$field</span> field needs to contain a valid IP address"; break; case 'validate_valid_cc': $resp[] = "The <span class=\"$field_class\">$field</span> field needs to contain a valid credit card number"; break; case 'validate_valid_name': $resp[] = "The <span class=\"$field_class\">$field</span> field needs to contain a valid human name"; break; case 'validate_contains': $resp[] = "The <span class=\"$field_class\">$field</span> field needs contain one of these values: ".implode(', ', $param); break; case 'validate_street_address': $resp[] = "The <span class=\"$field_class\">$field</span> field needs to be a valid street address"; break; } } if(!$convert_to_string) { return $resp; } else { $buffer = ''; foreach($resp as $s) { $buffer .= "<span class=\"$error_class\">$s</span>"; } return $buffer; } } /** * Filter the input data according to the specified filter set * * @access public * @param mixed $input * @param array $filterset * @return mixed */ public function filter(array $input, array $filterset) { foreach($filterset as $field => $filters) { if(!array_key_exists($field, $input)) { continue; } $filters = explode('|', $filters); foreach($filters as $filter) { $params = NULL; if(strstr($filter, ',') !== FALSE) { $filter = explode(',', $filter); $params = array_slice($filter, 1, count($filter) - 1); $filter = $filter[0]; } if(is_callable(array($this, 'filter_'.$filter))) { $method = 'filter_'.$filter; $input[$field] = $this->$method($input[$field], $params); } else if(function_exists($filter)) { $input[$field] = $filter($input[$field]); } else { throw new Exception("Filter method '$filter' does not exist."); } } } return $input; } // ** ------------------------- Filters --------------------------------------- ** // /** * Replace noise words in a string (http://tax.cchgroup.com/help/Avoiding_noise_words_in_your_search.htm) * * Usage: '<index>' => 'noise_words' * * @access protected * @param string $value * @param array $params * @return string */ protected function filter_noise_words($value, $params = NULL) { $value = preg_replace('/\s\s+/u', chr(32),$value); $value = " $value "; $words = explode(',', self::$en_noise_words); foreach($words as $word) { $word = trim($word); $word = " $word "; // Normalize if(stripos($value, $word) !== FALSE) { $value = str_ireplace($word, chr(32), $value); } } return trim($value); } /** * Remove all known punctuation from a string * * Usage: '<index>' => 'rmpunctuataion' * * @access protected * @param string $value * @param array $params * @return string */ protected function filter_rmpunctuation($value, $params = NULL) { return preg_replace("/(?![.=$'€%-])\p{P}/u", '', $value); } /** * Translate an input string to a desired language [DEPRECIATED] * * Any ISO 639-1 2 character language code may be used * * See: http://www.science.co.il/language/Codes.asp?s=code2 * * @access protected * @param string $value * @param array $params * @return string */ /* protected function filter_translate($value, $params = NULL) { $input_lang = 'en'; $output_lang = 'en'; if(is_null($params)) { return $value; } switch(count($params)) { case 1: $input_lang = $params[0]; break; case 2: $input_lang = $params[0]; $output_lang = $params[1]; break; } $text = urlencode($value); $translation = file_get_contents( "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q={$text}&langpair={$input_lang}|{$output_lang}" ); $json = json_decode($translation, true); if($json['responseStatus'] != 200) { return $value; } else { return $json['responseData']['translatedText']; } } */ /** * Sanitize the string by removing any script tags * * Usage: '<index>' => 'sanitize_string' * * @access protected * @param string $value * @param array $params * @return string */ protected function filter_sanitize_string($value, $params = NULL) { return filter_var($value, FILTER_SANITIZE_STRING); } /** * Sanitize the string by urlencoding characters * * Usage: '<index>' => 'urlencode' * * @access protected * @param string $value * @param array $params * @return string */ protected function filter_urlencode($value, $params = NULL) { return filter_var($value, FILTER_SANITIZE_ENCODED); } /** * Sanitize the string by converting HTML characters to their HTML entities * * Usage: '<index>' => 'htmlencode' * * @access protected * @param string $value * @param array $params * @return string */ protected function filter_htmlencode($value, $params = NULL) { return filter_var($value, FILTER_SANITIZE_SPECIAL_CHARS); } /** * Sanitize the string by removing illegal characters from emails * * Usage: '<index>' => 'sanitize_email' * * @access protected * @param string $value * @param array $params * @return string */ protected function filter_sanitize_email($value, $params = NULL) { return filter_var($value, FILTER_SANITIZE_EMAIL); } /** * Sanitize the string by removing illegal characters from numbers * * @access protected * @param string $value * @param array $params * @return string */ protected function filter_sanitize_numbers($value, $params = NULL) { return filter_var($value, FILTER_SANITIZE_NUMBER_INT); } /** * Filter out all HTML tags except the defined basic tags * * @access protected * @param string $value * @param array $params * @return string */ protected function filter_basic_tags($value, $params = NULL) { return strip_tags($value, self::$basic_tags); } /** * Filter out all SQL Valnurablities * * @access protected * @param string $value * @param array $params * @return string */ protected function filter_mysql_escape($value, $params = NULL) { return mysql_real_escape_string($value); } // ** ------------------------- Validators ------------------------------------ ** // /** * Verify that a value is contained within the pre-defined value set * * Usage: '<index>' => 'contains,value value value' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_contains($field, $input, $param = NULL) { $param = trim(strtolower($param)); $value = trim(strtolower($input[$field])); if (preg_match_all('#\'(.+?)\'#', $param, $matches, PREG_PATTERN_ORDER)) { $param = $matches[1]; } else { $param = explode(chr(32), $param); } if(in_array($value, $param)) { // valid, return nothing return; } else { return array( 'field' => $field, 'value' => $value, 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Check if the specified key is present and not empty * * Usage: '<index>' => 'required' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_required($field, $input, $param = NULL) { if(isset($input[$field]) && trim($input[$field]) != '') { return; } else { return array( 'field' => $field, 'value' => NULL, 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the provided email is valid * * Usage: '<index>' => 'valid_email' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_valid_email($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } if(!filter_var($input[$field], FILTER_VALIDATE_EMAIL)) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the provided value length is less or equal to a specific value * * Usage: '<index>' => 'max_len,240' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_max_len($field, $input, $param = NULL) { if(!isset($input[$field])) { return; } if(function_exists('mb_strlen')) { if(mb_strlen($input[$field]) <= (int)$param) { return; } } else { if(strlen($input[$field]) <= (int)$param) { return; } } return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } /** * Determine if the provided value length is more or equal to a specific value * * Usage: '<index>' => 'min_len,4' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_min_len($field, $input, $param = NULL) { if(!isset($input[$field])) { return; } if(function_exists('mb_strlen')) { if(mb_strlen($input[$field]) >= (int)$param) { return; } } else { if(strlen($input[$field]) >= (int)$param) { return; } } return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } /** * Determine if the provided value length matches a specific value * * Usage: '<index>' => 'exact_len,5' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_exact_len($field, $input, $param = NULL) { if(!isset($input[$field])) { return; } if(function_exists('mb_strlen')) { if(mb_strlen($input[$field]) == (int)$param) { return; } } else { if(strlen($input[$field]) == (int)$param) { return; } } return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } /** * Determine if the provided value contains only alpha characters * * Usage: '<index>' => 'alpha' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_alpha($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } if(!preg_match("/^([a-zÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ])+$/i", $input[$field]) !== FALSE) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the provided value contains only alpha-numeric characters * * Usage: '<index>' => 'alpha_numeric' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_alpha_numeric($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } if(!preg_match("/^([a-z0-9ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ])+$/i", $input[$field]) !== FALSE) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the provided value contains only alpha characters with dashed and underscores * * Usage: '<index>' => 'alpha_dash' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_alpha_dash($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } if(!preg_match("/^([a-z0-9ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ_-])+$/i", $input[$field]) !== FALSE) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the provided value is a valid number or numeric string * * Usage: '<index>' => 'numeric' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_numeric($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } if(!is_numeric($input[$field])) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the provided value is a valid integer * * Usage: '<index>' => 'integer' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_integer($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } if(!filter_var($input[$field], FILTER_VALIDATE_INT)) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the provided value is a PHP accepted boolean * * Usage: '<index>' => 'boolean' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_boolean($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } $bool = filter_var($input[$field], FILTER_VALIDATE_BOOLEAN); if(!is_bool($bool)) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the provided value is a valid float * * Usage: '<index>' => 'float' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_float($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } if(!filter_var($input[$field], FILTER_VALIDATE_FLOAT)) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the provided value is a valid URL * * Usage: '<index>' => 'valid_url' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_valid_url($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } if(!filter_var($input[$field], FILTER_VALIDATE_URL)) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if a URL exists & is accessible * * Usage: '<index>' => 'url_exists' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_url_exists($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } $url = str_replace( array('http://', 'https://', 'ftp://'), '', strtolower($input[$field]) ); if(function_exists('checkdnsrr')) { if(!checkdnsrr($url)) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } else { if(gethostbyname($url) == $url) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } } /** * Determine if the provided value is a valid IP address * * Usage: '<index>' => 'valid_ip' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_valid_ip($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } if(!filter_var($input[$field], FILTER_VALIDATE_IP) !== FALSE) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the provided value is a valid IPv4 address * * Usage: '<index>' => 'valid_ipv4' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_valid_ipv4($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } if(!filter_var($input[$field], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== FALSE) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the provided value is a valid IPv6 address * * Usage: '<index>' => 'valid_ipv6' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_valid_ipv6($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } if(!filter_var($input[$field], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== FALSE) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the input is a valid credit card number * * See: http://stackoverflow.com/questions/174730/what-is-the-best-way-to-validate-a-credit-card-in-php * Usage: '<index>' => 'valid_cc' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_valid_cc($field, $input, $param = NULL) { if(!isset($input[$field]) || empty($input[$field])) { return; } $number = preg_replace('/\D/', '', $input[$field]); if(function_exists('mb_strlen')) { $number_length = mb_strlen($input[$field]); } else { $number_length = strlen($input[$field]); } $parity = $number_length % 2; $total = 0; for($i = 0; $i < $number_length; $i++) { $digit = $number[$i]; if ($i % 2 == $parity) { $digit *= 2; if ($digit > 9) { $digit -= 9; } } $total += $digit; } if($total % 10 == 0) { return; // Valid } else { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the input is a valid human name [Credits to http://github.com/ben-s] * * See: https://github.com/Wixel/GUMP/issues/5 * Usage: '<index>' => 'valid_name' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_valid_name($field, $input, $param = NULL) { if(!isset($input[$field])|| empty($input[$field])) { return; } if(!preg_match("/^([a-zÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïñðòóôõöùúûüýÿ '-])+$/i", $input[$field]) !== FALSE) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } /** * Determine if the provided input is likely to be a street address using weak detection * * Usage: '<index>' => 'street_address' * * @access protected * @param string $field * @param array $input * @return mixed */ protected function validate_street_address($field, $input, $param = NULL) { if(!isset($input[$field])|| empty($input[$field])) { return; } // Theory: 1 number, 1 or more spaces, 1 or more words $hasLetter = preg_match('/[a-zA-Z]/', $input[$field]); $hasDigit = preg_match('/\d/' , $input[$field]); $hasSpace = preg_match('/\s/' , $input[$field]); $passes = $hasLetter && $hasDigit && $hasSpace; if(!$passes) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } } // EOC Here is add_stock.php <?php include_once("init.php"); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>POSNIC - Add Stock Category</title> <!-- Stylesheets --> <link href='http://fonts.googleapis.com/css?family=Droid+Sans:400,700' rel='stylesheet'> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="js/date_pic/date_input.css"> <link rel="stylesheet" href="lib/auto/css/jquery.autocomplete.css"> <!-- Optimize for mobile devices --> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <!-- jQuery & JS files --> <?php include_once("tpl/common_js.php"); ?> <script src="js/script.js"></script> <script src="js/date_pic/jquery.date_input.js"></script> <script src="lib/auto/js/jquery.autocomplete.js "></script> <script> /*$.validator.setDefaults({ submitHandler: function() { alert("submitted!"); } });*/ $(document).ready(function() { $("#supplier").autocomplete("supplier1.php", { width: 160, autoFill: true, selectFirst: true }); $("#category").autocomplete("category.php", { width: 160, autoFill: true, selectFirst: true }); // validate signup form on keyup and submit $("#form1").validate({ rules: { name: { required: true, minlength: 3, maxlength: 200 }, stockid: { required: true, minlength: 3, maxlength: 200 }, cost: { required: true, }, sell: { required: true, } }, messages: { name: { required: "Please Enter Stock Name", minlength: "Category Name must consist of at least 3 characters" }, stockid: { required: "Please Enter Stock ID", minlength: "Category Name must consist of at least 3 characters" }, sell: { required: "Please Enter Selling Price", minlength: "Category Name must consist of at least 3 characters" }, cost: { required: "Please Enter Cost Price", minlength: "Category Name must consist of at least 3 characters" } } }); }); function numbersonly(e){ var unicode=e.charCode? e.charCode : e.keyCode if (unicode!=8 && unicode!=46 && unicode!=37 && unicode!=38 && unicode!=39 && unicode!=40 && unicode!=9){ //if the key isn't the backspace key (which we should allow) if (unicode<48||unicode>57) return false } } </script> </script> </head> <body> <!-- TOP BAR --> <?php include_once("tpl/top_bar.php"); ?> <!-- end top-bar --> <!-- HEADER --> <div id="header-with-tabs"> <div class="page-full-width cf"> <ul id="tabs" class="fl"> <li><a href="dashboard.php" class="dashboard-tab">Dashboard</a></li> <li><a href="view_sales.php" class="sales-tab">Sales</a></li> <li><a href="view_customers.php" class=" customers-tab">Customers</a></li> <li><a href="view_purchase.php" class="purchase-tab">Purchase</a></li> <li><a href="view_supplier.php" class=" supplier-tab">Supplier</a></li> <li><a href="view_product.php" class="active-tab stock-tab">Stocks / Products</a></li> <li><a href="view_payments.php" class="payment-tab">Payments / Outstandings</a></li> <li><a href="view_report.php" class="report-tab">Reports</a></li> </ul> <!-- end tabs --> <!-- Change this image to your own company's logo --> <!-- The logo will automatically be resized to 30px height. --> <a href="#" id="company-branding-small" class="fr"><img src="<?php if(isset($_SESSION['logo'])) { echo "upload/".$_SESSION['logo'];}else{ echo "upload/posnic.png"; } ?>" alt="Point of Sale" /></a> </div> <!-- end full-width --> </div> <!-- end header --> <!-- MAIN CONTENT --> <div id="content"> <div class="page-full-width cf"> <div class="side-menu fl"> <h3>Stock Management</h3> <ul> <li><a href="add_stock.php">Add Stock/Product</a></li> <li><a href="view_product.php">View Stock/Product</a></li> <li><a href="add_category.php">Add Stock Category</a></li> <li><a href="view_category.php">view Stock Category</a></li> <li><a href="view_stock_availability.php">view Stock Available</a></li> </ul> </div> <!-- end side-menu --> <div class="side-content fr"> <div class="content-module"> <div class="content-module-heading cf"> <h3 class="fl">Add Stock </h3> <span class="fr expand-collapse-text">Click to collapse</span> <div style="margin-top: 15px;margin-left: 150px"></div> <span class="fr expand-collapse-text initial-expand">Click to expand</span> </div> <!-- end content-module-heading --> <div class="content-module-main cf"> <?php //Gump is libarary for Validatoin if(isset($_POST['name'])){ $_POST = $gump->sanitize($_POST); $gump->validation_rules(array( 'name' => 'required|max_len,100|min_len,3', 'stockid' => 'required|max_len,200', 'sell' => 'required|max_len,200', 'cost' => 'required|max_len,200', 'supplier' => 'max_len,200', 'category' => 'max_len,200' )); $gump->filter_rules(array( 'name' => 'trim|sanitize_string|mysql_escape', 'stockid' => 'trim|sanitize_string|mysql_escape', 'sell' => 'trim|sanitize_string|mysql_escape', 'cost' => 'trim|sanitize_string|mysql_escape', 'category' => 'trim|sanitize_string|mysql_escape', 'supplier' => 'trim|sanitize_string|mysql_escape' )); $validated_data = $gump->run($_POST); $name = ""; $stockid = ""; $sell = ""; $cost = ""; $supplier = ""; $category = ""; if($validated_data === false) { echo $gump->get_readable_errors(true); } else { $name=mysql_real_escape_string($_POST['name']); $stockid=mysql_real_escape_string($_POST['stockid']); $sell=mysql_real_escape_string($_POST['sell']); $cost=mysql_real_escape_string($_POST['cost']); $supplier=mysql_real_escape_string($_POST['supplier']); $category=mysql_real_escape_string($_POST['category']); $count = $db->countOf("stock_details", "stock_name ='$name'"); if($count>1) { $data='Dublicat Entry. Please Verify'; $msg='<p style=color:red;font-family:gfont-family:Georgia, Times New Roman, Times, serif>'.$data.'</p>';// ?> <script src="dist/js/jquery.ui.draggable.js"></script> <script src="dist/js/jquery.alerts.js"></script> <script src="dist/js/jquery.js"></script> <link rel="stylesheet" href="dist/js/jquery.alerts.css" > <script type="text/javascript"> jAlert('<?php echo $msg; ?>', 'POSNIC'); </script> <?php } else { if($db->query("insert into stock_details(stock_id,stock_name,stock_quatity,supplier_id,company_price,selling_price,category) values('$stockid','$name',0,'$supplier',$cost,$sell,'$category')")) { $db->query("insert into stock_avail(name,quantity) values('$name',0)"); $msg=" $name Stock Details Added" ; header("Location: add_stock.php?msg=$msg"); }else echo "<br><font color=red size=+1 >Problem in Adding !</font>" ; } } } if(isset($_GET['msg'])){ $data=$_GET['msg']; $msg='<p style=color:#153450;font-family:gfont-family:Georgia, Times New Roman, Times, serif>'.$data.'</p>';// ?> <script src="dist/js/jquery.ui.draggable.js"></script> <script src="dist/js/jquery.alerts.js"></script> <script src="dist/js/jquery.js"></script> <link rel="stylesheet" href="dist/js/jquery.alerts.css" > <script type="text/javascript"> jAlert('<?php echo $msg; ?>', 'POSNIC'); </script> <?php } ?> <form name="form1" method="post" id="form1" action=""> <table class="form" border="0" cellspacing="0" cellpadding="0"> <tr> <?php $max = $db->maxOfAll("id", "stock_details"); $max=$max+1; $autoid="SD".$max.""; ?> <td><span class="man">*</span>Stock ID:</td> <td><input name="stockid" type="text" id="stockid" readonly maxlength="200" class="round default-width-input" value="<?php echo $autoid; ?>" /></td> <td><span class="man">*</span>Name:</td> <td><input name="name"placeholder="ENTER CATEGORY NAME" type="text" id="name" maxlength="200" class="round default-width-input" value="<?php echo $name; ?>" /></td> </tr> <tr> <td><span class="man">*</span>Cost:</td> <td><input name="cost" placeholder="ENTER COST PRICE" type="text" id="cost" maxlength="200" class="round default-width-input" onkeypress="return numbersonly(event)" value="<?php echo $cost; ?>" /></td> <td><span class="man">*</span>Sell:</td> <td><input name="sell" placeholder="ENTER SELLING PRICE" type="text" id="sell" maxlength="200" class="round default-width-input" onkeypress="return numbersonly(event)" value="<?php echo $sell; ?>" /></td> </tr> <tr> <td>Supplier:</td> <td><input name="supplier" placeholder="ENTER SUPPLIER NAME" type="text" id="supplier" maxlength="200" class="round default-width-input" value="<?php echo $supplier; ?>" /></td> <td>Category:</td> <td><input name="category" placeholder="ENTER CATEGORY NAME" type="text" id="category" maxlength="200" class="round default-width-input" value="<?php echo $category; ?>" /></td> </tr> <tr> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> <input class="button round blue image-right ic-add text-upper" type="submit" name="Submit" value="Add"> (Control + S) <td align="right"><input class="button round red text-upper" type="reset" name="Reset" value="Reset"> </td> </tr> </table> </form> </div> <!-- end content-module-main --> </div> <!-- end content-module --> </div> <!-- end full-width --> </div> <!-- end content --> <!-- FOOTER --> <div id="footer"> <p>Any Queries email to <a href="mailto:sridhar.posnic@gmail.com?subject=Stock%20Management%20System">sridhar.posnic@gmail.com</a>.</p> </div> <!-- end footer --> </body> </html> now who can tell me what is wrong with the function filter_var() method on line 186 in ump.class.php?
  9. nb the 1st snip is from database_install.php . Which is now the bone of contention. and source of the new error due to th change I made by creating a var $myconnection into db_class.php
  10. ok now I think there's been a major improvement. The error has cleared but one of the scripts is now giving out error saying "$data="Database Configration is Not vaild";" between lines 120 and 122. <!-- MAIN CONTENT --> <div id="content"> <?php if((isset($_POST['host']) and isset($_POST['username']) and $_POST['host']!="" and $_POST['username']!="") or (isset($_SESSION['host']) and isset($_SESSION['user']))) { if(isset($_SESSION['host'])){ $host= $_SESSION['host']; $user=$_SESSION['user']; $pass=$_SESSION['pass']; } if(isset($_POST['host'])){ $host= trim($_POST['host']); $user= trim($_POST['username']); $pass= trim($_POST['password']); } $link = mysqli_connect("$host","$user","$pass"); if (!$link) { $data="Database Configration is Not vaild"; header("location:install.php?msg=$data"); exit; } ?> <form action="setup_page.php" method="POST" id="login-form" class="cmxform" autocomplete="off"> <fieldset > <p> <?php if(isset($_REQUEST['msg'])) { $msg=$_REQUEST['msg']; echo "<p style=color:red>$msg</p>"; } ?> </p> <p> <?php $con=mysqli_connect("$host","$user","$pass"); // Check connection $sql="CREATE DATABASE MY_p"; if (mysqli_query($con,$sql)){ $sql="DROP DATABASE MY_p"; mysqli_query($con,$sql); ?> <input type="radio" value="1" name="select[]" id="create" onClick="create_data()" >Create New DataBase <input type="text" id="name" class="round full-width-input" name="name" autofocus /> <?php }else{ ?> <input type="radio" disabled="disabled" >Create New DataBase <input type="text" disabled="disabled" class="round full-width-input" placeholder="No Permission To Create New Database" name="name" autofocus /> <?php } ?> </p> <p> <input type="radio" name="select[]" id="select" onClick="select_data()" >Select Created DataBase<br> <select name="select_box" class="round full-width-input" id="select_box" style="padding: 5px 10px 5px 10px; border: 1px solid #D9DBDD;"> <?php $dbh = new PDO( "mysql:host=$host", $user, $pass ); $dbs = $dbh->query( 'SHOW DATABASES' ); while( ( $db = $dbs->fetchColumn( 0 ) ) !== false ) { echo "<option value=".$db." style=margin:10px 10px 10px 10px;><p >$db</p></option>"; } ?> </select> </p> <input type="hidden" name="host" value="<?php echo $host ?>"> <input type="hidden" name="username" value="<?php echo $user ?>"> <input type="hidden" name="password" value="<?php echo $pass ?>"> <br> <input type="checkbox" name="dummy" value="1" >Add Demo Data <br> <br> <!--<a href="dashboard.php" class="button round blue image-right ic-right-arrow">LOG IN</a>--> <input type="submit" class="button round blue image-right ic-right-arrow" name="submit" value="INSTALL" /> </fieldset> </form> </div> <!-- end content --> <?php } ?> <!-- FOOTER --> <div id="footer"> Here's the corrected db.class.php: <?php /** A PHP class to access MySQL database with convenient methods * in an object oriented way, and with a powerful debug system.\n * Licence: LGPL \n * Web site: http://slaout.linux62.org/ * @version 1.0 * @author Sébastien Laoût (slaout@linux62.org) */ class DB { /** Put this variable to true if you want ALL queries to be debugged by default: */ var $defaultDebug = false; /** INTERNAL: The start time, in miliseconds. */ var $mtStart; /** INTERNAL: The number of executed queries. */ var $nbQueries; /** INTERNAL: The last result ressource of a query(). */ var $lastResult; /** Connect to a MySQL database to be able to use the methods below. */ var $myconnection; function DB($base, $server, $user, $pass) { $this->mtStart = $this->getMicroTime(); $this->nbQueries = 0; $this->lastResult = NULL; $this->myconnection = mysqli_connect($server, $user, $pass); $this->myconnection = mysqli_select_db($this->myconnection,$base) ; if ($myconnection==FALSE) { $data='Database Connection is Not valid Please Enter The valid database connection'; header("location:install.php?msg=$data"); exit; } } /** Query the database. * @param $query The query. * @param $debug If true, it output the query and the resulting table. * @return The result of the query, to use with fetchNextObject(). */ function query($query, $debug = -1) { $this->nbQueries++; $this->lastResult = mysql_query($query) or $this->debugAndDie($query); $this->debug($debug, $query, $this->lastResult); return $this->lastResult; } /** Do the same as query() but do not return nor store result.\n * Should be used for INSERT, UPDATE, DELETE... * @param $query The query. * @param $debug If true, it output the query and the resulting table. */ function execute($query, $debug = -1) { $this->nbQueries++; mysql_query($query) or $this->debugAndDie($query); $this->debug($debug, $query); } /** Convenient method for mysql_fetch_object(). * @param $result The ressource returned by query(). If NULL, the last result returned by query() will be used. * @return An object representing a data row. */ function fetchNextObject($result = NULL) { if ($result == NULL) $result = $this->lastResult; if ($result == NULL || mysql_num_rows($result) < 1) return NULL; else return mysql_fetch_object($result); } /** Get the number of rows of a query. * @param $result The ressource returned by query(). If NULL, the last result returned by query() will be used. * @return The number of rows of the query (0 or more). */ function numRows($result = NULL) { if ($result == NULL) return mysql_num_rows($this->lastResult); else return mysql_num_rows($result); } /** Get the result of the query as an object. The query should return a unique row.\n * Note: no need to add "LIMIT 1" at the end of your query because * the method will add that (for optimisation purpose). * @param $query The query. * @param $debug If true, it output the query and the resulting row. * @return An object representing a data row (or NULL if result is empty). */ function queryUniqueObject($query, $debug = -1) { $query = "$query LIMIT 1"; $this->nbQueries++; $result = mysqli_query($this->myconnection, $query) or $this->debugAndDie($query); $this->debug($debug, $query, $result); return mysql_fetch_object($result); } /** Get the result of the query as value. The query should return a unique cell.\n * Note: no need to add "LIMIT 1" at the end of your query because * the method will add that (for optimisation purpose). * @param $query The query. * @param $debug If true, it output the query and the resulting value. * @return A value representing a data cell (or NULL if result is empty). */ function queryUniqueValue($query, $debug = -1) { $query = "$query LIMIT 1"; $this->nbQueries++; $result = mysql_query($query) or $this->debugAndDie($query); $line = mysql_fetch_row($result); $this->debug($debug, $query, $result); return $line[0]; } /** Get the maximum value of a column in a table, with a condition. * @param $column The column where to compute the maximum. * @param $table The table where to compute the maximum. * @param $where The condition before to compute the maximum. * @return The maximum value (or NULL if result is empty). */ function maxOf($column, $table, $where) { return $this->queryUniqueValue("SELECT MAX(`$column`) FROM `$table` WHERE $where"); } /** Get the maximum value of a column in a table. * @param $column The column where to compute the maximum. * @param $table The table where to compute the maximum. * @return The maximum value (or NULL if result is empty). */ function maxOfAll($column, $table) { return $this->queryUniqueValue("SELECT MAX(`$column`) FROM `$table`"); } /** Get the count of rows in a table, with a condition. * @param $table The table where to compute the number of rows. * @param $where The condition before to compute the number or rows. * @return The number of rows (0 or more). */ function countOf($table, $where) { return $this->queryUniqueValue("SELECT COUNT(*) FROM `$table` WHERE $where"); } /** Get the count of rows in a table. * @param $table The table where to compute the number of rows. * @return The number of rows (0 or more). */ function countOfAll($table) { return $this->queryUniqueValue("SELECT COUNT(*) FROM `$table`"); } /** Internal function to debug when MySQL encountered an error, * even if debug is set to Off. * @param $query The SQL query to echo before diying. */ function debugAndDie($query) { $this->debugQuery($query, "Error"); die("<p style=\"margin: 2px;\">".mysql_error()."</p></div>"); } /** Internal function to debug a MySQL query.\n * Show the query and output the resulting table if not NULL. * @param $debug The parameter passed to query() functions. Can be boolean or -1 (default). * @param $query The SQL query to debug. * @param $result The resulting table of the query, if available. */ function debug($debug, $query, $result = NULL) { if ($debug === -1 && $this->defaultDebug === false) return; if ($debug === false) return; $reason = ($debug === -1 ? "Default Debug" : "Debug"); $this->debugQuery($query, $reason); if ($result == NULL) echo "<p style=\"margin: 2px;\">Number of affected rows: ".mysql_affected_rows()."</p></div>"; else $this->debugResult($result); } /** Internal function to output a query for debug purpose.\n * Should be followed by a call to debugResult() or an echo of "</div>". * @param $query The SQL query to debug. * @param $reason The reason why this function is called: "Default Debug", "Debug" or "Error". */ function debugQuery($query, $reason = "Debug") { $color = ($reason == "Error" ? "red" : "orange"); echo "<div style=\"border: solid $color 1px; margin: 2px;\">". "<p style=\"margin: 0 0 2px 0; padding: 0; background-color: #DDF;\">". "<strong style=\"padding: 0 3px; background-color: $color; color: white;\">$reason:</strong> ". "<span style=\"font-family: monospace;\">".htmlentities($query)."</span></p>"; } /** Internal function to output a table representing the result of a query, for debug purpose.\n * Should be preceded by a call to debugQuery(). * @param $result The resulting table of the query. */ function debugResult($result) { echo "<table border=\"1\" style=\"margin: 2px;\">". "<thead style=\"font-size: 80%\">"; $numFields = mysql_num_fields($result); // BEGIN HEADER $tables = array(); $nbTables = -1; $lastTable = ""; $fields = array(); $nbFields = -1; while ($column = mysql_fetch_field($result)) { if ($column->table != $lastTable) { $nbTables++; $tables[$nbTables] = array("name" => $column->table, "count" => 1); } else $tables[$nbTables]["count"]++; $lastTable = $column->table; $nbFields++; $fields[$nbFields] = $column->name; } for ($i = 0; $i <= $nbTables; $i++) echo "<th colspan=".$tables[$i]["count"].">".$tables[$i]["name"]."</th>"; echo "</thead>"; echo "<thead style=\"font-size: 80%\">"; for ($i = 0; $i <= $nbFields; $i++) echo "<th>".$fields[$i]."</th>"; echo "</thead>"; // END HEADER while ($row = mysql_fetch_array($result)) { echo "<tr>"; for ($i = 0; $i < $numFields; $i++) echo "<td>".htmlentities($row[$i])."</td>"; echo "</tr>"; } echo "</table></div>"; $this->resetFetch($result); } /** Get how many time the script took from the begin of this object. * @return The script execution time in seconds since the * creation of this object. */ function getExecTime() { return round(($this->getMicroTime() - $this->mtStart) * 1000) / 1000; } /** Get the number of queries executed from the begin of this object. * @return The number of queries executed on the database server since the * creation of this object. */ function getQueriesCount() { return $this->nbQueries; } /** Go back to the first element of the result line. * @param $result The resssource returned by a query() function. */ function resetFetch($result) { if (mysql_num_rows($result) > 0) mysql_data_seek($result, 0); } /** Get the id of the very last inserted row. * @return The id of the very last inserted row (in any table). */ function lastInsertedId() { return mysql_insert_id(); } /** Close the connexion with the database server.\n * It's usually unneeded since PHP do it automatically at script end. */ function close() { mysql_close(); } /** Internal method to get the current time. * @return The current time in seconds with microseconds (in float format). */ function getMicroTime() { list($msec, $sec) = explode(' ', microtime()); return floor($sec / 1000) + $msec; } } // class DB ?> Any better ideas?
  11. @sycho, thanks for your effort, Im looking closely at your suggestion. To be more specific, the trouble spot is here: function queryUniqueObject($query, $debug = -1) { $query = "$query LIMIT 1"; $this->nbQueries++; $result = mysqli_query($myconnection, $query) or $this->debugAndDie($query); $this->debug($debug, $query, $result); return mysql_fetch_object($result); } As ably described above, line 106 refers to "$result = mysqli_query($myconnection, $query) or $this->debugAndDie($query);". There's a possibility that $myconnection is not visible to the method. Well thought out Psycho. Yea, @ginerjm, of cos its well thought out.Btw, $myconnection is defined @ the top of the class here: function DB($base, $server, $user, $pass) { $this->mtStart = $this->getMicroTime(); $this->nbQueries = 0; $this->lastResult = NULL; $myconnection = mysqli_connect($server, $user, $pass); $myconnection = mysqli_select_db($myconnection,$base) ; if ($myconnection==FALSE) { $data='Database Connection is Not valid Please Enter The valid database connection'; header("location:install.php?msg=$data"); exit; } } @mac, sorry about the mix up, I stand corrected.
  12. <?php /** A PHP class to access MySQL database with convenient methods * in an object oriented way, and with a powerful debug system.\n * Licence: LGPL \n * Web site: http://slaout.linux62.org/ * @version 1.0 * @author Sébastien Laoût (slaout@linux62.org) */ class DB { /** Put this variable to true if you want ALL queries to be debugged by default: */ var $defaultDebug = false; /** INTERNAL: The start time, in miliseconds. */ var $mtStart; /** INTERNAL: The number of executed queries. */ var $nbQueries; /** INTERNAL: The last result ressource of a query(). */ var $lastResult; /** Connect to a MySQL database to be able to use the methods below. */ function DB($base, $server, $user, $pass) { $this->mtStart = $this->getMicroTime(); $this->nbQueries = 0; $this->lastResult = NULL; $myconnection = mysqli_connect($server, $user, $pass); $myconnection = mysqli_select_db($myconnection,$base) ; if ($myconnection==FALSE) { $data='Database Connection is Not valid Please Enter The valid database connection'; header("location:install.php?msg=$data"); exit; } } /** Query the database. * @param $query The query. * @param $debug If true, it output the query and the resulting table. * @return The result of the query, to use with fetchNextObject(). */ function query($query, $debug = -1) { $this->nbQueries++; $this->lastResult = mysql_query($query) or $this->debugAndDie($query); $this->debug($debug, $query, $this->lastResult); return $this->lastResult; } /** Do the same as query() but do not return nor store result.\n * Should be used for INSERT, UPDATE, DELETE... * @param $query The query. * @param $debug If true, it output the query and the resulting table. */ function execute($query, $debug = -1) { $this->nbQueries++; mysql_query($query) or $this->debugAndDie($query); $this->debug($debug, $query); } /** Convenient method for mysql_fetch_object(). * @param $result The ressource returned by query(). If NULL, the last result returned by query() will be used. * @return An object representing a data row. */ function fetchNextObject($result = NULL) { if ($result == NULL) $result = $this->lastResult; if ($result == NULL || mysql_num_rows($result) < 1) return NULL; else return mysql_fetch_object($result); } /** Get the number of rows of a query. * @param $result The ressource returned by query(). If NULL, the last result returned by query() will be used. * @return The number of rows of the query (0 or more). */ function numRows($result = NULL) { if ($result == NULL) return mysql_num_rows($this->lastResult); else return mysql_num_rows($result); } /** Get the result of the query as an object. The query should return a unique row.\n * Note: no need to add "LIMIT 1" at the end of your query because * the method will add that (for optimisation purpose). * @param $query The query. * @param $debug If true, it output the query and the resulting row. * @return An object representing a data row (or NULL if result is empty). */ function queryUniqueObject($query, $debug = -1) { $query = "$query LIMIT 1"; $this->nbQueries++; $result = mysqli_query($myconnection, $query) or $this->debugAndDie($query); $this->debug($debug, $query, $result); return mysql_fetch_object($result); } /** Get the result of the query as value. The query should return a unique cell.\n * Note: no need to add "LIMIT 1" at the end of your query because * the method will add that (for optimisation purpose). * @param $query The query. * @param $debug If true, it output the query and the resulting value. * @return A value representing a data cell (or NULL if result is empty). */ function queryUniqueValue($query, $debug = -1) { $query = "$query LIMIT 1"; $this->nbQueries++; $result = mysql_query($query) or $this->debugAndDie($query); $line = mysql_fetch_row($result); $this->debug($debug, $query, $result); return $line[0]; } /** Get the maximum value of a column in a table, with a condition. * @param $column The column where to compute the maximum. * @param $table The table where to compute the maximum. * @param $where The condition before to compute the maximum. * @return The maximum value (or NULL if result is empty). */ function maxOf($column, $table, $where) { return $this->queryUniqueValue("SELECT MAX(`$column`) FROM `$table` WHERE $where"); } /** Get the maximum value of a column in a table. * @param $column The column where to compute the maximum. * @param $table The table where to compute the maximum. * @return The maximum value (or NULL if result is empty). */ function maxOfAll($column, $table) { return $this->queryUniqueValue("SELECT MAX(`$column`) FROM `$table`"); } /** Get the count of rows in a table, with a condition. * @param $table The table where to compute the number of rows. * @param $where The condition before to compute the number or rows. * @return The number of rows (0 or more). */ function countOf($table, $where) { return $this->queryUniqueValue("SELECT COUNT(*) FROM `$table` WHERE $where"); } /** Get the count of rows in a table. * @param $table The table where to compute the number of rows. * @return The number of rows (0 or more). */ function countOfAll($table) { return $this->queryUniqueValue("SELECT COUNT(*) FROM `$table`"); } /** Internal function to debug when MySQL encountered an error, * even if debug is set to Off. * @param $query The SQL query to echo before diying. */ function debugAndDie($query) { $this->debugQuery($query, "Error"); die("<p style=\"margin: 2px;\">".mysql_error()."</p></div>"); } /** Internal function to debug a MySQL query.\n * Show the query and output the resulting table if not NULL. * @param $debug The parameter passed to query() functions. Can be boolean or -1 (default). * @param $query The SQL query to debug. * @param $result The resulting table of the query, if available. */ function debug($debug, $query, $result = NULL) { if ($debug === -1 && $this->defaultDebug === false) return; if ($debug === false) return; $reason = ($debug === -1 ? "Default Debug" : "Debug"); $this->debugQuery($query, $reason); if ($result == NULL) echo "<p style=\"margin: 2px;\">Number of affected rows: ".mysql_affected_rows()."</p></div>"; else $this->debugResult($result); } /** Internal function to output a query for debug purpose.\n * Should be followed by a call to debugResult() or an echo of "</div>". * @param $query The SQL query to debug. * @param $reason The reason why this function is called: "Default Debug", "Debug" or "Error". */ function debugQuery($query, $reason = "Debug") { $color = ($reason == "Error" ? "red" : "orange"); echo "<div style=\"border: solid $color 1px; margin: 2px;\">". "<p style=\"margin: 0 0 2px 0; padding: 0; background-color: #DDF;\">". "<strong style=\"padding: 0 3px; background-color: $color; color: white;\">$reason:</strong> ". "<span style=\"font-family: monospace;\">".htmlentities($query)."</span></p>"; } /** Internal function to output a table representing the result of a query, for debug purpose.\n * Should be preceded by a call to debugQuery(). * @param $result The resulting table of the query. */ function debugResult($result) { echo "<table border=\"1\" style=\"margin: 2px;\">". "<thead style=\"font-size: 80%\">"; $numFields = mysql_num_fields($result); // BEGIN HEADER $tables = array(); $nbTables = -1; $lastTable = ""; $fields = array(); $nbFields = -1; while ($column = mysql_fetch_field($result)) { if ($column->table != $lastTable) { $nbTables++; $tables[$nbTables] = array("name" => $column->table, "count" => 1); } else $tables[$nbTables]["count"]++; $lastTable = $column->table; $nbFields++; $fields[$nbFields] = $column->name; } for ($i = 0; $i <= $nbTables; $i++) echo "<th colspan=".$tables[$i]["count"].">".$tables[$i]["name"]."</th>"; echo "</thead>"; echo "<thead style=\"font-size: 80%\">"; for ($i = 0; $i <= $nbFields; $i++) echo "<th>".$fields[$i]."</th>"; echo "</thead>"; // END HEADER while ($row = mysql_fetch_array($result)) { echo "<tr>"; for ($i = 0; $i < $numFields; $i++) echo "<td>".htmlentities($row[$i])."</td>"; echo "</tr>"; } echo "</table></div>"; $this->resetFetch($result); } /** Get how many time the script took from the begin of this object. * @return The script execution time in seconds since the * creation of this object. */ function getExecTime() { return round(($this->getMicroTime() - $this->mtStart) * 1000) / 1000; } /** Get the number of queries executed from the begin of this object. * @return The number of queries executed on the database server since the * creation of this object. */ function getQueriesCount() { return $this->nbQueries; } /** Go back to the first element of the result line. * @param $result The resssource returned by a query() function. */ function resetFetch($result) { if (mysql_num_rows($result) > 0) mysql_data_seek($result, 0); } /** Get the id of the very last inserted row. * @return The id of the very last inserted row (in any table). */ function lastInsertedId() { return mysql_insert_id(); } /** Close the connexion with the database server.\n * It's usually unneeded since PHP do it automatically at script end. */ function close() { mysql_close(); } /** Internal method to get the current time. * @return The current time in seconds with microseconds (in float format). */ function getMicroTime() { list($msec, $sec) = explode(' ', microtime()); return floor($sec / 1000) + $msec; } } // class DB ?> Specifically, line 106 here..
  13. After overcoming this-> error "Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in this-> $myconnection = mysql_connect($server, $user, $pass);" by changing mysql_query to mysqli_query($con, $query), I started getting this specific error on line 106= $result = mysqli_query($myconnection, $query) or $this->debugAndDie($query); Warning: mysqli_query() expects parameter 1 to be mysqli, null given on line 106=="$result = mysqli_query($myconnection, $query) or $this->debugAndDie($query);" This header wont go, I tried $myconnection = mysql_connect($query); and it says expecting 2 parameters. Please I'm open to ideas to solve this, <snip - code is posted in next post>
  14. One more thing David, on my local machine the dir is C:\xampp\htdocs\ASearch, ie $dir = 'dir for search'; the code executes properly, but on my subdomain say http://s.hgf.com, where the target files are when I click the submit button, the browser just keeps loading and does not respond. Meanwhile the local 1 executes properly. How do you think I should link up to the subdomain in order for this script to work?
  15. briliant David, I did change line six from while(false!== ($file = readdir($res))) { to while(false!== ($file = readdir($res)) && $q!='') { ..and it stopped the error. Thanks a mil. and keep the skill up Pal.
  16. Im having this error being thrown up on execution donno what could be wrong. Actually Im trying to display specific files as a url link for download from a search box. Could some1 tell me how I can get over this error? <?php $dir = 'dir for search'; $exclude = array('.','..','.htaccess'); $q = (isset($_GET['q']))? strtolower($_GET['q']) : ''; $res = opendir($dir); while(false!== ($file = readdir($res))) { if(strpos(strtolower($file),$q)!== false &&!in_array($file,$exclude)) { echo "<a href='$dir/$file'>$file</a>"; echo "<br>"; } } closedir($res); ?> <!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'> <html xmlns='http://www.w3.org/1999/xhtml'> <head> <meta http-equiv='Content-Type' content='text/html; charset=utf-8' /> <title>SEARCH SCRIPT</title> </head> <body> <div id='header'> SEARCH FOR FILES </div> <div id='formsearch'> <form action='SearchScript.php' method='get'><input name='q' type='text'> <input type='submit'></form> </div> <div> </body> </html> the line 7 => if(strpos(strtolower($file),$q)!== false &&!in_array($file,$exclude)) { what is wrong with this line? Any ideas?
  17. You already answered the question yourself. Again "a method that will return the variable and whats assigned to the vairable". Im sorry but you seem not to understand how to carry out your objective. Rather you are going around with what you think you know or can work. Simply supply the variables as arguements that will return their values when involed. Why not: function accounts($demo=true,$from_number,$sid,$token) { if($demo) { if {$from_number = "blah"; $sid = "******************"; $token = "*****************"; } else { $from_number = "5555555555"; $sid = "*****************"; $token = "*****************"; } } accounts($demo=true,$from_number,$sid,$token); You might hav to still debug further...to get there.
  18. Now why in world would you want to "instantiate a child class object" as " a copy of an instantiated parent class object", ? Isn't that clumsy ? or repeatitive?
  19. Teyon, Barand, David, and Kevin thanks all for your time. I'd go back to my drawing board and fix this then give u guz an update.
  20. I think zend needs to look properly into the rules of function declarations and its attendant calls. I mean there should be a level of consistency as php 6.0 approaches. Tenyon, you seem to have some better understanding of what is happening here. Mr. Kevin could u pls be more descriptive of your point by code demo?? Mr. Barand, pls can you make your pointers to this issue more closer to the present call. Much appreciated guz.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.