avoid records with the same data - php

by means of an if attempt that can not be created two records with the same name, it does not work and you can create a record with a dupiclate name
this is the controller
include_once 'model/solucion.php';
public function Guardar()
{
$this->model->Duplicado($_POST['Nombre']);
$name = $this->model->resultado2['Nombre'];
if($name == $_POST['Nombre']){
die("No se puede crear una solucion con el mismo nombre");
}else{
$solucion = new solucion();
$solucion->id = $_REQUEST['id'];
$solucion->Nombre = $_REQUEST['Nombre'];
$solucion->Tipo = $_REQUEST['Tipo'];
$solucion->Descripcion = $_REQUEST['Descripcion'];
$solucion->Pagina = $_FILES['Pagina']['name'];
}
header("Location: index.php");
}
this is the model
public $resultado2;
public function Duplicado($Nombre)
{
try {
$stm = $this->pdo->prepare("SELECT * FROM fallas WHERE Nombre = '$Nombre'");
$stm->execute();
$res=$stm->fetch(PDO::FETCH_ASSOC);
$this->resultado2 = array();
$i = 0;
foreach ($res as $row)
{
$this->resultado2[$i]['id'] = $row['id'];
$this->resultado2[$i]['Nombre'] = $row['Nombre'];
$this->resultado2[$i]['Tipo'] = $row['Tipo'];
$this->resultado2[$i]['Descripcion'] = $row['Descripcion'];
$this->resultado2[$i]['Pagina'] = $row['Pagina'];
$i++;
}
} catch (Exception $ex) {
die($e->getMessage());
}
}
this is the view
<ol class="breadcrumb">
<li>Inicio</li>
<li class="active"><?php echo $solucion->id != null ?
$solucion->Nombre : 'Nueva Solución'; ?></li>
</ol>
<form id="frm-alumno" action="?c=solucion&a=Guardar" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="<?php echo $solucion->id; ?>" />
<div class="form-group">
<label>Nombre</label>
<input type="text" name="Nombre" value="<?php echo $solucion->Nombre; ?>" class="form-control" placeholder="Ingrese su nombre" required>
</div>
<div class="form-group">
<label for="exampleFormControlSelect1">Tipo de fallo</label>
<select class="form-control" id="exampleFormControlSelect1" name="Tipo" value="<?php echo $solucion->Tipo; ?>">
<option value="software">software</option>
<option value="hardware">hardware</option>
<option value="red">red</option>
</select>
</div>
<div class="form-group">
<label>Descripcion</label>
<textarea type="text" name="Descripcion" value="<?php echo $solucion->Descripcion; ?>" class="form-control" rows="10" cols="40" required>
</textarea>
</div>
<div class="form-group">
<label>Pagina.php</label>
<input type="file" name="Pagina" value="<?php echo $solucion->Pagina; ?>" >
</div>
<div class="form-group">
<label >Imagenes</label>
<input type="file" class="form-control" id="archivo[]" name="archivo[]" multiple="" >
</div>
<hr />
<br>
<div class="text-right">
<button class="btn btn-success">Guardar</button>
</div>
What do I have to change in the controller to avoid creating duplicate records with the same name?

You need to pass the array and check whether this is empty or not . Check below for the code and run it and let me know if you get any error .
public function Duplicado($Nombre)
{
try{
$stm = $this->pdo->prepare("SELECT * FROM fallas WHERE Nombre = '$Nombre'");
$stm->execute();
$res=$stm->fetch(PDO::FETCH_ASSOC);
return $res;
}catch (Exception $ex) {
die($e->getMessage());
}
}
include_once 'model/solucion.php';
public function Guardar()
{
$name = $this->model->Duplicado($_POST['Nombre']);
//$name = $this->model->resultado2['Nombre'];
if(!empty($name)){
die("No se puede crear una solucion con el mismo nombre");
}else{
$solucion = new solucion();
$solucion->id = $_REQUEST['id'];
$solucion->Nombre = $_REQUEST['Nombre'];
$solucion->Tipo = $_REQUEST['Tipo'];
$solucion->Descripcion = $_REQUEST['Descripcion'];
$solucion->Pagina = $_FILES['Pagina']['name'];
}
header("Location: index.php");
}

