I've been testing a CRUD interface with PHP and SQLSRV driver but i got stuck on the creating part, i can read the data that alredy was added on the database by id, but i cant get to work the create data from PHP to the database, when i press the create Button it clears the inputs and shows the errors. Would like to know if there is something wrong with my code so far.
PHP CODE:
<?php
require 'database.php';
if ( !empty($_POST)) {
$iError = null;
$nError = null;
$dError = null;
$tError = null;
$id = $_POST['id'];
$name = $_POST['name'];
$Address = $_POST['Address'];
$phone = $_POST['phone'];
$valid = true;
if (empty($id)) {
$iError = 'add id';
$valid = false;
}
if (empty($name)) {
$nError = 'add name';
$valid = false;
}
if (empty($Address)) {
$dError = 'add address';
$valid = false;
}
if (empty($phone)) {
$tError = 'add phone';
$valid = false;
}
if ($valid) {
$tsql = "INSERT INTO dbo.TEST1 (id, name, Address, phone) values(?, ?, ?, ?)";
$arr1 = array($id, $name, $Address, $phone);
$stmt = sqlsrv_query($conn, $tsql, $arr1 );
if ( $stmt === FALSE ){
echo "New data created";
}
else {
echo "Error creating data";
die(print_r(sqlsrv_errors(),true));
}
}
}?>`
this is the HTML part:
<body>
<div>
<div>
<h3>CREAR</h3>
</div>
<form class="form-horizontal" action="create.php" method="post">
<div class=" <?php echo !empty($iError)?'error':'';?>">
<label >ID</label>
<div >
<input name="name" type="text" placeholder="ID" value="<?php echo !empty($id)?$id:'';?>">
<?php if (!empty($iError)): ?>
<span ><?php echo $iError;?></span>
<?php endif; ?>
</div>
</div>
<div class=" <?php echo !empty($nError)?'error':'';?>">
<label>name</label>
<div>
<input name="name" type="text" placeholder="name" value="<?php echo !empty($name)?$name:'';?>">
<?php if (!empty($nError)): ?>
<span><?php echo $nError;?></span>
<?php endif; ?>
</div>
</div>
<div class=" <?php echo !empty($emailError)?'error':'';?>">
<label >Address</label>
<div >
<input name="email" type="text" placeholder="Address" value="<?php echo !empty($Address)?$Address:'';?>">
<?php if (!empty($dError)): ?>
<span><?php echo $dError;?></span>
<?php endif;?>
</div>
</div>
<div class=" <?php echo !empty($tError)?'error':'';?>">
<label >phoner</label>
<div >
<input name="mobile" type="text" placeholder="phone" value="<?php echo !empty($phone)?$phone:'';?>">
<?php if (!empty($tError)): ?>
<span ><?php echo $tError;?></span>
<?php endif;?>
</div>
</div>
<div >
<button type="submit">Create</button>
Return
</div>
</form>
</div>
</div>
Related
I will describe my problems briefly. There are 2 main issues in my web app:
Date of Birth does not show in the edit page (DONE)
I cannot submit my record to the database (partly due to problem 1)
Here is my code:
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "students";
$mysqli = new mysqli($host, $username, $password, $database);
if (!$mysqli) {
die("Cannot connect to mysql");
}
if (isset($_POST['save'])) {
// Display errors if all fields are blank
$errors = [];
if (strlen(trim($_POST['student_id'])) === 0) {
$errors['student_id'] = "Không được để trống trường này";
}
if (strlen(trim($_POST['first_name'])) === 0) {
$errors['first_name'] = "Không được để trống trường này";
}
if (strlen(trim($_POST['last_name'])) === 0) {
$errors['last_name'] = "Không được để trống trường này";
}
if (strlen(trim($_POST['email'])) === 0) {
$errors['email'] = "Không được để trống trường này";
} else {
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Email phải đúng định dạng';
}
}
if (strlen(trim($_POST['dob'])) === 0) {
$errors['dob'] = "Không được để trống trường này";
}
}
// If there is not any black field, show the information at the index page
$id = $_GET['id'];
$sql = "SELECT * FROM students WHERE id = $id";
$result = $mysqli->query($sql);
$students = $result->fetch_assoc();
print_r($students) ;
if (isset($errors) && count($errors) == 0) {
$student_id = $_POST['student_id'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$dob = $_POST['dob'];
$sql = "UPDATE students(student_id, first_name, last_name, email, dob)
SET student_id = '$student_id', first_name = '$first_name', last_name = '$last_name', email = '$email', dob = '$dob'
WHERE id = '$id'";
$result = $mysqli->query($sql);
if ($result) {
header('location: index.php');
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Student List</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
</head>
<body>
<div class="card">
<div class="card-body">
<h3 class="card-title">Create Student</h3>
<form method="POST" action="./update.php" id="update">
<!-- Student ID -->
<div class="form-group">
<label for="student_id">Student ID <span style="color:red;">*</span></label>
<input type="text" id="student_id" name="student_id" class="form-control <?php echo isset($errors['student_id']) ? 'is-invalid' : '' ?>" placeholder="" value="<?php echo $students['student_id'] ?>">
<?php if (isset($errors) && isset($errors['student_id'])) { ?>
<small id="helpId" class="invalid-feedback"><?php echo $errors['student_id']; ?></small>
<?php } ?>
</div>
<!-- First Name -->
<div class="form-group">
<label for="first_name">First Name <span style="color:red;">*</span></label>
<input type="text" id="first_name" name="first_name" class="form-control <?php echo isset($errors['first_name']) ? 'is-invalid' : '' ?>" placeholder="" value="<?php echo $students['first_name'] ?> ">
<?php if (isset($errors) && isset($errors['first_name'])) { ?>
<small id="helpId" class="invalid-feedback"><?php echo $errors['first_name']; ?></small>
<?php } ?>
</div>
<!-- Last Name -->
<div class="form-group">
<label for="last_name">Last name <span style="color:red;">*</span></label>
<input type="text" id="last_name" name="last_name" class="form-control <?php echo isset($errors['last_name']) ? 'is-invalid' : '' ?>" placeholder="" value="<?php echo $students['last_name'] ?>">
<?php if (isset($errors) && isset($errors['last_name'])) { ?>
<small id="helpId" class="invalid-feedback"><?php echo $errors['last_name']; ?></small>
<?php } ?>
</div>
<!-- Email -->
<div class="form-group">
<label for="email">Email <span style="color:red;">*</span></label>
<input type="email" id="email" name="email" class="form-control <?php echo isset($errors['email']) ? 'is-invalid' : '' ?>" placeholder="" value="<?php echo $students['email'] ?> ">
<?php if (isset($errors) && isset($errors['email'])) { ?>
<small id="helpId" class="invalid-feedback"><?php echo $errors['email']; ?></small>
<?php } ?>
</div>
<!-- Date of Birth -->
<div class="form-group">
<label for="dob">Date of Birth <span style="color:red;">*</span></label>
<input type="date" id="dob" name="dob" class="form-control <?php echo isset($errors['dob']) ? 'is-invalid' : '' ?>" placeholder="" value="<?php echo $students['dob'] ?> ">
<?php if (isset($errors) && isset($errors['dob'])) { ?>
<small id="helpId" class="invalid-feedback"><?php echo $errors['dob']; ?></small>
<?php } ?>
</div>
<!-- Buttons -->
<button type="submit" class="btn btn-primary" name="save">Save</button>
<a class="btn btn-secondary" href="./index.php">Cancel</a>
</form>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/js/bootstrap.min.js" integrity="sha384-+YQ4JLhjyBLPDQt//I+STsc9iw4uQqACwlvpslubQzn4u2UU2UFM80nGisd026JF" crossorigin="anonymous"></script>
</body>
</html>
Here is some pictures about those:
Hopefully, you can help me solve those problems as much as possible. Thank you!
The date of birth issue: extra space at the end of your value tag
value="<?php echo $students['dob'] ?> "
The database issues:
malformed update statement
insecure, open-to-attack query
You kind of mixed insert and update.
UPDATE students(student_id, first_name, last_name, email, dob)
SET student_id = '$student_id', first_name = '$first_name', last_name = '$last_name', email = '$email', dob = '$dob'
WHERE id = '$id'
Update statements don't take a field list in parens like you have it.
So the statement is failing. However you should really protect again SQL injection attacks by using query binding and prepared statements. Looks like this:
$sql = "UPDATE students SET student_id = '?', first_name = '?', last_name = '?', email = '?', dob = '?' WHERE id = '?'";
$query = $mysqli->prepare($sql);
$query->bind_param("isssi", $student_id, $first_name, $last_name, $email, $dob, $id);
$query->execute();
https://www.w3schools.com/php/php_mysql_prepared_statements.asp
I've been fiddling with this for hours and cant figure out why the $_GET statements perform correctly, but the $_POST statements don't.
IF $stock is in dB, show values in the form, and if the form is submitted submit UPDATE those values, IF $stock is NOT in dB and the form is submitted INSERT into table. Neither $_POST statement seems to work, yet are not throwing any errors, just redirecting back to the same page when you hit the submit button.
include_once ('../helper_content/sql_Connect.php');
$error = array();
$KBB_Low = "";
$KBB_High = "";
$KBB_Fair = "";
$KBB_Retail = "";
$KBB_URL = "";
$TrueCar_Great = "";
$TrueCar_Average = "";
$TrueCar_Above = "";
$TrueCar_URL = "";
$NADA_Trade = "";
$NADA_Loan = "";
$NADA_Retail = "";
# Was the form submitted via POST?
if(isset($_POST['Submit'])) {
# Yes
# Is this a new stock item?
if(empty($_POST['stock'])) {
# Yes - insert
$kbb_low = filter_var($_POST['kbb_low'], FILTER_SANITIZE_STRING);
$kbb_high = filter_var($_POST['kbb_high'], FILTER_SANITIZE_STRING);
$kbb_fair = filter_var($_POST['kbb_fair'], FILTER_SANITIZE_STRING);
$kbb_retail = filter_var($_POST['kbb_retail'], FILTER_SANITIZE_STRING);
$kbb_url = filter_var($_POST['kbb_url'], FILTER_SANITIZE_STRING);
$truecar_great = filter_var($_POST['truecar_great'], FILTER_SANITIZE_STRING);
$truecar_average = filter_var($_POST['truecar_average'], FILTER_SANITIZE_STRING);
$truecar_above = filter_var($_POST['truecar_above'], FILTER_SANITIZE_STRING);
$truecar_url = filter_var($_POST['truecar_url'], FILTER_SANITIZE_STRING);
$nada_trade = filter_var($_POST['nada_trade'], FILTER_SANITIZE_STRING);
$nada_loan = filter_var($_POST['nada_loan'], FILTER_SANITIZE_STRING);
$nada_retail = filter_var($_POST['nada_retail'], FILTER_SANITIZE_STRING);
if ($stmt = $conn->prepare("INSERT INTO `Inventory_Valuations` (`stock`,
`kbb_low`, `kbb_high`, `kbb_fair`, `kbb_retail`, `kbb_url`,
`truecar_great`, `truecar_average`, `truecar_above`, `truecar_url`,
`nada_trade`, `nada_loan`, `nada_retail`
) VALUES (?,?,?,?,?,?)")) {
$stmt->bind_param('iiiisiiisiii', $stock,
$kbb_low, $kbb_high, $kbb_fair, $kbb_retail, $kbb_url,
$truecar_great, $truecar_average, $truecar_above, $truecar_url,
$nada_trade, $nada_loan, $nada_retail
);
if ($stmt->execute()) {
$stmt->close();
header('Location: ./?inserted=true');
exit();
} else {
$error[] = "Error adding: " . $stmt->error;
$stmt->close();
}
}
} else {
# No - update
$stock = $_POST['stock'];
$kbb_low = $_POST['kbb_low'];
$kbb_high = $_POST['kbb_high'];
$kbb_fair = $_POST['kbb_fair'];
$kbb_retail = $_POST['kbb_retail'];
$kbb_url = $_POST['kbb_url'];
$truecar_great = $_POST['truecar_great'];
$truecar_average = $_POST['truecar_average'];
$truecar_above = $_POST['truecar_above'];
$truecar_url = $_POST['truecar_url'];
$nada_trade = $_POST['nada_trade'];
$nada_loan = $_POST['nada_loan'];
$nada_retail = $_POST['nada_retail'];
/*... get variables from the $_POST array */
if ($stmt = $conn->prepare("UPDATE `Inventory_Valuations` SET
kbb_low=?, kbb_high=?, kbb_fair=?, kbb_retail=?, kbb_url=?,
truecar_great=?, truecar_average=?, truecar_above=?, truecar_url=?,
nada_trade=?, nada_loan=?, nada_retail=?
WHERE stock=?")) {
$stmt->bind_param('iiiisiiisiii',
$kbb_low, $kbb_high, $kbb_fair, $kbb_retail, $kbb_url,
$truecar_great, $truecar_average, $truecar_above, $truecar_url,
$nada_trade, $nada_loan, $nada_retail,
$stock);
if ($stmt->execute()) {
$stmt->close();
header('Location: ./?updated=true');
exit();
}
else {
$error[] = "Error updating: " . $stmt->error;
$stmt->close();
}
}
}
}
else {
# No - assume a GET
$status = 'Active';
$stock = $_GET['stock'];
$cat = $_GET['cat'];
if(isset($_GET['updated'])) {
$message = "Record updated";
}
else if(isset($_GET['inserted'])) {
$message = "Record added into database";
}
if($stock != "") {
# Load the item?
$query = "SELECT * FROM `Inventory_Valuations` WHERE stock=?";
$stmt = $conn->prepare($query);
$stmt->bind_param('i', $stock);
if($stmt->execute()) {
$result = $stmt->get_result();
if($result) {
$row = $result->fetch_assoc();
$KBB_Low = $row['kbb_low'];
$KBB_High = $row['kbb_high'];
$KBB_Fair = $row['kbb_fair'];
$KBB_Retail = $row['kbb_retail'];
$KBB_URL = $row['kbb_url'];
$TrueCar_Great = $row['truecar_great'];
$TrueCar_Average = $row['truecar_average'];
$TrueCar_Above = $row['truecar_above'];
$TrueCar_URL = $row['truecar_url'];
$NADA_Trade = $row['nada_trade'];
$NADA_Loan = $row['nada_loan'];
$NADA_Retail = $row['nada_retail'];
}
}
$stmt->close();
}
}
?>
<?php if(isset($message)) : ?>
<div class="alert alert-success">
<?= $message ?>
</div>
<?php endif; ?>
<?php if(isset($error)) : ?>
<div class="alert alert-danger">
<ul>
<?php foreach($error as $err): ?>
<li><?= $err ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>?cat=Sales&stock=<?= $stock; ?>">
<section class="valuations">
<h3>Valuations</h3>
<input type="hidden" name="stock" value="<?= $stock; ?>">
<div>
<a target="_blank" href="<?=$KBB_Link; ?>"><img src="images/logos/KBB.png"></a>
<p>
<label for="kbb_low">Fair Market Range</label>
<input type="number" class="dollars" id="kbb_low" name="kbb_low" placeholder="Low" value="<?= $KBB_Low; ?>"> -
<input type="number" class="dollars" id="kbb_high" name="kbb_high" placeholder="High" value="<?= $KBB_High; ?>">
</p>
<p>
<label for="kbb_fair">Fair Price</label>
<input type="number" class="dollars" id="kbb_fair" name="kbb_fair" placeholder="Fair" value="<?= $KBB_Fair; ?>">
</p>
<p>
<label for="kbb_retail">Sug. Retail</label>
<input type="number" class="dollars" id="kbb_retail" name="kbb_retail" placeholder="Retail" value="<?= $KBB_Retail; ?>">
</p>
<p class="clear">
<label for="kbb_url">Report URL</label>
<input type="url" id="kbb_url" name="kbb_url" size="20" spellcheck="false" placeholder="www.kbb.com/" value="<?= $KBB_URL; ?>">
<i title="Copy KBB URL" data-clipboard-target="#kbb_url" data-clipboard-action="copy" class="fa fa-clipboard" aria-hidden="true"></i>
</p>
</div>
<div>
<img src="images/logos/TrueCar.png">
<p><label for="truecar_great">Great Price</label> <input type="number" class="dollars" id="truecar_great" name="truecar_great" placeholder="Great" value="<?= $TrueCar_Great; ?>"></p>
<p><label for="truecar_average">Average Price</label> <input type="number" class="dollars" id="truecar_average" name="truecar_average" placeholder="Average" value="<?= $TrueCar_Average; ?>"></p>
<p><label for="truecar_above">High Price</label> <input type="number" class="dollars" id="truecar_above" name="truecar_above" placeholder="Above" value="<?= $TrueCar_Above; ?>"></p>
<p class="clear">
<label for="truecar_url">Report URL</label> <input type="url" id="truecar_url" name="truecar_url" size="20" spellcheck="false" placeholder="www.truecar.com/" value="<?= $TrueCar_URL; ?>">
<i title="Copy TrueCar URL" data-clipboard-target="#truecar_url" data-clipboard-action="copy" class="fa fa-clipboard" aria-hidden="true"></i>
</p>
</div>
<div>
<a target="_blank" href="http://www.nadaguides.com/Cars/<?= $year; ?>/<?= $make; ?>/<?= $model; ?>"><img src="images/logos/NADA.png"></a>
<p><label for="nada_trade">Trade</label> <input type="number" class="dollars" id="nada_trade" name="nada_trade" placeholder="Trade" value="<?= $NADA_Trade; ?>"></p>
<p><label for="nada_loan">Loan</label> <input type="number" class="dollars" id="nada_loan" name="nada_loan" placeholder="Loan" value="<?= $NADA_Loan; ?>"></p>
<p><label for="nada_retail">Retail</label> <input type="number" class="dollars" id="nada_retail" name="nada_retail" placeholder="Retail" value="<?= $NADA_Retail; ?>"></p>
</div>
<input type="submit" id="Submit" value="Submit">
</form>
<script src="include/js/clipboard.min.js"></script>
<script>
var clipboard = new Clipboard('.fa-clipboard');
clipboard.on('success', function(e) {console.log(e);});
clipboard.on('error', function(e) {console.log(e);});
</script>
Replace
if(isset($_POST['Submit']))
with
if (!empty($_POST))
this checks in general if anything has been posted (if the POST request is not empty -> do this)
Please verify your submit have this ...
<input type="submit" value="Submit" name="submit" />
and your form method is
<form method="POST" action="xyz"> ...
Your code is a bit off.
You're checking
if(isset($_POST['Submit'])) {
Which is not being posted at all. This is why, the if part never gets executed.
You can try to check if it is POST request by
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// …
}
maybe this helps.
You should use filter_input to handle POST and GET params. Using $_POST or $_GET is deprecated.
I maked image upload for my form, but this going with adding time to error
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'image' cannot be null' in /www/data08/users/i/itsiim.planet.ee/htdocs/progemine/system/lisa.php:58 Stack trace: #0 /www/data08/users/i/itsiim.planet.ee/htdocs/progemine/system/lisa.php(58): PDOStatement->execute(Array) #1 {main} thrown in /www/data08/users/i/itsiim.planet.ee/htdocs/progemine/system/lisa.php on line 58
<?php
require 'conf/db.php';
if ( !empty($_POST)) {
// keep track validation errors
$nimiError = null;
$emailError = null;
$mobiilError = null;
$suguError = null;
// keep track post values
$nimi = $_POST['nimi'];
$email = $_POST['email'];
$mobiil = $_POST['mobiil'];
$sugu = $_POST['sugu'];
// validate input
$valid = true;
if (empty($nimi)) {
$nimiError = 'Palun sisesta nimi';
$valid = false;
}
if (empty($email)) {
$emailError = 'Palun sisesta e-mail';
$valid = false;
} else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$emailError = 'Palun sisesta korrektne e-mail';
$valid = false;
}
if (empty($mobiil)) {
$mobiilError = 'Palun sisesta mobiili number';
$valid = false;
}
if (empty($sugu)) {
$suguError = 'Palun vali sugu';
$valid = false;
}
//Pilt
if(is_uploaded_file($_FILES['image']['tmp_name'])){
$folder = "upload/";
$file = basename( $_FILES['image']['name']);
$full_path = $folder.$file;
if(move_uploaded_file($_FILES['image']['tmp_name'], $full_path)) {
$image = $full_path;
}
}
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO kliendid (nimi,email,mobiil,sugu,image) values(?, ?, ?, ?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($nimi,$email,$mobiil,$sugu,$image));
Database::disconnect();
header("Location: index.php");
}
}
?>
<!DOCTYPE html>
<html lang="et">
<head>
<meta charset="utf-8">
<title>Klientide andmed by Siim Aarmaa IS-13</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="col-md-6 col-md-offset-3">
<div class="row">
<h3>Lisa uus klient</h3>
</div>
<form class="form-horizontal" action="lisa.php" method="post">
<div class="form-group <?php echo !empty($nimiError)?'error':'';?>">
<label class="col-sm-2 control-label">Nimi</label>
<div class="controls">
<input name="nimi" type="text" placeholder="Nimi" value="<?php echo !empty($nimi)?$nimi:'';?>">
<?php if (!empty($nimiError)): ?>
<span class="help-block"><?php echo $nimiError;?></span>
<?php endif; ?>
</div>
</div>
<div class="form-group <?php echo !empty($emailError)?'error':'';?>">
<label class="col-sm-2 control-label">E-mail</label>
<div class="controls">
<input name="email" type="text" placeholder="E-mail" value="<?php echo !empty($email)?$email:'';?>">
<?php if (!empty($emailError)): ?>
<span class="help-block"><?php echo $emailError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-group <?php echo !empty($mobiilError)?'error':'';?>">
<label class="col-sm-2 control-label">Mobiili number</label>
<div class="controls">
<input name="mobiil" type="text" placeholder="Mobiili number" value="<?php echo !empty($mobiil)?$mobiil:'';?>">
<?php if (!empty($mobiilError)): ?>
<span class="help-block"><?php echo $mobiilError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-group <?php echo !empty($suguError)?'error':'';?>">
<label class="col-sm-2 control-label">Sugu</label>
<div class="controls">
<input name="sugu" type="radio" value="<?php echo !empty($mees)?$mees:'Mees';?>">Mees
<input name="sugu" type="radio" value="<?php echo !empty($naine)?$naine:'Naine';?>">Naine
<?php if (!empty($suguError)): ?>
<span class="help-block"><?php echo $suguError;?></span>
<?php endif;?>
</div><br>
<div class="form-group <?php echo !empty($mobiilError)?'error':'';?>">
<label class="col-sm-2 control-label">Pilt</label>
<div class="controls">
<input type="file" name="image" required="required" value=""/>
<?php if (!empty($mobiilError)): ?>
<span class="help-block"><?php echo $mobiilError;?></span>
<?php endif;?>
</div>
</div>
<br>
<div class="form-group">
<button type="submit" class="btn btn-success">Lisa klient</button>
<a class="btn btn-default" href="index.php">Tagasi</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>
Looks like something went wrong with the fileupload. You have no else branches for the is_uploaded_file() and move_uploaded_file() checks.
<?php
require 'conf/db.php';
$errors = array();
if ( !isset($_POST['nimi'],$_POST['email'],$_POST['mobiil'],$_POST['sugu']) ) {
$errors['parameter'] = 'missing POST parameter';
}
else {
// keep track post values
$nimi = $_POST['nimi'];
$email = $_POST['email'];
$mobiil = $_POST['mobiil'];
$sugu = $_POST['sugu'];
// validate input
if (empty($nimi)) {
$errors['nimi'] = 'Palun sisesta nimi';
}
if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$errors['email'] = 'Palun sisesta korrektne e-mail';
}
if (empty($mobiil)) {
$errors['mobiil'] = 'Palun sisesta mobiili number';
}
if (empty($sugu)) {
$errors['suguError'] = 'Palun vali sugu';
}
if ( empty($errors) ) {
//Pilt
if( !is_uploaded_file($_FILES['image']['tmp_name']) ) {
$errors['upload'] = 'no file uploaded';
}
else {
$folder = "upload/";
$file = basename( $_FILES['image']['name']);
$full_path = $folder.$file;
if( !move_uploaded_file($_FILES['image']['tmp_name'], $full_path) ) {
$errors['upload'] = 'cannot move file';
}
else {
$image = $full_path;
}
}
}
}
// insert data
if ( empty($errors) ) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO kliendid (nimi,email,mobiil,sugu,image) values(?, ?, ?, ?, ?)";
$q = $pdo->prepare($sql);
$q->execute( array($nimi,$email,$mobiil,$sugu,$image) );
Database::disconnect();
header("Location: index.php");
die;
}
else {
echo '<pre>', join("\r\n", $errors), '</pre>';
}
The problem is because of the Undefined index: image, which means your file didn't get uploaded. And that's because you didn't set the enctype="multipart/form-data" in your <form> element. It should be,
<form class="form-horizontal" action="lisa.php" method="post" enctype="multipart/form-data">
// your HTML code
</form>
I'm attempting to add the update function to my CRUD application. Essentially it uses the database specified, and uses the 'id' from the index.php page, which is 'productID' from the database. In another part of the application, a store management feature is included with the same skeleton Update page and works perfectly.
The database (Product) contains productID(PK), productName, productPrice, storeID(FK), productDate, productComments, productQuantity, and productPortion.
I'm certain it's within the PHP script, likely around the UPDATE command after using a few error checks but I can't seem to figure out what might be the main issue.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Update an Item</h3>
</div>
<form class="form-horizontal" action="update.php" method="post">
<input type="hidden" name="productID" value="<?php echo $id ?>">
<div class="control-group <?php echo !empty($nameError)?'error':'';?>">
<label class="control-label">Item</label>
<div class="controls">
<input name="productName" type="text" placeholder="Product Name" value="<?php echo !empty($productName)?$productName:'';?>">
<?php if (!empty($nameError)): ?>
<span class="help-inline"><?php echo $nameError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($priceError)?'error':'';?>">
<label class="control-label">Price</label>
<div class="controls">
<input name="productPrice" type="number" step="any" placeholder="Price" value="<?php echo !empty($productPrice)?$productPrice:'';?>">
<?php if (!empty($priceError)): ?>
<span class="help-inline"><?php echo $priceError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($storeError)?'error':'';?>">
<label class="control-label">Store</label>
<div class="controls">
<select name="storeID" class="form-control">
<option value="">Select Store</option>
<?php $pdo=D atabase::connect(); $sql='SELECT * FROM Store ORDER BY storeName DESC' ; foreach ($pdo->query($sql) as $row) { $selected = $row['storeID']==$storeID?'selected':''; echo '
<option value="'. $row['storeID'] .'" '. $selected .'>'. $row['storeName'] .'</option>'; } Database::disconnect(); ?>
</select>
<?php if (!empty($storeError)): ?>
<span class="help-inline"><?php echo $storeError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($dateError)?'error':'';?>">
<label class="control-label">Date</label>
<div class="controls">
<input name="productDate" type="date" step="any" placeholder="Date" value="<?php echo !empty($productDate)?$productDate:'';?>">
<?php if (!empty($dateError)): ?>
<span class="help-inline"><?php echo $dateError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($commentsError)?'error':'';?>">
<label class="control-label">Comments</label>
<div class="controls">
<input name="productComments" type="text" placeholder="Comments" value="<?php echo !empty($productComments)?$productComments:'';?>">
<?php if (!empty($commentsError)): ?>
<span class="help-inline"><?php echo $commentsError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($quantityError)?'error':'';?>">
<label class="control-label">Quantity</label>
<div class="controls">
<input name="productQuantity" type="number" placeholder="Quantity" value="<?php echo !empty($productQuantity)?$productQuantity:'';?>">
<?php if (!empty($quantityError)): ?>
<span class="help-inline"><?php echo $quantityError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($portionError)?'error':'';?>">
<label class="control-label">Portion</label>
<div class="controls">
<input name="productPortion" type="number" placeholder="Portion" value="<?php echo !empty($productPortion)?$productPortion:'';?>">
<?php if (!empty($portionError)): ?>
<span class="help-inline"><?php echo $portionError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Update</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div>
<!-- /container -->
</body>
</html>
PHP
<?php
require 'database.php';
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
if ( null==$id ) {
header("Location: index.php");
}
if ( !empty($_POST)) {
// keep track validation errors
$nameError = null;
$priceError = null;
$storeError = null;
$dateError = null;
$quantityError = null;
$portionError = null;
// keep track post values
$id = $_POST['id'];
$storeID= $_POST['storeID'];
$productName = $_POST['productName'];
$productPrice = $_POST['productPrice'];
$productQuantity = $_POST['productQuantity'];
$productPortion = $_POST['productPortion'];
$productComments = $_POST['productComments'];
$productDate = $_POST['productDate'];
//error displayed for creation errors
$valid = true;
if (empty($productName)) {
$nameError = 'Please enter the name of the product';
$valid = false;
}
if (empty($productPrice)) {
$priceError = 'Please enter a price';
$valid = false;
}
if (empty($storeID)) {
$storeError = 'Please enter a store';
$valid = false;
}
if (empty($productDate)) {
$dateError = 'Please enter the purchase date';
$valid = false;
}
if (empty($productComments)) {
$commentsError = 'Please enter any comments';
$valid = false;
}
if (empty($productQuantity)) {
$quantityError = 'Please select the quantity';
$valid = false;
}
if (empty($productPortion)) {
$portionError = 'Please enter the portion';
$valid = false;
}
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE Product SET productName=?, productPrice=?, storeID=?, productDate=?,
productComments=?, productQuantity=?, productPortion=? WHERE productID=?";
$q = $pdo->prepare($sql);
$q->execute(array($productName,$productPrice,$storeID,$productDate,
$productComments,$productQuantity,$productPortion,$id));
Database::disconnect();
header("Location: index.php");
}
} else {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM Product WHERE productID = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$productName = $data['productName'];
$productPrice = $data['productPrice'];
$storeID = $data['storeID'];
$productQuantity = $data['productQuantity'];
$productPortion = $data['productPortion'];
$productComments = $data['productComments'];
$productDate = $data['productDate'];
Database::disconnect();
}
?>
Having a quick look at your code you are sending the form data via $_POST and on the php script checking $_GET then grabbing the id from $_REQUEST. Try changing
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
to
if ( !empty($_POST['id'])) {
$id = $_POST['id'];
}
Hope that helps!
Thanks Donniep!
I found that the answer was actually related to the POST values after being submitted. My impression was that I could still use the value from the GET call of 'id', but I instead needed to use the actual ID value from the product DB instead. The solution turned out to be:
// keep track post values
$id = $_POST['id'];
Needed to be changed to:
// keep track post values
$id = $_POST['productID'];
I am trying to update the records but the update query is not working for some reason.It is deleting and inserting fine but somehow the update doesn't work.I have checked various questions but couldn't find the answer.I have checked the data inserted in the query and its fine too.This is my code.
<?php
require 'database.php';
$ido = 0;
if ( !empty($_GET['id'])) {
$ido = $_REQUEST['id'];
echo $ido;
}
if ( !empty($_POST)) {
// keep track validation errors
$nameError = null;
$descError = null;
$priceError = null;
// keep track post values
$name = $_POST['name'];
$desc = $_POST['desc'];
$price = $_POST['price'];
// validate input
$valid = true;
if (empty($name)) {
$nameError = 'Please enter Name';
$valid = false;
}
if (empty($desc)) {
$descError = 'Please enter Valid descriptin';
$valid = false;
}
if (empty($price) || filter_var($price, FILTER_VALIDATE_INT) == false) {
$priceError = 'Please enter a valid price';
$valid = false;
}
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE Items SET I_name = ? , I_desc = ? ,I_price = ? WHERE I_id = ?"; <---This is the update query part
$q = $pdo->prepare($sql);
$q->execute(array($name,$desc,$price,$ido)); <---these are the values inserted
Database::disconnect();
header("Location: index.php");
}
}
else {
echo $ido;
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM Items where I_id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($ido));
$data = $q->fetch(PDO::FETCH_ASSOC);
$name = $data['I_name'];
$desc = $data['I_desc'];
$price = $data['I_price'];
Database::disconnect();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Update Items</h3>
</div>
<form class="form-horizontal" action="update_items.php" method="post">
<div class="control-group <?php echo !empty($nameError)?'error':'';?>">
<label class="control-label">Name</label>
<div class="controls">
<input name="name" type="text" placeholder="Item Name" value="<?php echo !empty($name)?$name:'';?>">
<?php if (!empty($nameError)): ?>
<span class="help-inline"><?php echo $nameError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($descError)?'error':'';?>">
<label class="control-label">Description</label>
<div class="controls">
<input name="desc" type="text" placeholder="Item Description" value="<?php echo !empty($desc)?$desc:'';?>">
<?php if (!empty($descError)): ?>
<span class="help-inline"><?php echo $descError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($priceError)?'error':'';?>">
<label class="control-label">Price</label>
<div class="controls">
<input name="price" type="text" placeholder="Item Price" value="<? php echo !empty($price)?$price:'';?>">
<?php if (!empty($priceError)): ?>
<span class="help-inline"><?php echo $priceError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Create</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>
This is your form:
<form class="form-horizontal" action="update_items.php" method="post">
^ nothing here
As you can see you are posting and there is no query variable after the url you are posting to.
Then you check for the ID:
$ido = 0;
if (!empty($_GET['id'])) {
$ido = $_REQUEST['id'];
echo $ido;
}
$ido will remain 0 as there is no $_GET['id'].
You can either modify your form to add the ID or add a hidden variable in the form with the ID and check for $_POST['id'].
I'd go for the second option:
<form class="form-horizontal" action="update_items.php" method="post">
<input type="hidden" name="id" value="<?php echo $ido; ?>">
and in php:
if (!empty($_POST)) {
$ido = $_POST['id'];