capturing data using dropdown menu,radio buttons in mysql - php

I am making a simple registration form with radio button and a drop-down menu.
My problem is I cannot insert form data into my database. I think I am not capturing the form data but I am not sure.
Because when I submit the form I get the error SORRY! ERROR while inserting record ! which is telling me it failed to insert.i have tried to add
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL);
so that i see the actual errors displayed on my page but i still can not see to figure out what is it that i'm doing wrong.
Page code:
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL);
include_once 'dbconfig.php';
if(isset($_POST['btn-save']))
{
$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
$employee_nrc = $_POST['employee_nrc'];
$Phone = $_POST['phone_no'];
$Businesstype = $_POST['business_type'];
$Businesssite = $_POST['business_site'];
$Businessactivity = $_POST['business_activity'];
if($crud->create($fname,$lname,$employee_nrc,$Phone,$Businesstype,$Businesssite,$Businessactivity))
{
header("Location: add-data.php?inserted");
}
else
{
header("Location: add-data.php?failure");
}
}
?>
<?php include_once 'header.php'; ?>
<div class="clearfix"></div>
<?php
if(isset($_GET['inserted']))
{
?>
<div class="container">
<div class="alert alert-info">
<strong>WOW!</strong> Record was inserted successfully HOME!
</div>
</div>
<?php
}
else if(isset($_GET['failure']))
{
?>
<div class="container">
<div class="alert alert-warning">
<strong>SORRY!</strong> ERROR while inserting record !
</div>
</div>
<?php
}
?>
<div class="clearfix"></div><br />
<div class="container">
<form class="form-horizontal" method='post'>
<fieldset>
<legend>Registration System</legend>
<div class="form-group">
<label for="inputFirstName" class="col-lg-2 control-label">First Name</label>
<div class="col-lg-10">
<input type="text" name="first_name" class="form-control" required>
</div>
</div>
<div class="form-group">
<label for="inputLastName" class="col-lg-2 control-label">Last Name</label>
<div class="col-lg-10">
<input type="text" name="last_name" class="form-control" required>
</div>
</div>
<div class="form-group">
<label for="inputEmployeeNRC" class="col-lg-2 control-label">Employee NRC</label>
<div class="col-lg-10">
<input type="text" name="Employee_nrc" class="form-control" required>
</div>
</div>
<div class="form-group">
<label for="inputEmployeePhoneNumber" class="col-lg-2 control-label">Employee Phone Number</label>
<div class="col-lg-10">
<input type="text" name="phone_no" class='form-control' required>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Business Type</label>
<div class="col-lg-10">
<div class="radio">
<label>
<input type="radio" name="business_type" value=" HomeStead stalls" checked>
HomeStead stalls
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="business_type" value=" Vending" checked>
Vending
</label>
</div>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Business Location</label>
<div class="col-lg-10">
<div class="radio">
<label>
<input type="radio" name="business_site" value=" Market" checked>
Market
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="business_site" value="Residential Area" checked>
Residential Area
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="business_site" value="Street Vending" checked>
Street Vending
</label>
</div>
</div>
</div>
<div class="form-group">
<label for="select" class="col-lg-2 control-label">Business Activities</label>
<div class="col-lg-10">
<select class="form-control" name="business_activity">
<option value="Agriculture, forestry and fishing">Agriculture, forestry and fishing</option>
<option value="Mining and quarrying">Mining and quarrying</option>
<option value="Manufacturing">Manufacturing</option>
<option value="Electricity, gas, steam and air conditioning supply">Electricity, gas, steam and air conditioning supply</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button type="submit" class="btn btn-primary" name="btn-save">
<span class="glyphicon glyphicon-plus"></span> ADD Record
</button>
<i class="glyphicon glyphicon-backward"></i> Back to index
</div>
</div>
</fieldset>
</form>
</div>
<?php include_once 'footer.php'; ?>
my crud function
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL);
class crud
{
private $db;
function __construct($DB_con)
{
$this->db = $DB_con;
}
public function create($fname,$lname,$employee_nrc,$Phone,$Businesstype,$Businesssite,$Businessactivity)
{
try
{
$stmt = $this->db->prepare("INSERT INTO tbl_users(first_name,last_name,employee_nrc, phone_no, Businesstype ,Businesssite ,Businessactivity) VALUES(:fname, :lname, :employee_nrc, :Phone, :Businesstype, :Businesssite, :Businessactivity)");
$stmt->bindparam(":fname",$fname);
$stmt->bindparam(":lname",$lname);
$stmt->bindparam(":employee_nrc",$employee_nrc);
$stmt->bindparam(":Phone",$Phone);
$stmt->bindparam(":Businesstype",$Businesstype);
$stmt->bindparam(":Businesssite",$Businesssite);
$stmt->bindparam(":Businessactivity",$Businessactivity);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
public function getID($id)
{
$stmt = $this->db->prepare("SELECT * FROM tbl_users WHERE id=:id");
$stmt->execute(array(":id"=>$id));
$editRow=$stmt->fetch(PDO::FETCH_ASSOC);
return $editRow;
}
public function update($id,$fname,$lname,$email,$contact)
{
try
{
$stmt=$this->db->prepare("UPDATE tbl_users SET first_name=:fname,
last_name=:lname,
employee_nrc=:employee_nrc,
phone_no=:Phone,
Businesstype=:Businesstype,
Businesssite=:Businesssite,
Businessactivity=:Businessactivity
WHERE id=:id ");
$stmt->bindparam(":fname",$fname);
$stmt->bindparam(":lname",$lname);
$stmt->bindparam(":employee_nrc",$employee_nrc);
$stmt->bindparam(":Businesstype",$Phone);
$stmt->bindparam(":Businesstype",$Businesstype);
$stmt->bindparam(":Businesssite",$Businesssite);
$stmt->bindparam(":Businessactivity",$Businessactivity);
$stmt->bindparam(":id",$id);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
public function delete($id)
{
$stmt = $this->db->prepare("DELETE FROM tbl_users WHERE id=:id");
$stmt->bindparam(":id",$id);
$stmt->execute();
return true;
}
/* paging */
public function dataview($query)
{
$stmt = $this->db->prepare($query);
$stmt->execute();
if($stmt->rowCount()>0)
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<tr>
<td><?php print($row['id']); ?></td>
<td><?php print($row['first_name']); ?></td>
<td><?php print($row['last_name']); ?></td>
<td><?php print($row['employee_nrc']); ?></td>
<td><?php print($row['phone_no']); ?></td>
<td><?php print($row['Businesstype']); ?></td>
<td><?php print($row['Businesssite']); ?></td>
<td><?php print($row['Businessactivity']); ?></td>
<td align="center">
<i class="glyphicon glyphicon-edit"></i>
</td>
<td align="center">
<i class="glyphicon glyphicon-remove-circle"></i>
</td>
</tr>
<?php
}
}
else
{
?>
<tr>
<td>Nothing here...</td>
</tr>
<?php
}
}
public function paging($query,$records_per_page)
{
$starting_position=0;
if(isset($_GET["page_no"]))
{
$starting_position=($_GET["page_no"]-1)*$records_per_page;
}
$query2=$query." limit $starting_position,$records_per_page";
return $query2;
}
public function paginglink($query,$records_per_page)
{
$self = $_SERVER['PHP_SELF'];
$stmt = $this->db->prepare($query);
$stmt->execute();
$total_no_of_records = $stmt->rowCount();
if($total_no_of_records > 0)
{
?><ul class="pagination"><?php
$total_no_of_pages=ceil($total_no_of_records/$records_per_page);
$current_page=1;
if(isset($_GET["page_no"]))
{
$current_page=$_GET["page_no"];
}
if($current_page!=1)
{
$previous =$current_page-1;
echo "<li><a href='".$self."?page_no=1'>First</a></li>";
echo "<li><a href='".$self."?page_no=".$previous."'>Previous</a></li>";
}
for($i=1;$i<=$total_no_of_pages;$i++)
{
if($i==$current_page)
{
echo "<li><a href='".$self."?page_no=".$i."' style='color:red;'>".$i."</a></li>";
}
else
{
echo "<li><a href='".$self."?page_no=".$i."'>".$i."</a></li>";
}
}
if($current_page!=$total_no_of_pages)
{
$next=$current_page+1;
echo "<li><a href='".$self."?page_no=".$next."'>Next</a></li>";
echo "<li><a href='".$self."?page_no=".$total_no_of_pages."'>Last</a></li>";
}
?></ul><?php
}
}
/* paging */
}

Your issue is that you have not properly coded the <input> tags in your HTML.
Each <input> tag required a name="" attribute as it is this attribute and not the id="" that the browser uses to create the name=value pairs that are sent as $_GET or $_POST variables
So amend your code and add a name="" attribute ro all the input tags like so :-
<input type="text" name="first_name" class="form-control" id="inputFirstName" placeholder="first name">
and so on for all the input fields, making sure the names you give to each input match the names you are using in your PHP code.
Also make sure that the name="last_name" is the same as the $_POST['last_name'].
Case should also match, so name='Employee NRC' and $_POST['employee_nrc']; do not match and wont work. Also dont put spaces in the name='Employee NRC' either remove spaces or us an underscore _ in the name like name='employee_nrc'.

Related

How to populate the value of a field on another field on same table

I have a table that has "customer registration" "Update Billing Address" and "Update Shipping Address" a group of fields. Upon registration the user fills the "customer registration".
I'd like the values on this field ("customer registration") to be populated automatically on "Update Billing Address" and "Update Shipping Address" instead of filling both fields manually. Note these are different fields but on same table in the Database.
How do I achieve this? Please pardon me if this question is too elementary, I've tried to find the answer here from previous post but can't get what I want. enter image description here
<?php require_once('header.php'); ?>
<?php
// Check if the customer is logged in or not
if(!isset($_SESSION['customer'])) {
header('location: '.BASE_URL.'logout.php');
exit;
} else {
// If customer is logged in, but admin make him inactive, then force logout this user.
$statement = $pdo->prepare("SELECT * FROM tbl_customer WHERE cust_id=? AND cust_status=?");
$statement->execute(array($_SESSION['customer']['cust_id'],0));
$total = $statement->rowCount();
if($total) {
header('location: '.BASE_URL.'logout.php');
exit;
}
}
?>
<?php
if (isset($_POST['form1'])) {
$valid = 1;
if(empty($_POST['cust_name'])) {
$valid = 0;
$error_message .= LANG_VALUE_123."<br>";
}
if(empty($_POST['cust_phone'])) {
$valid = 0;
$error_message .= LANG_VALUE_124."<br>";
}
if(empty($_POST['cust_address'])) {
$valid = 0;
$error_message .= LANG_VALUE_125."<br>";
}
if(empty($_POST['cust_country'])) {
$valid = 0;
$error_message .= LANG_VALUE_126."<br>";
}
if(empty($_POST['cust_city'])) {
$valid = 0;
$error_message .= LANG_VALUE_127."<br>";
}
if(empty($_POST['cust_state'])) {
$valid = 0;
$error_message .= LANG_VALUE_128."<br>";
}
if(empty($_POST['cust_zip'])) {
$valid = 0;
$error_message .= LANG_VALUE_129."<br>";
}
if($valid == 1) {
// update data into the database
$statement = $pdo->prepare("UPDATE tbl_customer SET cust_name=?, cust_cname=?, cust_phone=?, cust_country=?, cust_address=?, cust_city=?, cust_state=?, cust_zip=? WHERE cust_id=?");
$statement->execute(array(
strip_tags($_POST['cust_name']),
strip_tags($_POST['cust_cname']),
strip_tags($_POST['cust_phone']),
strip_tags($_POST['cust_country']),
strip_tags($_POST['cust_address']),
strip_tags($_POST['cust_city']),
strip_tags($_POST['cust_state']),
strip_tags($_POST['cust_zip']),
$_SESSION['customer']['cust_id']
));
$success_message = LANG_VALUE_130;
$_SESSION['customer']['cust_name'] = $_POST['cust_name'];
$_SESSION['customer']['cust_cname'] = $_POST['cust_cname'];
$_SESSION['customer']['cust_phone'] = $_POST['cust_phone'];
$_SESSION['customer']['cust_country'] = $_POST['cust_country'];
$_SESSION['customer']['cust_address'] = $_POST['cust_address'];
$_SESSION['customer']['cust_city'] = $_POST['cust_city'];
$_SESSION['customer']['cust_state'] = $_POST['cust_state'];
$_SESSION['customer']['cust_zip'] = $_POST['cust_zip'];
}
}
?>
<div class="page">
<div class="container">
<div class="row">
<div class="col-md-12">
<?php require_once('customer-sidebar.php'); ?>
</div>
<div class="col-md-12">
<div class="user-content">
<h3>
<?php echo LANG_VALUE_117; ?>
</h3>
<?php
if($error_message != '') {
echo "<div class='error' style='padding: 10px;background:#f1f1f1;margin-bottom:20px;'>".$error_message."</div>";
}
if($success_message != '') {
echo "<div class='success' style='padding: 10px;background:#f1f1f1;margin-bottom:20px;'>".$success_message."</div>";
}
?>
<form action="" method="post">
<?php $csrf->echoInputField(); ?>
<div class="row">
<div class="col-md-6 form-group">
<label for=""><?php echo LANG_VALUE_102; ?> *</label>
<input type="text" class="form-control" name="cust_name" value="<?php echo $_SESSION['customer']['cust_name']; ?>">
</div>
<div class="col-md-6 form-group">
<label for=""><?php echo LANG_VALUE_103; ?></label>
<input type="text" class="form-control" name="cust_cname" value="<?php echo $_SESSION['customer']['cust_cname']; ?>">
</div>
<div class="col-md-6 form-group">
<label for=""><?php echo LANG_VALUE_94; ?> *</label>
<input type="text" class="form-control" name="" value="<?php echo $_SESSION['customer']['cust_email']; ?>" disabled>
</div>
<div class="col-md-6 form-group">
<label for=""><?php echo LANG_VALUE_104; ?> *</label>
<input type="text" class="form-control" name="cust_phone" value="<?php echo $_SESSION['customer']['cust_phone']; ?>">
</div>
<div class="col-md-12 form-group">
<label for=""><?php echo LANG_VALUE_105; ?> *</label>
<textarea name="cust_address" class="form-control" cols="30" rows="10" style="height:70px;"><?php echo $_SESSION['customer']['cust_address']; ?></textarea>
</div>
<div class="col-md-6 form-group">
<label for=""><?php echo LANG_VALUE_106; ?> *</label>
<select name="cust_country" class="form-control">
<?php
$statement = $pdo->prepare("SELECT * FROM tbl_country ORDER BY country_name ASC");
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
?>
<option value="<?php echo $row['country_id']; ?>" <?php if($row['country_id'] == $_SESSION['customer']['cust_country']) {echo 'selected';} ?>><?php echo $row['country_name']; ?></option>
<?php
}
?>
</select>
</div>
<div class="col-md-6 form-group">
<label for=""><?php echo LANG_VALUE_107; ?> *</label>
<input type="text" class="form-control" name="cust_city" value="<?php echo $_SESSION['customer']['cust_city']; ?>">
</div>
<div class="col-md-6 form-group">
<label for=""><?php echo LANG_VALUE_108; ?> *</label>
<input type="text" class="form-control" name="cust_state" value="<?php echo $_SESSION['customer']['cust_state']; ?>">
</div>
<div class="col-md-6 form-group">
<label for=""><?php echo LANG_VALUE_109; ?> *</label>
<input type="text" class="form-control" name="cust_zip" value="<?php echo $_SESSION['customer']['cust_zip']; ?>">
</div>
</div>
<input type="submit" class="btn btn-primary" value="<?php echo LANG_VALUE_5; ?>" name="form1">
</form>
</div>
</div>
</div>
</div>
</div>
I expect the value of the cust_name, cust_cname, cust_phone, cust_country, cust_address, cust_city, cust_state, cust_zip to populate on the equivalent fields. If you understand what I mean.
The answear is in your code:
$statement = $pdo->prepare("SELECT * FROM tbl_country ORDER BY country_name ASC");
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row){ }?>
The last foreach is a cicle it runs on all the result table, so if you want to update the filds, you need to change the "question" to the table you want to query and then on the cicle store them in the correct variables cust_name, cust_cname, cust_phone, cust_country, cust_address, cust_city, cust_state, cust_zip i suppose.
Good Luck

Customer Name,Mobile Number and Description Fetch but not fetch address why?

<?php
if(isset($_POST['updatecustomer'])){
$customerID=trim($_POST['customerID']);
$customername=trim($_POST['customername']);
$mobilenumber=trim($_POST['mobilenumber']);
$Description=trim($_POST['description']);
$area=trim($_POST['area']);
if(empty($customername)){
$errorcustomername="Please Enter Customer Name";
}
elseif (empty($mobilenumber)) {
$Errormobilenumber="Please Enter Mobile Number";
}
elseif (empty($Description)) {
$Errordescription="Please Enter Description";
}
elseif (empty($area)) {
$Errorarea="Please Enter Address";
}
else
{
try {
if (trim($_FILES["image"]["name"])!=""){
$base=explode(".", strtolower(basename($_FILES["image"]["name"])));
$ext=end($base);
if($ext=="png" or $ext=="jpg" or $ext=="jpeg"){
$image1 = getimagesize($_FILES["image"]["tmp_name"]);
$width = $image1[0];
$height = $image1[1];
if($width<256 || $height<256){
$error = true;
$ErrorImage = "Please select an image with minimum resolution of 256x256 !";
}else{
$image1=uniqid().".".$ext;
move_uploaded_file($_FILES["image"]["tmp_name"], "picture/" . $image1);
$image1="picture/".$image1;
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/update Query/
$sql="UPDATE customer SET shopID='$shopID',name='$customername',
mobile='$mobilenumber',area='$area',description='$Description',picture='$image1' WHERE customerID='$customerID'";
$con->exec($sql);
$sql1="UPDATE customerdetails SET area='$area' WHERE customerID='$customerID' ";
if (mysqli_query($conn,$sql1)) {
$success="Customer Updated Successfully";
}
else
{
$errorSubmit="Customer not Updated";
}
}
}
else {
}
$error = true;
$ErrorImage="invalid image extension !";
}
else {
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql="UPDATE customer SET shopID='$shopID',name='$customername',mobile='$mobilenumber,area='$area',description='$Description' WHERE customerID='$customerID'";
$con->exec($sql);
$sql1="UPDATE customerdetails SET area='$area' WHERE customerID='$customerID' ";
if (mysqli_query($conn,$sql1)) {
$success="Customer Updated Successfully";
}
else
{
$errorSubmit="Customer not Updated";
}
}
}
catch(PDOException $e)
{
$errorSubmit= $e->getMessage();
}
}
}
?>
<div class="boxed">
<div id="content-container">
<div id="page-title">
<h1 class="page-header text-overflow">Update Customer</h1>
</div>
<ol class="breadcrumb">
<li>Dashboard</li>
<li>Customer</li>
<li class="active">Update Customer</li>
</ol>
<div id="page-content">
<div class="col-sm-12" style="padding-bottom: 5%">
<div class="panel">
<div class="panel-heading">
<h3 class="panel-title">Update Customer Details</h3>
</div>
<form class="form-horizontal" method="POST" enctype="multipart/form-data">
<div class="panel-body">
<?php
/join Query/
$id=mysqli_real_escape_string($conn,$_GET['id']);
$sql="SELECT customer.*,customerdetails.* FROM customer JOIN customerdetails ON customer.customerID=customerdetails.customerID WHERE customer.customerID='$id'";
$read=mysqli_query($conn,$sql);
while ($row1=mysqli_fetch_assoc($read)) {
# code...
?>
<input type="hidden" name="customerID" value="<?php echo $row1['customerID']; ?>">
<div class="form-group">
<label class="col-sm-3 control-label" for="demo-hor-inputemail">Customer Name</label>
<div class="col-sm-9">
<input type="text" name="customername" class="form-control" placeholder="Customer Name" value="<?php echo $row1['name']; ?>"
oninput="this.value = this.value.replace(/[^A-Za-z ]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" maxlength="60" required="">
<?php if (!empty($errorcustomername)) { ?> <p class="label label-danger"><?php echo $errorcustomernamee; ?></p> <?php } ?>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" for="demo-hor-inputemail">Mobile Number</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="mobilenumber" placeholder="Mobile Number" value="<?php echo
$row1['mobile'];?>" oninput="this.value = this.value.replace(/[^0-9- ]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" maxlength="10"/>
<?php if (!empty($Errormobilenumber)) { ?> <p class="label label-danger"><?php echo $Errormobilenumber; ?></p> <?php } ?>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" for="demo-hor-inputemail">Address</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="area" placeholder="Address" value="<?php echo $row1['area'];?>" />
<?php if (!empty( $Errorarea)) { ?> <p class="label label-danger"><?php echo $Errorarea; ?></p> <?php } ?>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" for="demo-hor-inputemail">Description</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="description" placeholder="Description" value="<?php echo $row1['description'];?>" />
<?php if (!empty($Errordescription)) { ?> <p class="label label-danger"><?php echo $Errordescription; ?></p> <?php } ?>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" for="demo-hor-inputemail">Picture</label>
<div class="col-sm-9">
<input type="file" class="form-control" name="image" placeholder="Password" value="<?php echo $row1['image'];?>"
/>
<?php if (!empty($Errorimage)) { ?> <p class="text text-danger"><?php echo $Errorimage; ?></p> <?php } ?>
</div>
</div>
<?php
}
?>
</div>
<div align="center">
<?php if (!empty($success)) { ?> <span class="label label-success"><?php echo $success; ?></span> <?php } ?>
<?php if (!empty($errorSubmit)) { ?> <span class="label label-danger"><?php echo $errorSubmit; ?></span> <?php } ?>
</div>
<div class="panel-footer text-right">
<button class="btn btn-success" type="submit" name="updatecustomer">Update Customer</button>
</div>
</form>
</div>
</div>
</div>
</div>
<?php
include 'include/sidebar.php';
include 'include/footer.php';
?>
<?php
}
else
{
header('location:login.php');
}
?>
please check first area is inserting to DB or not?

Php Prepared Statement Fails to insert data into database through form

I'm trying to insert data into a database, the script executes all the way down and redirect the user to the page but no record gets inserted. I've been trying to figure out why for hours. I keep creating new scripts but i'm missing something apparently.
init.php
<?php
/*for error 1045 config.inc.php*/
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "");
define("DB_DATABASE", "databasename");
$db = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()){
echo "database failed to connect with following errors:". mysqli_connect_error();
die();
}
require_once $_SERVER['DOCUMENT_ROOT'].'/ecommerce/config.php';
require_once BASEURL.'helpers/helpers.php';
form.php
<?php
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once $_SERVER['DOCUMENT_ROOT'].'/HeleneQuirion/core/init.php';
include 'includes/header.php';
if(isset($_GET['add'])){
$parentQuery = $db->query("SELECT * FROM categories WHERE parent= 0" );
if (isset($_POST['submit'])) {
// prepare and bind
$stmt = $db->prepare("INSERT INTO product (prod_name, categories, list_price, price,prod_width,prod_depth,prod_height,prod_material,quantity,image_1,image_2,image_3,image_4,description,care_instructions) VALUES (?,?, ?,?,?,?,?,?,?,?,?,?,?,?,?)");
$stmt->bind_param("ssiiiiisissssss" ,$prod_name, $child,$list_price,$price,$prod_width,$prod_depth,$prod_height,$prod_material,$quantity,$image_1,$image_2,$image_3,$image_4,$description,$care_instructions);
// set parameters and execute
if(isset($_POST['prod_name']))
{
$prod_name = sanitize($_POST)['prod_name'];
}
if(isset($_POST['child']))
{
$categories = sanitize($_POST)['child'];
}
if(isset($_POST['list_price']))
{
$prod_name = sanitize($_POST)['list_price'];
}
if(isset($_POST['price']))
{
$price = sanitize($_POST)['price'];
}
if(isset($_POST['prod_width']))
{
$prod_width = sanitize($_POST)['prod_width'];
}
if(isset($_POST['prod_depth']))
{
$prod_depth = sanitize($_POST)['prod_depth'];
}
if(isset($_POST['prod_height']))
{
$prod_height = sanitize($_POST)['prod_height'];
}
if(isset($_POST['prod_material']))
{
$prod_material = sanitize($_POST)['prod_material'];
}
if(isset($_POST['quantity']))
{
$quantity = sanitize($_POST)['quantity'];
}
if(isset($_POST['care_instructions']))
{
$care_instructions = sanitize($_POST)['care_instructions'];
}
if(isset($_POST['image_1']))
{
$image_1 = $_FILES['image_1'];
}
if(isset($_POST['image_2']))
{
$image_2 = $_FILES['image_2'];
}
if(isset($_POST['image_3']))
{
$image_3 = $_FILES['image_3'];
}
if(isset($_POST['image_4']))
{
$image_4 = $_FILES['image_4'];
}
if(isset($_POST['description']))
{
$description = sanitize($_POST)['description'];
}
$stmt->execute() or die(mysqli_error($db));
header('Location: products.php');
$stmt->close();
$conn->close();
}
?>
<form action="products.php?add=1" method="POST" enctype="multipart/form-data">
<div class='container_12'>
<div class="form-group col-md-3">
<label for="prod_name">Product Name*:</label>
<input type="text" name="prod_name" id="prod_name" class="form-control" value="<?=((isset($_POST['prod_name']))?sanitize($_POST['prod_name']):' ');?>">
</div>
<div class="form-group col-md-3">
<label for="parent">Parent Category*:</label>
<select class="form-control" id="parent" name="parent">
<option value=""<?=((isset($_POST['parent']) && $_POST['parent'] == '')?'selected':'');?>></option>
<?php while($parent = mysqli_fetch_assoc($parentQuery)): ?>
<option value=" <?=$parent['id'];?>"<?=((isset($_POST['parent']) && $_POST['parent'] == $parent['id'])?' select':'');?>><?=$parent['category_name'];?></option>
<?php endwhile; ?>
</select>
</div>
<div class='form-group col-md-3'>
<label for='child'>Second Category*:</label>
<select id='child' name='child' class='form-control'></select>
</div>
</div>
<div class='container_12'>
<div class='form-group col-md-3'>
<label for='list_price'>List Price(OPTIONAL): </label>
<input type="text" id="list_price" name="list_price" class="form-control" value="<?=((isset($_POST['list_price']))?sanitize($_POST['list_price']):'');?>">
</div>
<div class="form-group col-md-3">
<label for="price">Price*:</label>
<input type="text" id="price" name="price" class="form-control" value="<?=((isset($_POST['price']))?sanitize($_POST['price']):'');?>">
</div>
<div class='form-group col-md-3'>
<label for='prod_width'>Width* (in inches):</label>
<input type="text" id="prod_width" name="prod_width" class="form-control" value="<?=((isset($_POST['prod_width']))?sanitize($_POST['prod_width']):'');?>">
</div>
<div class='form-group col-md-3'>
<label for='prod_depth'>Height*(in inches):</label>
<input type="text" id="'prod_depth" name="'prod_depth" class="form-control" value="<?=((isset($_POST['prod_depth']))?sanitize($_POST['prod_depth']):'');?>">
</div>
</div>
<div class='container_12'>
<div class='form-group col-md-3'>
<label for='prod_height'>Depth*(in inches):</label>
<input type="text" id="prod_height" name="prod_height" class="form-control" value="<?=((isset($_POST['prod_height']))?sanitize($_POST['prod_height']):'');?>">
</div>
<div class='form-group col-md-3'>
<label for='prod_material'>Construction Material:</label>
<input type="text" id="prod_material" name="prod_material" class="form-control" value="<?=((isset($_POST['prod_material']))?sanitize($_POST['prod_material']):'');?>">
</div>
<div class='form-group col-md-6'>
<label>Quantity * :</label>
<input type="text" id="quantity" name="quantity" class="form-control" value="<?=((isset($_POST['quantity']))?sanitize($_POST['quantity']):'');?>">
</div>
</div>
<div class='container_12'>
<div class="form-group col-md-3"> <label for="image_1">Product Photo #1:</label>
<input type="file" name="image_1" id="image_1" class="form-control">
</div>
<div class="form-group col-md-3"> <label for="image_2">Product Photo #2:</label>
<input type="file" name="image_2" id="image_2" class="form-control">
</div>
<div class="form-group col-md-3"> <label for="image_3">Product Photo #3:</label>
<input type="file" name="image_3" id="image_3" class="form-control">
</div>
<div class="form-group col-md-3"> <label for="image_4">Product Photo#4:</label>
<input type="file" name="image_4" id="image_4" class="form-control">
</div>
</div>
<div class='container_12'>
<div class="form-group col-md-6">
<label for="description">Description:</label>
<textarea id="description" name="description" class="form-control" rows="6"><?=((isset($_POST['description']))?sanitize($_POST['description']):'');?></textarea>
</div>
<div class="form-group col-md-6">
<label for="care_instructions">Care Instructions*:</label>
<textarea id="care_instructions" name="care_instructions" class="form-control" rows="6"><?=((isset($_POST['care_instructions']))?sanitize($_POST['care_instructions']):'');?></textarea>
</div></div>
<div class='container_12'>
<div class="form-group pull-right">
<input type='submit' name='submit' value='Add Product' class='form-control btn-success pull-right'>
</div></div>
</form>
This is just to clarify one of the points in the comments above...
So I knocked up some test code to check what is going on...
<?php
$_POST['prod_name'] = 'fred';
function sanitize($thing){
var_dump("Inside Sanitize- ", $thing);
return $thing;
}
// Original Code - sends an array to sanitize
if(isset( $_POST['prod_name'] )) {
$prod_name = sanitize($_POST)['prod_name'];
}
var_dump('Original Version '.$prod_name);
// New Code 1 - Sends a String to sanitize
if(isset( $_POST['prod_name'] )) {
$prod_name = sanitize($_POST['prod_name']);
}
// New Code 2 - Should use this one, or could make this a function.
$prod_name = isset($_POST['prod_name'])? sanitize($_POST['prod_name']):'';
var_dump($prod_name);

Submit button won't work in PHP

PHP Code
<?php
if (!isset($_SESSION)) { session_start(); }
include "connect.php";
include "functions.php";
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
header('location: no_acces.php');
exit();
} else {
$id_user = $_SESSION['userid'];
$q_user = mysqli_query($conn, "SELECT * FROM users WHERE id = $id_user");
if (mysqli_num_rows($q_user) === 1) {
$r_user = mysqli_fetch_assoc($q_user);
} else {
unset($_SESSION['login']);
unset($_SESSION['userid']);
header('location: no_acces.php');
exit();
}
}
$error = "";
$userQuery = mysqli_query($conn, "SELECT username FROM users");
$user = mysqli_fetch_assoc($userQuery);
$id = $_GET['id'];
if (isset($_POST['edit_contact'])) {
$roepnaam = $_POST['roepnaam'];
$naam = $_POST['naam'];
$land = $_POST['land'];
$bedrijf = $_POST['bedrijf'];
$adres1 = $_POST['adres1'];
$adres2 = $_POST['adres2'];
$stad = $_POST['stad'];
$postcode = $_POST['postcode'];
$provincie = $_POST['provincie'];
$telefoon = $_POST['telefoon'];
$email = $_POST['email'];
$captcha= $_POST['g-recaptcha-response'];
if(!$captcha){
$error = "Er is een fout opgetreden";
}
if ($error == "") {
$insertUser = ("UPDATE address SET
roepnaam = '$roepnaam', naam = '$naam', bedrijf = '$bedrijf', telefoon = '$telefoon', email = '$email', adres1 = '$adres1', adres2 = '$adres2', stad = '$stad', postcode = '$postcode', provincie = '$provincie', land = '$land' WHERE id = $id");
if (mysqli_query($conn, $insertUser)) {
$_SESSION['edit_contact'] = true;
header('location: address_book.php');
} else {
$error = "Er is een fout opgetreden";
}
}
}
?>
HTML Code
<!DOCTYPE html>
<html lang="en">
<body>
<form action="" method="post">
<?php if ($error !== "") { ?>
<div class="row">
<div class="col-md-12 error">
<?php echo $error; ?>
</div>
</div>
<?php } ?>
<label for="firstName" class="control-label">Naam:</label>
<div class="row ">
<div class="col-md-6">
<input type="text" class="form-control" id="firstName" placeholder="Roepnaam" name="roepnaam" value="<?php if (isset($_POST['roepnaam'])) { echo $_POST['roepnaam']; } ?>" required/>
</div>
<div class="col-md-6">
<input type="text" class="form-control" id="lastName" placeholder="Naam" name="naam" value="<?php if (isset($_POST['naam'])) { echo $_POST['naam']; } ?>" required/>
</div>
</div>
<label for="username" class="control-label">Bedrijf:</label>
<div class="row ">
<div class="col-md-12">
<input type="text" class="form-control" id="username" placeholder="Bedrijf" name="bedrijf" value="<?php if (isset($_POST['bedrijf'])) { echo $_POST['bedrijf']; } ?>" required/>
</div>
</div>
<label for="password" class="control-label">Telefoonnummer:</label>
<div class="row ">
<div class="col-md-12">
<input type="text" class="form-control" id="password" placeholder="Telefoonnummer" name="telefoon" value="<?php if (isset($_POST['telefoon'])) { echo $_POST['telefoon']; } ?>" required/>
</div>
</div>
<label for="email" class="control-label">Email:</label>
<div class="row ">
<div class="col-md-12">
<input type="text" class="form-control" id="email" placeholder="E-mailadres" name="email" value="<?php if (isset($_POST['email'])) { echo $_POST['email']; } ?>" required/>
</div>
</div>
<label for="adres1" class="control-label">Adres:</label>
<div class="row">
<div class="col-md-12">
<input type="text" class="form-control" id="adres1" placeholder="Adres 1" name="adres1" value="<?php if (isset($_POST['adres1'])) { echo $_POST['adres1']; } ?>" required/>
</div>
</div>
<div class="row padding-top-10">
<div class="col-md-12">
<input type="text" class="form-control" id="adres2" placeholder="Adres 2" name="adres2" value="<?php if (isset($_POST['adres2'])) { echo $_POST['adres2']; } ?>"/>
</div>
</div>
<div class="row">
<div class="col-md-3">
<label for="postcode" class="control-label">Postcode:</label>
</div>
<div class="col-md-5">
<label for="city" class="control-label">Stad:</label>
</div>
<div class="col-md-4">
<label for="regio" class="control-label">Regio:</label>
</div>
</div>
<div class="row ">
<div class="col-md-3">
<input type="text" class="form-control" id="postcode" placeholder="Postcode" name="postcode" value="<?php if (isset($_POST['postcode'])) { echo $_POST['postcode']; } ?>" required/>
</div>
<div class="col-md-5">
<input type="text" class="form-control" id="city" placeholder="Stad" name="stad" value="<?php if (isset($_POST['stad'])) { echo $_POST['stad']; } ?>" required/>
</div>
<div class="col-md-4">
<input type="text" class="form-control" id="regio" placeholder="Provincie" name="provincie" value="<?php if (isset($_POST['provincie'])) { echo $_POST['provincie']; } ?>" required/>
</div>
</div>
<label for="land" class="control-label">Land:</label>
<div class="row ">
<div class="col-md-12">
<input type="text" class="form-control" id="password" placeholder="Land" name="land" value="<?php if (isset($_POST['land'])) { echo $_POST['land']; } ?>" required/>
</div>
</div>
<div class="row">
<div class="col-md-8 padding-top-10 ">
<div class="g-recaptcha " data-sitekey="6LcCsBoTAAAAAK72uzyJSrgWwD8xuF6jFIfgFaHX"></div>
</div>
</div>
<div class="row">
<div class="col-md-2 padding-top-10">
<input type="submit" name="edit_contact" class="btn btn-succes" value="Wijzigen">
</div>
<div class="col-md-2 padding-top-10">
<input type="text" name="delete_contact" action="delete_contact.php" class="btn btn-succes" value="Contact verwijderen">
</div>
</div>
</form>
</body>
</html>
PHP Code
<?php
if (!isset($_SESSION)) { session_start(); }
include "connect.php";
include "functions.php";
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true || !isset($_SESSION['userid']) || $_SESSION['userid'] == "") {
header('location: login.php');
exit();
} else {
session_regenerate_id();
}
$id = $_GET['id'];
$query = "DELETE FROM address WHERE id= $id";
mysqli_query ($query);
if (mysql_affected_rows() == 1) {
header('location: addressbook.php');
} else {
echo "Verwijderen mislukt";
}
?>
I'm trying to make a delete button for my contacts within the addressbook. but everytime I click "Contact verwijderen" the webpage resets it self and the contact won't be deleted. Could anyone help me to fix this?
You input is a text input and you don't have a form asociated with it,create one and change the type of submit to submit
<form action="delete_contact.php" method="post">
//other inputs
<input type="submit" name="delete_contact" class="btn btn-succes" value="Contact verwijderen">
</form>
You are mixing MySQL and MySQLi functions:
mysqli_query ($query);
if (mysql_affected_rows() == 1)
You cannot mix MySQL with MySQLi, your code should be:
mysqli_query ($query);
if (mysqli_affected_rows($conn) == 1)
Add a normal link to delete the contact, you don't need a form.
<a href="delete_contact.php?id=<?php echo $id ?>">
Contact verwijderen
</a>

