How to Populate fields using URL parametres in using php and mysql - php

I have a URL link, and upon clicking the link, it has to populate the fields as soon as the page is opened, below is the URL link and the form that has to be populated with few fields,fields such as names, idocode and email has to be populated, and the rest by the user and the submit button has no effect, what am I doing wrong,
URL: 'http://www.domain.com/register/registration.php?token=$token&stud_id=stud_id'
<?php
error_reporting(1);
session_start();
include 'includes/connect.php';
$student_id = $_GET["id"];
$_SESSION['student_id'] = $student_id;
$token = $_GET["tokenk"];
$_SESSION['token'] = $token;
if (isset($_GET["id"]) && isset($_GET["tk"])) {
$sql = "SELECT * FROM student WHERE student_id=" . $student_id . " and token='" . $token . "'";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if (!empty($result)) {
$sql = "UPDATE student SET first_name=:first_name, middle_name=:middle_name, last_name=:last_name WHERE student_id=:student_id";
$stmt->bindValue(':first_name', $first_name);
$stmt->bindValue(':middle_name', $middle_name);
$stmt->bindValue(':last_name', $last_name);
$stmt->bindValue(':student_id', $student_id);
$result = $stmt->execute();
} else {
}
}
if ($_POST["Submit"] == "Submit") {
//echo '<pre>';print_r($_POST["name"]);exit;
$ccode = $_POST["idode"];
$first_name = $_POST['first_name'];
$middle_name = $_POST['middle_name'];
$last_name = $_POST['last_name'];
$course = $_POST["course"];
$email = $_POST['email'];
$password = $_POST["password"];
$confirm_password = $_POST["confirm_password"];
//echo "<br/>In post"; die();
//echo $name.'>>>>'.$email.'>>>>'.$idcode;exit;
add_student_session($_POST);
$validate = add_student_validator($_POST);
//echo '<pre>';print_r($validate);exit;
if (isset($validate) && $validate) {
//echo "<br/>Validated: TRUE<br/>"; die();
$sql = "SELECT COUNT(*) AS num FROM student WHERE student_id = :student_id";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':idcode', $idcode);
$stmt->bindValue(':first_name', $first_name);
$stmt->bindValue(':middle_name', $middle_name);
$stmt->bindValue(':last_name', $last_name);
$stmt->bindValue(':course', $course);
$stmt->bindValue(':date_of_birth', $date_of_birth);
$stmt->bindValue(':email', $email);
$stmt->bindValue(':password', $password);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row['num'] > 0) {
$_SESSION["already_exist"] = TRUE;
} else {
//echo "<br/>Validated: FALSE<br/>"; die();
$sql = "INSERT INTO student (course, date_of_birth, password) VALUES (:course, :date_of_birth, :password)";
$stmt = $pdo->prepare($sql);
//echo "<br/>CCODE: ".$idcode;exit;
$stmt->bindValue(':course', $course);
$stmt->bindValue(':date_of_birth', $date_of_birth);
$stmt->bindValue(':password', $password);
$stmt->bindValue(':confirm_password', $confirm_password);
if ($_POST["password"] != $_POST["confirm_password"]) {
echo 'passwords do not match';
}
$result1 = $stmt->execute();
//echo $result ;exit;
if ($result1) {
echo '<div><p class="text-success">Created Successfully!</p></>';
}
clear_session();
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Register</title>
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css"/>
<link rel="stylesheet" href="css/bootstrap.min.custom.css" type="text/css"/>
<script src="js/bootstrap.min.js"></script>
<script language="javascript" src="js/calendar.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="Absolute-Center is-Responsive">
<div class="col-md-10 col-md-offset-2 well">
<form class="form-horizontal" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"
role="form">
<legend>Registration</legend>
<div class="form-group">
<label for="name" class="col-xs-2 control-label">CCODE:</label>
<div class="col-xs-10">
<input class="form-control" type="text" name="idcode" required
placeholder="CCODE/EMPLOYEE CODE/ ID CODE"
value="<?php echo #$_POST['idcode']; ?>" readonly/>
<label for="idcode" generated="true" class="error">
<?= isset($error_hash["idcode"]) ? $error_hash["idcode"] : "" ?>
</label>
</div>
</div>
<div class="form-group">
<label for="birthday" class="col-xs-2 control-label">Name:</label>
<div class="col-xs-10">
<div class="form-inline">
<div class="form-group">
<input class="form-control" type="text" name="first_name" required
placeholder="First Name"
value="<?php echo #$_POST['first_name']; ?>"/>
<label for="first_name" generated="true" class="error">
<?= isset($error_hash["first_name"]) ? $error_hash["first_name"] : "" ?>
</label>
</div>
<div class="form-group">
<input class="form-control" type="text" name="middle_name" required
placeholder="Middle Name"
value="<?php echo #$_POST['middle_name']; ?>"/>
<label for="middle_name" generated="true" class="error">
<?= isset($error_hash["middle_name"]) ? $error_hash["middle_name"] : "" ?>
</label>
</div>
<div class="form-group">
<input class="form-control" type="text" name="last_name" required
placeholder="Last Name" value="<?php echo #$_POST['last_name']; ?>"/>
<label for="middle_name" generated="true" class="error">
<?= isset($error_hash["last_name"]) ? $error_hash["last_name"] : "" ?>
</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="name" class="col-xs-2 control-label">Designation:</label>
<div class="col-xs-10">
<input class="form-control" type="text" name="course" required
placeholder="Designation"
value="<?= isset($_SESSION["course"]) ? $_SESSION["course"] : ""; ?>"/>
<label for="course" generated="true" class="error">
<?= isset($error_hash["course"]) ? $error_hash["course"] : "" ?>
</label>
</div>
</div>
<div class="form-group">
<label for="name" class="col-xs-2 control-label">Date-Of-Birth:</label>
<div class="col-xs-8">
<select name="dd">
<option value="">Date</option>
<?php
for ($i = 1; $i <= 31; $i++) {
echo "<option value='$i'>" . $i . "</option>";
}
?>
</select>
<select name="mm">
<option value="">Month</option>
<?php
for ($i = 1; $i <= 12; $i++) {
echo "<option value='$i'>" . $i . "</option>";
}
?>
</select>
<select name="yy">
<option value="">Year</option>
<?php
for ($i = 1960; $i <= 2020; $i++) {
echo "<option value='$i'>" . $i . "</option>";
}
?>
</select>
</div>
</div>
<div class="form-group">
<label for="name" class="col-xs-2 control-label">Email:</label>
<div class="col-xs-10">
<input class="form-control" type="email" name="email" required placeholder="Email"
value="<?php echo #$_POST['email']; ?>" readonly/>
<label for="email" generated="true" class="error">
<?= isset($error_hash["email"]) ? $error_hash["email"] : "" ?>
</label>
</div>
</div>
<div class="form-group">
<label for="name" class="col-xs-2 control-label">Password:</label>
<div class="col-xs-10">
<input class="form-control" type="password" name="password" required
placeholder="Password"
value="<?= isset($_SESSION["password"]) ? $_SESSION["password"] : ""; ?>"/>
<label for="name" generated="true" class="error">
<?= isset($error_hash["password"]) ? $error_hash["password"] : "" ?>
</label>
</div>
</div>
<div class="form-group">
<label for="name" class="col-xs-2 control-label">Confirm Password:</label>
<div class="col-xs-10">
<input class="form-control" type="password" name="confirm_password" required
placeholder="Confirm Password"
value="<?= isset($_SESSION["confirm_password"]) ? $_SESSION["confirm_password"] : ""; ?>"/>
<label for="name" generated="true" class="error">
<?= isset($error_hash["confirm_password"]) ? $error_hash["confirm_password"] : "" ?>
</label>
</div>
</div>
</form>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="form-actions">
<input type="submit" name="Submit" value="Submit" class="btn btn-primary"/>
</div>
<br>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</html>

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

For loop showing only the final result

I have the following PHP query:
<?php
$row='';
$access = 0;
$user = (isset($_POST['nume']) && !empty($_POST['nume'])) ? $_POST['nume'] : "" ;
$email = (isset($_POST['email']) && !empty($_POST['email'])) ? $_POST['email'] : "" ;
$telefon = (isset($_POST['telefon']) && !empty($_POST['telefon'])) ? $_POST['telefon'] : "" ;
$cnp = (isset($_POST['cnp']) && !empty($_POST['cnp'])) ? $_POST['cnp'] : "" ;
$serieci = (isset($_POST['serieci']) && !empty($_POST['serieci'])) ? $_POST['serieci'] : "" ;
$mesaj = (isset($_POST['mesaj']) && !empty($_POST['mesaj'])) ? $_POST['mesaj'] : "" ;
$email_status=1;
$db = pg_connect("host=local port=5432 dbname=login_robinson user=robinson password=123");
$query = "INSERT INTO tcheckin(nume,email,telefon,cnp,serieci,mesaj) VALUES ('$user','$email','$telefon','$cnp','$serieci','$mesaj')";
$result = pg_query($query);
$test=$_SESSION[PRE.'nume'];
$test1=$_SESSION[PRE.'uid'];
?>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<link href="https://fonts.googleapis.com/css?family=Playfair+Display:400,700,900|Rubik:300,400,700" rel="stylesheet">
<title>Efectueaza check-in</title>
<?php
include('include/links.php');
include('include/scripts.php');
?>
</head>
<?php
$i=1;
$conn = pg_connect("host=local port=5432 dbname=login_robinson user=robinson password=123");
$test1=$_SESSION[PRE.'uid'];
$result = pg_query($conn, "SELECT nume FROM tregister WHERE id = '$test1'");
if (!$result) {
echo "An error occurred.\n";
exit;
}
$row = pg_fetch_row($result);
$result1 = pg_query($conn, "SELECT nr_camere FROM tregister WHERE nume = '$user'");
if (!$result1) {
echo "An error occurred.\n";
exit;
}
$camere = pg_fetch_row($result1);
echo $row[0];
for($i=1; $i<$camere[0]; $i++){
if(isset($_POST['submit'])){
echo "<script>
alert('Check-in efectuat cu success! Daca ai rezervat mai multe camere te rog sa completezi si check-in-ul pentru celelalte camere.');
window.location.href='acasa';
</script>";
echo "<script>
alert('S-a produs o eroare! Te rog mai verifica odata formularul!');
</script>";
}
}
?>
<body style="display: block !important;" ng-cloak="" ng-class="{ 'layout-fixed' : app.layout.isFixed, 'layout-boxed' : app.layout.isBoxed, 'layout-dock' : app.layout.isDocked, 'layout-material': app.layout.isMaterial, 'aside-offscreen' : app.sidebar.isOffscreen, 'aside-mini' : app.sidebar.isMini, 'aside-right' : app.sidebar.isRight, 'footer-hidden': app.footer.hidden, 'in-app': !$state.includes('page')}">
<div class="animated fadeOutZoom">
<div class="container container-sm animated fadeInDown">
<div class="app-view-header">Bine ai venit, <?php echo $row[0]; ?>!</div>
<div class="center-block mt-xl">
<div class="panel">
<div class="panel-body">
<p class="pv text-bold">Check-in pentru camera cu numarul <?php echo $i; ?></p>
<form action="#" method="post">
<div class="row">
<div class="col-md-12 form-group">
<label for="nume">Nume</label>
<input type="text" id="text " value=" <?php echo $row[0]; ?>" class="form-control " name="nume" disabled="disabled">
</div>
</div>
<div class="row">
<div class="col-md-12 form-group">
<label for="telefon">Telefon</label>
<input type="phone" id="telefon " class="form-control " name="telefon" required>
</div>
</div>
<div class="row">
<div class="col-md-12 form-group">
<label for="email">Email</label>
<input type="email" id="email" class="form-control " name="email" required>
</div>
</div>
<div class="row">
<div class="col-md-12 form-group">
<label for="cnp">CNP</label>
<input type="text" id="text " class="form-control "name="cnp" required>
</div>
</div>
<div class="row">
<div class="col-md-12 form-group">
<label for="serie">Serie de buletin</label>
<input type="text" id="text " class="form-control " name="serieci" required>
</div>
</div>
<div class="row">
<div class="col-md-12 form-group">
<label for="message">Scrie un mesaj *Optional</label>
<textarea name="mesaj" id="message" class="form-control " cols="5" rows="4"></textarea>
</div>
</div>
<div class="row">
<div class="col-md-6 form-group">
<input type="submit" value="Rezerva acum" class="btn btn-primary" name="submit">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/js/bootstrap-datepicker.min.js"></script>
<script>
$('#arrival_date, #departure_date').datepicker({format: 'dd/mm/yyyy'});
</script>
</body>
</html>
<?php
ob_end_flush();
?>
What I want to do it's to see a page for a number of times. For example, if a user selected 4 rooms, I need make the check-in process 4 times, once for each room, I tried with a for loop but it's showing only the final result..what can I do? It's a little bit weird, I tried also with a while but still doesn't work..

Unable to add data into database in php

<?php
if(isset($_POST["submit"]))
if (!empty($_FILES["uploadImage"]["name"])) {
//Including dbconfig file.
require 'config.php';
$ImageSavefolder = "images/student/";
move_uploaded_file($_FILES["uploadImage"]["tmp_name"] ,
"$ImageSavefolder".$_FILES["uploadImage"]["name"]);
$name = mysqli_real_escape_string($conn, $_POST['name']);
$fathername = mysqli_real_escape_string($conn, $_POST['fathername']);
$htno = mysqli_real_escape_string($conn, $_POST['htno']);
$phoneno = mysqli_real_escape_string($conn, $_POST['phoneno']);
$department = mysqli_real_escape_string($conn, $_POST['department']);
$class = mysqli_real_escape_string($conn, $_POST['class']);
$address = mysqli_real_escape_string($conn, $_POST['address1']);
$address2 = mysqli_real_escape_string($conn, $_POST['address2']);
$city = mysqli_real_escape_string($conn, $_POST['city']);
$state = mysqli_real_escape_string($conn, $_POST['state']);
$zip = mysqli_real_escape_string($conn, $_POST['zip']);
$sql= "INSERT INTO student_detail(name,fathername,htno,phoneno,department,class,address1,address2,city,state,zip) VALUES ('$name','$fathername','$htno','$phoneno','$department','$class','$address','$address2','$city','$state','$zip','".$_FILES['uploadImage']['name']."')";
if(!mysqli_query($conn,$sql))
{
echo "Not Updated";
}
else
{
echo "<br><div class='alert alert-success' role='alert'>Added Sucessfully !</div>";
}
}
?>
This code is not working for adding the following data into database. Did I do anything wrong? Please help me sort the problem.
I already created database with config.php
Form Data
<form method="post" action="" enctype="multipart/form-data">
<div class="form-row">
<div class="form-group col-md-6">
<label for="name">Name</label>
<input type="text" class="form-control" placeholder="Please Enter Name" name="name">
</div>
<div class="form-group col-md-6">
<label for="fathername">Father's Name</label>
<input type="text" class="form-control" placeholder="Please Enter Father's Name" name="fathername">
</div>
<div class="form-group col-md-6">
<label for="htno">Hall Ticket/ Roll No.</label>
<input type="text" class="form-control" placeholder="Please Enter Hall Ticket/ Roll No." name="htno">
</div>
<div class="form-group col-md-6">
<label for="phoneno">Phone Number</label>
<input type="text" class="form-control" placeholder="Please Enter Phone No." name="phoneno">
</div>
<div class="form-group col-md-6">
<label for="department">Department</label>
<select class="form-control" name="department">
<option selected="selected">Choose your Department</option>
<?php
require('config.php');
$result = mysqli_query($conn,"SELECT * FROM department");
while($test= mysqli_fetch_array($result))
{
echo "<option value='".$test['department_name']."'>".$test['department_name']."</option>";
}
?>
</select>
</div>
<div class="form-group col-md-6">
<label for="class">Class</label>
<select class="form-control" name="class">
<option selected="selected">Choose your Class</option>
<?php
require('config.php');
$result = mysqli_query($conn,"SELECT * FROM class");
while($test= mysqli_fetch_array($result))
{
echo "<option value='".$test['class_name']."'>".$test['class_name']."
</option>";
}
?>
</select>
</div>
</div>
<div class="form-group">
<label for="address">Address</label>
<input type="text" class="form-control" placeholder="House No./Flat No." name="address1">
</div>
<div class="form-group">
<label for="address2">Address 2 (Optional)</label>
<input type="text" class="form-control" placeholder="Locality/Area/Street" name="address2">
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="city">City</label>
<input type="text" class="form-control" name="city">
</div>
<div class="form-group col-md-4">
<label for="state">State</label>
<select class="form-control" name="state">
<option selected="selected"name="bihar">bihar</option>
<option>...</option>
</select>
</div>
<div class="form-group col-md-2">
<label for="zip">Zip</label>
<input type="text" class="form-control" name="zip">
</div>
<div class="form-group col-md-6">
<label for="profile">Profile Pic</label><br>
<input type="file" accept="image/*" onchange="loadFile(event)" name="uploadImage" id="uploadImage">
<img id="output" style="width:20%;"/>
<script>
var loadFile = function(event) {
var reader = new FileReader();
reader.onload = function(){
var output = document.getElementById('output');
output.src = reader.result;
};
reader.readAsDataURL(event.target.files[0]);
};
</script>
</div>
</div>
<button type="submit" name="submit" class="btn btn-primary">Submit</button>
</form>
you are trying to insert extra value which is not exist in query see here.
your field
(name,fathername,htno,phoneno,department,class,address1,address2,city,state,zip)
and your values
('$name','$fathername','$htno','$phoneno','$department','$class','$address','$address2','$city','$state','$zip','".$_FILES['uploadImage']['name']."')
you need to do add image field also
your full query
$sql= "INSERT INTO student_detail(name,fathername,htno,phoneno,department,class,address1,address2,city,state,zip,imageFieldName) VALUES ('$name','$fathername','$htno','$phoneno','$department','$class','$address','$address2','$city','$state','$zip','".$_FILES['uploadImage']['name']."')";
<?php
/* dbconnection.php file
$conn = mysqli_connect("localhost","root","12345") or die (mysqli_error());
mysqli_select_db($conn,"student") or die (mysqli_error());
*/
//Including dbconnection file here
include('dbconnection.php');
if(isset($_POST["submit"]))
{
if (!empty($_FILES["uploadImage"]["name"]))
{
$ImageSavefolder = "images/student/";
$name = $_FILES["uploadImage"]["name"];
$tmp_name = $_FILES["uploadImage"]["tmp_name"];
move_uploaded_file(tmp_name, $ImageSavefolder.$name);
$sql = "INSERT INTO students (name,fathername,htno,phoneno,department,class,address1,address2,city,state,zip,image) VALUES ('".$_POST["name"]."','".$_POST["fathername"]."','".$_POST["htno"]."','".$_POST["phoneno"]."','".$_POST["department"]."','".$_POST["class"]."','".$_POST["address1"]."','".$_POST["address2"]."','".$_POST["city"]."','".$_POST["state"]."','".$_POST["zip"]."','".$name."')";
if ($conn->query($sql) === TRUE)
{
echo "<script type= 'text/javascript'>alert('Record Inserted Successfully');</script>";
}
else
{
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>";
}
}
}
?>

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>

Categories