Related

how to popup an alert when form is submitted

I have a registration form and when people compile the form and submit it I want to show a popup, but the problem is it's not working. here is the code:
<?php
// result is when it's all good
if ($result) {
echo '<div class="vai-accedi">
<div class="vai-accedi2">
<div class="vai-accedi3">
<p>Congratulazioni! Registrazione Completata, puoi procedere ad accedere al tuo account. clicca ok per procedere</p>
Ok
</div>
</div>
</div>';
}
?>
All the code
<!-- signup backend connection -->
<?php
include 'dbcon.php';
session_start();
// error_reporting(0);
// if (isset($_SESSION['nome'])) {
// header("Location: header.php");
// }
if (isset($_POST['submit'])) {
$nome = mysqli_real_escape_string($conn,$_POST['nome']);
$cvn = mysqli_real_escape_string($conn,$_POST['cittàvn°']);
$numerodicell = mysqli_real_escape_string($conn,$_POST['numerodicell']);
$email = mysqli_real_escape_string($conn,$_POST['email']);
$password = mysqli_real_escape_string($conn,$_POST['password']);
$confpassword = mysqli_real_escape_string($conn,$_POST['confpassword']);
$password = md5($_POST['password']);
$confpassword = md5($_POST['confpassword']);
if ($password == $confpassword) {
$sql = "SELECT * FROM utenti WHERE email='$email'";
$result = mysqli_query($conn, $sql);
if (!$result->num_rows > 0) {
$sql = "INSERT INTO utenti (nome,cittàvn°, numerodicell, email, password, confpassword)
VALUES ('$nome','$cvn','$numerodicell','$email','$password','$confpassword')";
$result = mysqli_query($conn, $sql);
if ($result) {
// echo "<script>alert('Congratulazioni! Registrazione Completata, puoi procedere ad accedere al tuo account. clicca ok per procedere')</script>";
echo '<div class="vai-accedi">
<div class="vai-accedi2">
<div class="vai-accedi3">
<p>Congratulazioni! Registrazione Completata, puoi procedere ad accedere al tuo account. clicca ok per procedere</p>
Ok
</div>
</div>
</div>';
// header( "Refresh:1; url='login.php'");
$nome = "";
$cvn = "";
$numerodicell = "";
$email = "";
$_POST['password'] = "";
$_POST['confpassword'] = "";
} else {
echo "<script>alert('oops! qualcosa è andato storto.')</script>";
}
} else {
echo "<script>alert('oops! Email già registrata.')</script>";
}
} else {
echo "<script>alert('le due password non combaciano.')</script>";
}
}
?>
<!-- signup backend connection -->
<div class="registrati">
<div class="registratiinner registratiinner2">
<h1>Registrati</h1>
<form action="" class="sign-up-form" method="POST" style="width:100%;">
<div class="input-wrapper">
<input type="text" placeholder="Nome" name="nome" required>
</div>
<div class="input-wrapper">
<input type="text" placeholder="Citta,Via,n°" required name="cittàvn°">
</div>
<div class="input-wrapper">
<input type="text" placeholder="Numero di Cellulare" required name="numerodicell">
</div>
<div class="input-wrapper">
<input type="email" placeholder="Email" required name="email">
</div>
<div class="input-wrapper">
<input type="password" placeholder="Crea una Nuova Password" required name="password">
</div>
<div class="input-wrapper">
<input type="password" placeholder="Conferma Password" required name="confpassword">
</div>
<div class="accetti">
<p style="font-size: 1.8rem; margin-top: 0;">Inviando accetti Termini & Condizioni</p>
</div>
<button type="submit" class="contact-button" style="border-radius: .5rem;" name="submit" type="submit">Registrati</button>
</form>

jQuery AJAX Update and Show/Hide Div