reason why sqlstate[hy093] error is happening? when all conditions are met

i'm trying to figure out whats wrong with this code i got from this forum basically i was trying to modify it and see if i could solve this error above which has also come with an undefined index error.my question is why the errors because all seems to be fine and the binding is ok
if i replace the POST with the GET in the if(isset($_POST['btn-update'])) the error is gone but nothing is happening.im trying to understand why the above sqlstate[hy093] error and the undefined index error on $id = $_POST['edit_id']; which is defined in the crud function
public function getID($id)
{
$stmt = $this->db->prepare("SELECT * FROM tbl_users WHERE id=:id");
$stmt->execute(array(":id"=>$id));
$editRow=$stmt->fetch(PDO::FETCH_ASSOC);
return $editRow;
}
the binding in the crud class seems to be ok
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL);
class crud
{
private $db;
function __construct($DB_con)
{
$this->db = $DB_con;
}
public function create($fname,$lname,$employee_nrc,$Phone,$Businesstype,$Businesssite,$Businessactivity)
{
try
{
$stmt = $this->db->prepare("INSERT INTO tbl_users(first_name,last_name,employee_nrc, phone_no, business_type ,business_site ,business_activity) VALUES(:fname, :lname, :employee_nrc, :Phone, :Businesstype, :Businesssite, :Businessactivity)");
$stmt->bindparam(":fname",$fname);
$stmt->bindparam(":lname",$lname);
$stmt->bindparam(":employee_nrc",$employee_nrc);
$stmt->bindparam(":Phone",$Phone);
$stmt->bindparam(":Businesstype",$Businesstype);
$stmt->bindparam(":Businesssite",$Businesssite);
$stmt->bindparam(":Businessactivity",$Businessactivity);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
public function getID($id)
{
$stmt = $this->db->prepare("SELECT * FROM tbl_users WHERE id=:id");
$stmt->execute(array(":id"=>$id));
$editRow=$stmt->fetch(PDO::FETCH_ASSOC);
return $editRow;
}
public function update($id,$fname,$lname,$employee_nrc,$Phone,$Businesstype,$Businesssite,$Businessactivityt)
{
try
{
$stmt=$this->db->prepare("UPDATE tbl_users SET first_name=:fname,
last_name=:lname,
employee_nrc=:employee_nrc,
phone_no=:Phone,
business_type=:Businesstype,
business_site=:Businesssite,
business_activity=:Businessactivity
WHERE id=:id ");
$stmt->bindparam(":fname",$fname);
$stmt->bindparam(":lname",$lname);
$stmt->bindparam(":employee_nrc",$employee_nrc);
$stmt->bindparam(":Businesstype",$Phone);
$stmt->bindparam(":Businesstype",$Businesstype);
$stmt->bindparam(":Businesssite",$Businesssite);
$stmt->bindparam(":Businessactivity",$Businessactivity);
$stmt->bindparam(":id",$id);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
public function delete($id)
{
$stmt = $this->db->prepare("DELETE FROM tbl_users WHERE id=:id");
$stmt->bindparam(":id",$id);
$stmt->execute();
return true;
}
/* paging */
public function dataview($query)
{
$stmt = $this->db->prepare($query);
$stmt->execute();
if($stmt->rowCount()>0)
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<tr>
<td><?php print($row['id']); ?></td>
<td><?php print($row['first_name']); ?></td>
<td><?php print($row['last_name']); ?></td>
<td><?php print($row['employee_nrc']); ?></td>
<td><?php print($row['phone_no']); ?></td>
<td><?php print($row['business_type']); ?></td>
<td><?php print($row['business_site']); ?></td>
<td><?php print($row['business_activity']); ?></td>
<td align="center">
<i class="glyphicon glyphicon-edit"></i>
</td>
<td align="center">
<i class="glyphicon glyphicon-remove-circle"></i>
</td>
</tr>
<?php
}
}
else
{
?>
<tr>
<td>Nothing here...</td>
</tr>
<?php
}
}
public function paging($query,$records_per_page)
{
$starting_position=0;
if(isset($_GET["page_no"]))
{
$starting_position=($_GET["page_no"]-1)*$records_per_page;
}
$query2=$query." limit $starting_position,$records_per_page";
return $query2;
}
public function paginglink($query,$records_per_page)
{
$self = $_SERVER['PHP_SELF'];
$stmt = $this->db->prepare($query);
$stmt->execute();
$total_no_of_records = $stmt->rowCount();
if($total_no_of_records > 0)
{
?><ul class="pagination"><?php
$total_no_of_pages=ceil($total_no_of_records/$records_per_page);
$current_page=1;
if(isset($_GET["page_no"]))
{
$current_page=$_GET["page_no"];
}
if($current_page!=1)
{
$previous =$current_page-1;
echo "<li><a href='".$self."?page_no=1'>First</a></li>";
echo "<li><a href='".$self."?page_no=".$previous."'>Previous</a></li>";
}
for($i=1;$i<=$total_no_of_pages;$i++)
{
if($i==$current_page)
{
echo "<li><a href='".$self."?page_no=".$i."' style='color:red;'>".$i."</a></li>";
}
else
{
echo "<li><a href='".$self."?page_no=".$i."'>".$i."</a></li>";
}
}
if($current_page!=$total_no_of_pages)
{
$next=$current_page+1;
echo "<li><a href='".$self."?page_no=".$next."'>Next</a></li>";
echo "<li><a href='".$self."?page_no=".$total_no_of_pages."'>Last</a></li>";
}
?></ul><?php
}
}
/* paging */
}
the edit page where the undefined index error is occurring is $id = $_POST['edit_id'];
<?php
include_once 'dbconfig.php';
$first_name= null;
$last_name=null;
$employee_nrc=null;
$phone_no=null;
$business_type=null;
$business_site=null;
$business_activity=null;
if(isset($_POST['btn-update']))
{
$id = $_POST['edit_id'];
$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
$employee_nrc = $_POST['employee_nrc'];
$Phone = $_POST['phone_no'];
$Businesstype = $_POST['business_type'];
$Businesssite = $_POST['business_site'];
$Businessactivity = $_POST['business_activity'];
if($crud->update($id,$fname,$lname,$employee_nrc,$Phone,$Businesstype,$Businesssite,$Businessactivity))
{
$msg = "<div class='alert alert-info'>
<strong>WOW!</strong> Record was updated successfully <a href='index.php'>HOME</a>!
</div>";
}
else
{
$msg = "<div class='alert alert-warning'>
<strong>SORRY!</strong> ERROR while updating record !
</div>";
}
}
if(isset($_GET['edit_id']))
{
$id = $_GET['edit_id'];
extract($crud->getID($id));
}
?>
<?php include_once 'header.php'; ?>
<div class="clearfix"></div>
<div class="container">
<?php
if(isset($msg))
{
echo $msg;
}
?>
</div>
<div class="clearfix"></div><br />
<div class="container">
<form class="form-horizontal" method='post'>
<fieldset>
<legend>Registration System</legend>
<div class="form-group">
<label for="inputFirstName" class="col-lg-2 control-label">First Name</label>
<div class="col-lg-10">
<input type="text" name="first_name" class="form-control" value="<?php echo $first_name; ?>" required>
</div>
</div>
<div class="form-group">
<label for="inputLastName" class="col-lg-2 control-label">Last Name</label>
<div class="col-lg-10">
<input type="text" name="last_name" class="form-control" value="<?php echo $last_name; ?>" required>
</div>
</div>
<div class="form-group">
<label for="inputEmployeeNRC" class="col-lg-2 control-label">Employee NRC</label>
<div class="col-lg-10">
<input type="text" name="employee_nrc" class="form-control" value="<?php echo $employee_nrc; ?>" required>
</div>
</div>
<div class="form-group">
<label for="inputEmployeePhoneNumber" class="col-lg-2 control-label">Employee Phone Number</label>
<div class="col-lg-10">
<input type="text" name="phone_no" class='form-control' value="<?php echo $phone_no; ?>" required>
</div>
</div>
<div class="form-group">
<label for="inputEmployeePhoneNumber" class="col-lg-2 control-label">Business Type</label>
<div class="col-lg-10">
<input type="text" name="business_type" class='form-control' value="<?php echo $business_type; ?>" required>
</div>
</div>
<div class="form-group">
<label for="inputEmployeePhoneNumber" class="col-lg-2 control-label">Business Location</label>
<div class="col-lg-10">
<input type="text" name="business_site" class='form-control' value="<?php echo $business_site; ?>" required>
</div>
</div>
<div class="form-group">
<label for="inputEmployeePhoneNumber" class="col-lg-2 control-label">Business Activities</label>
<div class="col-lg-10">
<input type="text" name="business_activity" class='form-control' value="<?php echo $business_activity; ?>" required>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button type="submit" class="btn btn-primary" name="btn-update">
<span class="glyphicon glyphicon-edit"></span> Update this Record
</button>
<i class="glyphicon glyphicon-backward"></i> CANCEL
</div>
</div>
</fieldset>
</form>
</div>
<?php include_once 'footer.php'; ?>
help identify the mistake and advice doing this for learning purposes and i would appreciate ideas and solutions
there is a type which was later corrected on this code
$stmt->bindparam(":Businesstype",$Phone);
it was supposed to be
$stmt->bindparam(":Phone",$Phone);
thanks.

Categories