Need some help doing my update Ajax call. What I want my code to do is to show when on click my update form and pass the data from the form to my update via AJAX. So far the form isn't showing on click nor is the update working. Everything else seems to be working right except for that.
index.php
<?php include 'includes/header.php' ?>
<div class="main" id="maincontent">
<div class="main-section">
<div class="add-section">
<form action="app/add.php" method="POST" autocomplete="off">
<?php if(isset($_GET['mess']) && $_GET['mess'] == 'error'){ ?>
<label for="title">To Do*</label>
<input type="text" id= "title" name="title"
style="border-color: #ff6666"
placeholder="This is required" aria-label="You need to create a to do!"/>
<label for="month">Month</label>
<input type="text" id="month" name="month" placeholder="Month Not Required" aria-label="Enter a month if needed"/>
<label for="year">Year</label>
<input type="text" id="year" name="year" placeholder="Year Not Required" aria-label="Enter a year if needed"/>
<button type="submit" aria-label="Enter"> &plus; </button>
<?php }else{ ?>
<label for="title">To Do*</label>
<input type="text" id= "title" name="title" placeholder="Enter a To Do" aria-label="Enter a To Do"/>
<label for="month">Month</label>
<input type="text" id="month" name="month" placeholder="Enter Month [1-12]" aria-label="Enter month if needed for your to do"/>
<label for="year">Year</label>
<input type="text" id="year" name="year" placeholder="Enter Year [yyyy]" aria-label="Enter a year if needed for your to do"/>
<button type="submit" aria-label="Enter"> &plus; </button>
<?php } ?>
</form>
</div>
<?php
$todos = $conn->query("SELECT * FROM todos ORDER BY id DESC");
?>
<div class="show-todo-section">
<?php if($todos->rowCount() <= 0){?>
<div class="todo-item">
<div class="empty">
<p>Enter a To Do!</p>
<img src="img/f.jpg" alt="Notebook" width="100%" height="175px" />
</div>
</div>
<?php } ?>
<?php while($todo = $todos->fetch(PDO::FETCH_ASSOC)) { ?>
<div class="todo-item">
<span id="<?php echo $todo['id']; ?>" class="remove-to-do" aria-label="Delete"><i class="fa fa-trash" style="font-size:18px"></i></span>
<span id="<?php echo $todo['id']; ?>" class="update-to-do" aria-label="Edit">
<i class="fa fa-pencil" style="font-size:18px"></i></span>
<?php if($todo['checked']) { ?>
<input type="checkbox" data-todo-id="<?php echo $todo['id']; ?>" class="check-box" checked />
<h2 class="checked"><?php echo $todo['title'] ?></h2>
<?php }else{ ?>
<input type="checkbox" data-todo-id="<?php echo $todo['id']; ?>" class="check-box">
<h2><?php echo $todo['title'] ?></h2>
<?php } ?>
<br>
<small>Created: <?php echo $todo['date_time'] ?> </small>
<div style="display:none;" class="update"><?php include 'updateForm.php'?></div>
<!---->
</div>
<?php } ?>
jQuery
<script>
$(document).ready(function(){
$('.remove-to-do').click(function(){
const id = $(this).attr('id');
$.post("app/remove.php",
{
id: id
},
(data) =>{
if(data){
$(this).parent().hide(600);
}
}
);
});
$(".check-box").click(function(e){
const id = $(this).attr('data-todo-id');
$.post("app/check.php",
{
id: id
},
(data) =>{
if(data != 'error')
{
const h2 = $(this).next();
if(data === '1'){
h2.removeClass('checked');
}else{
h2.addClass('checked');
}
}
}
);
}); /* */
$(".update-to-do").click(function(e){
const id = $(this).attr('id');
var title = $(this).attr('id'); //find
var month = $(this).attr('id');
var year = $(this).attr('id');
$.post("app/update.php",
{
id: id,
title: title,
month: month,
year : year
},
(data) =>{
//alert(id);
if(data != 'error')
{
var x = document.getElementsByClassName(".update");
if(form.hide()){
form.show();
}else{
form.hide();
}
}
}
);
});
});
updateForm.php
<div class="add-section">
<form action="app/update.php" method="POST" autocomplete="off">
<?php if(isset($_GET['mess']) && $_GET['mess'] == 'error'){ ?>
<label for="id" style="display:none;"></label>
<input type="hidden" id= "id" name="id" value="<?php echo $_GET['id']; ?>" aria-label=""/>
<label for="title">To Do*</label>
<input type="text" id= "title" name="title"
style="border-color: #ff6666"
placeholder="This is required" aria-label="You need to create a to do!"/>
<label for="month">Month</label>
<input type="text" id="month" name="month" placeholder="Month Not Required" aria-label="Enter a month if needed"/>
<label for="year">Year</label>
<input type="text" id="year" name="year" placeholder="Year Not Required" aria-label="Enter a year if needed"/>
<button type="submit" aria-label="Enter"> &plus; </button>
<?php }else{ ?>
<label for="id" style="display:none;"></label>
<!--<input type="hidden" id= "id" name="id" value="<?php //echo $_GET['id']; ?>" aria-label="id"/> -->
<label for="title">To Do*</label>
<input type="text" id= "title" name="title" placeholder="Enter a To Do" aria-label="Enter a To Do"/>
<label for="month">Month</label>
<input type="text" id="month" name="month" placeholder="Enter Month [1-12]" aria-label="Enter month if needed for your to do"/>
<label for="year">Year</label>
<input type="text" id="year" name="year" placeholder="Enter Year [yyyy]" aria-label="Enter a year if needed for your to do"/>
<div class="pad"></div>
<button type="submit" aria-label="Enter"> &plus; </button>
<?php } ?>
</form>
</div>
update.php
<?php
if(isset($_POST['id'])){
require '../includes/conn.php';
include 'func.php';
$id = $_POST['id'];
echo $id;
$title = $_POST['titleUp'];
$month = $_POST['monthUp'];
$year = $_POST['yearUp'];
$dateMonth;
$futureDate;
if(empty($id))
{
header("Location: ../updateForm.php?id=" . $id . "mess=error");
}
else
{
if( (!empty($title)) && (empty($month)) && (empty($year)) )
{ //need to filter 0 so its registered as not empty
$title = validTitle($title);
$stmt = $conn->prepare("UPDATE todos(title) VALUE(?) WHERE id=?");
$res = $stmt->execute([$title, $id]);
if($res)
{
header("Location: ../index.php");
}
else
{
header("Location: ../updateForm.php?id=" . $id . "mess=error");
}
$conn= null;
exit();
}
else if( (!empty($title)) && (!empty($month)) && (empty($year)) )
{
$title = validTitle($title);
$month = validMonth($month);
$dateMonth = dateMonth($month);
$year = date("Y");
$futureDate = futureDate($dateMonth, $year);
$stmt = $conn->prepare("UPDATE todos (title, future_datetime) VALUES (?,?) WHERE id=?");
$res = $stmt->execute([$title ,$futureDate, $id]);
if($res)
{
header("Location: ../index.php");
}
else
{
header("updateForm.php?id=" . $id . "mess=error");
}
$conn= null;
exit();
}
else if( (!empty($title)) && (!empty($month)) && (!(empty($year))))
{
$title = validTitle($title);
$month = validMonth($month);
$dateMonth = dateMonth($month);
$year = validYear($year);
$futureDate = futureDate($dateMonth, $year);
$stmt = $conn->prepare("UPDATE todos (title, future_datetime) VALUES (?,?) WHERE id=?");
$res = $stmt->execute([$title ,$futureDate, $id]);
if($res)
{
header("Location: ../index.php");
}
else
{
header("Location: ../updateForm.php?id=" . $id . "mess=error");
}
$conn= null;
exit();
}
else
{
header("Location: ../updateForm.php?id=" . $id . "mess=error");
}
}
}
else
{
header("Location: ../updateForm.php?id=" . $id . "mess=error");
}
?>
You are POSTing to the page but checking for GET.
Good manual pages to read:
Handling external variables
Example:
$.post("app/update.php",
{
id: id
alert(id);
},
That will send a POST to the app/update.php script you have which contains the following:
<?php
// $GET is not the same as $_GET
if(isset($GET['id'])){
require '../includes/conn.php';
include 'func.php';
$id = $GET['id'];
echo $id;
This will not work given that you are POSTing but looking incorrectly at $GET (which should be $_GET).
To fix change the following lines to:
<?php
if($_POST['id']){
require '../includes/conn.php';
include 'func.php';
$id = $_POST['id'];
echo $id;
Please note that $GET and $_GET aren't the same things, nor are $POST and $_POST.

My GET statements work correctly but my POST statements don't

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.

PHP Adding Data to Database

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>

PHP MySQL not updating for CRUD app

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'];

Categories