Mysql and PHP Update Problems - php

I am working on a simple Userprofile, where the user can update some data over Mysql. But it doesn´t update anything. Why?
<?php
if (isset($_GET['pageID'])) {
$id = $_GET['pageID'];
include("connector.php");
$stmt = $conn->prepare(" SELECT
cl.clientID, cl.firstname, cl.lastname, cl.mobilephone, cl.phone, cl.client_ID,
ad.street, ad.city, ad.postalcode,
wo.work_ID,
ha.hardware1, ha.serialnumber, ha.hardware2, ha.serialnumber2
FROM client cl
JOIN adress ad ON cl.clientID = ad.clientID
LEFT JOIN work wo ON cl.clientID = wo.clientID
LEFT JOIN hardware ha ON ad.adressID = ha.adressID
WHERE cl.clientID = '$id'");
$stmt->execute();
}
?>
<?php while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) : ?>
<div class="container">
<div class="col-sm-12 col-md-12 col-xl-12">
<div class="col-sm-3 col-md-3 col-xl-3 profileNames">
<img src="Userfotos/jedi.jpg" class="img-responsive"><br>
<button type="submit" name="submit" class="btn btn-info">edit Foto</button>
</div>
<div class="col-sm-3 col-md-3 col-xl-3 profileNames">
<p><h4>Lastname:</h4><?php echo $row['lastname']; ?></p>
<p><h4>Firstname:</h4> <?php echo $row['firstname']; ?></p>
<p><h4>Street</h4> <?php echo $row['street']; ?></p>
<p><h4>City</h4> <?php echo $row['city']; ?></p>
<p><h4>Postalcode</h4> <?php echo $row['postalcode']; ?></p>
<button type="button" class="btn btn-info" data-toggle="modal" data-target="#editPrivateData">Edit data
</button>
<div id="editPrivateData" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Edit Personal data</h4>
</div>
<div class="modal-body">
<form action="userProfile.php?pageID=1" method="post">
<div class="form-group">
<label for="_firstname">Firstname</label>
<input type="text" class="form-control" id="_firstname" name="firstname"
value="<?php echo $row['firstname']; ?>">
</div>
<div class="form-group">
<label for="_lastname">Lastname</label>
<input type="text" class="form-control" id="_lastname" name="lastname"
value="<?php echo $row['lastname']; ?>">
</div>
<div class="form-group">
<label for="_street">Street</label>
<input type="text" class="form-control" id="_street" name="street"
value="<?php echo $row['street']; ?>">
</div>
<div class="form-group">
<label for="_city">City</label>
<input type="text" class="form-control" id="_city" name="city"
value="<?php echo $row['city']; ?>">
</div>
<div class="form-group">
<label for="_postalcode">Postalcode</label>
<input type="text" class="form-control" id="_postalcode" name="postalcode"
value="<?php echo $row['postalcode']; ?>">
</div>
<button type="submit" name="submitPrivate" class="btn btn-info">Save</button>
<?php
if (isset($_POST['submitHardware'])) {
try {
$id = $_GET['pageID'];
$stmt = $conn->prepare("UPDATE clients.client SET
firstname = :firstname,
lastname = :lastname,
mobilephone = :mobilephone,
phone = :phone
WHERE clientID = $id");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':mobilephone', $mobilephone);
$stmt->bindParam(':phone', $phone);
$stmt->execute([':firstname' => $_POST['firstname'],
':lastname' => $_POST['lastname'],
':mobilephone' => $_POST['mobilephone'],
':phone' => $_POST['phone']
]);
} catch (PDOException $e) {
echo $e->getMessage() . ", ";
die("try to fix your inputs . If this doesn`t work, please contact your Admin.");
}
}
?>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-info" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-3 col-md-3 col-xl-3 profileNames">
<p><h4>Hardware1:</h4><?php echo $row['hardware1']; ?></p>
<p><h4>Serialnumber1:</h4><?php echo $row['serialnumber']; ?></p>
<p><h4>Hardware2:</h4><?php echo $row['hardware2']; ?></p>
<p><h4>Serialnumber2:</h4><?php echo $row['serialnumber2']; ?></p>
<button type="button" class="btn btn-info" data-toggle="modal" data-target="#editHardware">Edit data
</button>
<!-- Modal -->
<div id="editHardware" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Edit hardware data</h4>
</div>
<div class="modal-body">
<form action="userProfile.php?pageID=3" method="post">
<div class="form-group">
<label for="_hardware1">Hardware1</label>
<input type="text" class="form-control" id="_hardware" name="hardware1"
placeholder="<?php echo $row['hardware1']; ?>">
</div>
<div class="form-group">
<label for="serialnumber">Serialnumber1</label>
<input type="text" class="form-control" id="_serialnumber" name="serialnumber"
placeholder="<?php echo $row['serialnumber']; ?>">
</div>
<div class="form-group">
<label for="_hardware2">Hardware2</label>
<input type="text" class="form-control" id="_hardware2" name="hardware2"
placeholder="<?php echo $row['hardware2']; ?>">
</div>
<div class="form-group">
<label for="_serialnumber2">Serialnumber2</label>
<input type="text" class="form-control" id="_serialnumber2" name="serialnumber2"
placeholder="<?php echo $row['serialnumber2']; ?>">
</div>
<button type="submit" name="submitHardware" class="btn btn-info">Save</button>
<?php
if (isset($_POST['submitHardware'])) {
require("connector.php");
try {
$stmt = $conn->prepare("UPDATE clients.hardware SET
hardware1 = :hardware1,
serialnumber = :serialnumber,
hardware2 = :hardware2,
serialnumber2 = :serialnumber2,
WHERE hardware.clientID = '$id'");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':mobilephone', $mobilephone);
$stmt->bindParam(':phone', $phone);
$stmt->bindParam(':client_ID', $client_ID);
$stmt->execute([':hardware1' => $_POST['hardware1'],
':serialnumber' => $_POST['serialnumber'],
':hardware2' => $_POST['hardware2'],
':serialnumber2' => $_POST['seerialnumber2']
]);
} catch (PDOException $e) {
echo $e->getMessage() . ", ";
die("try to fix your inputs . If this doesn`t work, please contact your Admin.");
}
}
?>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-info" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-3 col-md-3 col-xl-3 profileNames">
<p><h4>ClientID:</h4><?php echo $row['client_ID']; ?></p>
<p><h4>WorkID:</h4><?php echo $row['work_ID']; ?></p>
<button type="submit" name="submit" class="btn btn-info">Edit data</button>
</div>
</div>
<?php endwhile; ?>
As you can see, there is a while-loop to fetch the data and display them into some fields. In Between this loop, i created two Bootstrap-Modals, where the user can edit something. if the user clicks on the "save" button, nothing happens. i really don`t understand where is the problem.
and another small point: the userprofile is generated dynamically with the clientID(pageID). how do i temporary save this pageID, so i can return to the current page after the form action method ="POST"
The clientID is the primary key in the database for the clients.client table. The client_ID is an ID the user has to set by himself, he can set whatever he want to. The PageID is linked to the clientID is for generating dynamical pages. That means: on another page there is a table which displays some basically informations about all users. If the logged in User clicks on a user from the table, there will be the userprofile dynamically generated.

your code is really weird. Please tell us what the page ID and client ID are. They are obviously not the same. But you use them as such. I reduced your code to just one modal and used hidden fields for client and page ID values.
<?php
// TODO: filter all input
if (isset($_POST['submitHardware']) && $_POST['pageID'] == 3) {
try {
include("connector.php");
$client_id = $_GET['clientID'];
$stmt = $conn->prepare("UPDATE clients.client SET
firstname = :firstname,
lastname = :lastname,
mobilephone = :mobilephone,
phone = :phone
WHERE clientID = $client_id");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':mobilephone', $mobilephone);
$stmt->bindParam(':phone', $phone);
$stmt->execute([':firstname' => $_POST['firstname'],
':lastname' => $_POST['lastname'],
':mobilephone' => $_POST['mobilephone'],
':phone' => $_POST['phone']
]);
} catch (PDOException $e) {
echo $e->getMessage() . ", ";
die("try to fix your inputs . If this doesn`t work, please contact your Admin.");
}
}
if (isset($_GET['clientID'])) {
$client_id = $_GET['clientID']; // TODO: filter
include("connector.php");
$stmt = $conn->prepare(" SELECT
cl.clientID, cl.firstname, cl.lastname, cl.mobilephone, cl.phone, cl.client_ID,
ad.street, ad.city, ad.postalcode,
wo.work_ID,
ha.hardware1, ha.serialnumber, ha.hardware2, ha.serialnumber2
FROM client cl
JOIN adress ad ON cl.clientID = ad.clientID
LEFT JOIN work wo ON cl.clientID = wo.clientID
LEFT JOIN hardware ha ON ad.adressID = ha.adressID
WHERE cl.clientID = '$client_id'");
$stmt->execute();
}
?>
<?php while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) : ?>
<div class="container">
<div class="col-sm-12 col-md-12 col-xl-12">
<div class="col-sm-3 col-md-3 col-xl-3 profileNames">
<img src="Userfotos/jedi.jpg" class="img-responsive"><br>
<button type="submit" name="submit" class="btn btn-info">edit Foto</button>
</div>
<div class="col-sm-3 col-md-3 col-xl-3 profileNames">
<p><h4>Hardware1:</h4><?php echo $row['hardware1']; ?></p>
<p><h4>Serialnumber1:</h4><?php echo $row['serialnumber']; ?></p>
<p><h4>Hardware2:</h4><?php echo $row['hardware2']; ?></p>
<p><h4>Serialnumber2:</h4><?php echo $row['serialnumber2']; ?></p>
<button type="button" class="btn btn-info" data-toggle="modal" data-target="#editHardware">Edit data
</button>
<!-- Modal -->
<div id="editHardware" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Edit hardware data</h4>
</div>
<div class="modal-body">
<form action="userProfile.php" method="post">
<input type="hidden" name="pageID" value="3">
<input type="hidden" name="clientID" value="<?php echo $client_id; ?>">
<div class="form-group">
<label for="_hardware1">Hardware1</label>
<input type="text" class="form-control" id="_hardware" name="hardware1"
placeholder="<?php echo $row['hardware1']; ?>">
</div>
<div class="form-group">
<label for="serialnumber">Serialnumber1</label>
<input type="text" class="form-control" id="_serialnumber" name="serialnumber"
placeholder="<?php echo $row['serialnumber']; ?>">
</div>
<div class="form-group">
<label for="_hardware2">Hardware2</label>
<input type="text" class="form-control" id="_hardware2" name="hardware2"
placeholder="<?php echo $row['hardware2']; ?>">
</div>
<div class="form-group">
<label for="_serialnumber2">Serialnumber2</label>
<input type="text" class="form-control" id="_serialnumber2" name="serialnumber2"
placeholder="<?php echo $row['serialnumber2']; ?>">
</div>
<button type="submit" name="submitHardware" class="btn btn-info">Save</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-info" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
<?php endwhile; ?>

Related

How to fix 'If(isset($_POST['Id'])) error' while editing the form in a PHP based CRUD application?

The "if(isset($_POST["titleId"]) && !empty($_POST["titleId"])" in my code is returning false value.
I'm working on a CRUD application, the insert modal is working fine, now I'm stuck at the update part of it. So when you click on the update icon it does fetch the right titleId in the URL but the first 'if' condition returns false and hence the update isn't working.
Here's what I've tried so far.
admin.php
<?php
$typeId = filter_input(INPUT_GET, "type");
$titleId = filter_input(INPUT_GET, "titleId");
$active = "admin" . $typeId;
require_once './pages/header.php';
require_once './functions/queries.php';
$getAll = Queries::getAllTitle($typeId);
?>
<div class="container">
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header clearfix">
<h2 class="pull-left"></h2>
<button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#facultyAddModal">Add Title</button>
</div>
<!--<div class="container">
<button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#facultyAddModal">Add Title</button>
<br><br>-->
<div class="panel-group" id="titleAccordion">
<?php
for ($i = 0; $i < count($getAll); $i++) {
echo <<<HTML
<div class="panel panel-default">
<div class="panel-heading"><h4 class="panel-title">
<a data-toggle="collapse" data-parent="#titleAccordion" href="#collapseF{$i}">{$getAll[$i]['title']}</a></h4>
</div>
<div id="collapseF{$i}" class="panel-collapse collapse" >
<div class="panel-body">
<div class="table-responsive">
<table class="table table-condensed"><tbody>
<tr><td>Title:</td><td>{$getAll[$i]['title']}</td></tr>
<tr><td>Units:</td><td>{$getAll[$i]['units']}</td></tr>
<tr><td>Category:</td><td>{$getAll[$i]['category']}</td></tr>
<tr><td>
<tr><td><input type="hidden" id="titleId" name="titleId" value="{$getAll[$i]['titleId']}"> </tr><td>
<a href='edit.php?titleId={$getAll[$i]['titleId']}' title='Update Record' data-toggle='tooltip'><span class='glyphicon glyphicon-pencil'></span></a>
<a href='delete.php?titleId={$getAll[$i]['titleId']}' title='Delete Record' data-toggle='tooltip'><span class='glyphicon glyphicon-trash'></span></a>
</tr></td>
</tbody></table>
</div>
</div>
</div>
</div>
HTML;
}
?>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Title Add Modal-->
<div class="modal fade" id="facultyAddModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Title</h4>
</div>
<div class="modal-body">
<div id="adminResult" class="hide" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<div id="resultAdminContent"></div>
</div>
<form class="cmxform" id="adminForm" method="post">
<label for="Activity">ActivityAttended (required)</label>
<input class="form-control" id="adminTitle" name="title" type="text" required>
<br>
<label for="units">Units (required)</label>
<input class="form-control" id="adminUnits" type="number" name="units" required>
<br>
<label for="Category">Category (Optional)</label>
<input class="form-control" id="adminCategory" type="text" name="category">
<br>
<?php echo
'<input type="hidden" id="addadminTypeId" value="'.$typeId.'">';
?>
<?php echo
'<input type="hidden" id="titleId" name="titleId" value="'.$titleId.'">';
?>
<button class="btn btn-info btn-primary" type="submit">Submit</button>
<br>
<br>
</form>
</div>
</div>
</div>
</div>
update.php
<?php
require_once 'functions/db_connection.php';
$conn = DB::databaseConnection();
$title = $units = $category = "";
if(isset($_POST["titleId"]) && !empty($_POST["titleId"])){
$titleId = $_POST['titleId'];
$sql = "UPDATE title SET title = :title, units = :units, category = :category WHERE titleId = :titleId";
if($stmt = $conn->prepare($sql))
{
// Bind variables to the prepared statement as parameters
$stmt->bindParam(':titleId', $titleId);
$stmt->bindParam(':title', $title);
$stmt->bindParam(':units', $units);
$stmt->bindParam(':category', $category);
if ($stmt->execute()) {
header("location: index.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
unset($stmt);
}
unset($conn);
} else{
if(isset($_GET["titleId"]) && !empty(trim($_GET["titleId"]))){
$titleId = trim($_GET["titleId"]);
$sql = "SELECT * FROM title WHERE titleId = :titleId";
if($stmt = $conn->prepare($sql))
{
$stmt->bindParam(':titleId', $titleId);
if ($stmt->execute()){
if($stmt->rowCount() == 1){
$result = $stmt->fetch(PDO::FETCH_ASSOC);
// Retrieve individual field value
$title = $result["title"];
$units = $result["units"];
$category = $result["category"];
} else{
echo"error1";
exit();
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
unset($stmt);
unset($conn);
} else{
// URL doesn't contain id parameter. Redirect to error page
echo"error2";
exit();
}
}
?>
<!--<!DOCTYPE html>-->
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Update Record</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
.wrapper{
width: 500px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2>Update Record</h2>
</div>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<label for="Activity">Title</label>
<input class="form-control" id="adminTitle" name="title" type="text" value="<?php echo $title; ?>" required>
<br>
<label for="units">Units (required)</label>
<input class="form-control" id="adminUnits" type="number" name="units" value="<?php echo $units; ?>" required>
<br>
<label for="Category">Category (Optional)</label>
<input class="form-control" id="adminCategory" type="text" value="<?php echo $category; ?>" name="category">
<br>
<input type="hidden" name="titleId" value="<?php echo $titleId; ?>">
<button class="btn btn-info btn-primary" type="submit">Submit</button>
<br>
<br>
</form>
</div>
</<div>
</div>
</div>
</div>
</body>
</html>
The only goal here is to get the update form working, the user should be able to update the records of the respective title being selected.
I don't know crud but I think there is a way to debug a little:
e.g. try this:
if(isset($_POST["titleId"]) && !empty($_POST["titleId"])){
// test if you are here:
echo 'hi, yeah I am here!';
}
or this
echo '<pre>';
var_dump($_POST);
echo '</pre>';
// before:
if(isset($_POST["titleId"]) && !empty($_POST["titleId"])){
// ...
}
also, take a look at
error_get_last()['message']

Modal doesn't validate with PHP

Modal will not trigger my PHP validation.
I can't get my modal to use my PHP validation. HTML validation works. It connects to the DB and makes the updates, but skips the server-side validation. I would appreciate any help, this is new to me why a modal won't validate.
My PHP and Modal form is in one file. I know I need more error messages added to my form, but leaving the phone number and first name out triggers no error messages, so I will add more once I fix this issue. The code just executes and changes the DB.
<?php
//ini_set( 'display_errors', 1 );
//error_reporting( E_ALL );
session_start();
// Include db config
require_once 'includes/dbh.inc.php';
// Process form when post submit
// if($_SERVER['REQUEST_METHOD'] === 'POST'){
// Sanitize POST
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$error=array();
// $error = false;
// $error = isset($_SESSION['error']);
// $error = $_SESSION['error'];
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$first = test_input($_POST['first']);
$last = test_input($_POST['last']);
$email = test_input($_POST['email']);
$unit = $_SESSION['unit'];
$bed = test_input($_POST['bed']);
$bath = test_input($_POST['bath']);
$web = test_input($_POST['web']);
$phone = test_input($_POST['phone']);
$manage = test_input($_POST['manage']);
$ck = $_POST['rent'];
$id = $_SESSION['id'];
// Validate name
if(empty($first) || empty($last)){
$error['name'] = "Enter name";
}
// Validate email
if(empty($email)){
$error['email'] = "Please enter email";
}
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error['email'] = "Invalid email format";
}
// Validate name
if(empty($bed) || empty($bath)){
$error['rooms'] = 'Please enter bed/bath #';
}
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$web)) {
$error['web'] = "Invalid URL";
}
// Validate name
if(empty($phone)){
$error['phone'] = 'Please enter your phone';
}
//Check phone # format 000-000-0000
if(!preg_match("/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i", $phone)) {
$error['phone'] = 'Please enter correct phone format';
}
//Check manage format
if (!preg_match("/^(\s\(([^)]+)\))?[[:punct:]]?\p{Lu}+(?:[\s'-]?[\p{L}\d]+)+(\(([^)]+)\))*$/", $manage)) {
$error['manage'] = 'Please enter correct management format';
}
if (empty($error)) {
var_dump($error);
print_r($error);
$sql = 'UPDATE condos_hp SET user_firstname=:first, user_lastname=:last, user_email=:email, user_bed=:bed, user_bath=:bath, user_web=:web, user_phone=:phone, user_manage=:manage, rent=:rent WHERE id=:id';
// Prepare statement
$stmt = $pdo->prepare($sql);
// Bind params
$stmt->bindParam(':first', $first, PDO::PARAM_STR);
$stmt->bindParam(':last', $last, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
// $stmt->bindParam(':unit', $unit);
$stmt->bindParam(':bed', $bed, PDO::PARAM_INT);
$stmt->bindParam(':bath', $bath, PDO::PARAM_INT);
$stmt->bindParam(':web', $web, PDO::PARAM_STR);
$stmt->bindParam(':phone', $phone, PDO::PARAM_STR);
$stmt->bindParam(':manage', $manage, PDO::PARAM_STR);
$stmt->bindParam(':rent', $ck, PDO::PARAM_INT);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute(array(':first'=>$first, ':last'=>$last, ':email'=>$email, ':bed'=>$bed, ':bath'=>$bath, ':web'=>$web, ':phone'=>$phone, ':manage'=>$manage, ':rent'=>$ck, ':id'=>$id));
// if($stmt){
// header('Location: index1.php');
//}
if (isset($_POST['update'])) {
// session_start();
//Then delete all SESSION variables
session_unset();
//And destroy the current session that is running
session_destroy();
// exit(header("Location: http://www.harbour-place.com/login0.php?update=success"));
if (headers_sent()) {
die("Redirect failed. Please click on this link: <a href=http://www.harbour-place.com/login0.php>");
}
else{
exit(header("Location: http://www.harbour-place.com/login0.php?update=success"));
}
}
}
include_once 'includes/mailer2.php';
?>
<!-- Button trigger modal -->
<div class="row justify-content-center">
<button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#exampleModalCenter">
UPDATE
</button>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="userupdateform" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle">UPDATE RENTAL UNIT # <?php echo htmlentities($_SESSION['unit']) ?> </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<div class="form-row justify-content-center">
<div class="form-group col-md-4">
<label >First Name</label>
<input type="text" class="form-control form-control-sm <?php echo (!empty($error['name'])) ? 'is-invalid' : ''; ?>" name="first" value="<?php echo htmlentities($_SESSION['first']) ?>">
<span class="invalid-feedback"><?php echo $error['name']; ?></span>
</div>
<div class="form-group col-md-4">
<label >Last Name</label>
<input type="text" class="form-control form-control-sm" name="last" value=<?php echo htmlentities($_SESSION['last']) ?> required>
</div>
</div>
<div class="form-row justify-content-center">
<div class="form-group col-md-8">
<label >Email</label>
<input type="text" class="form-control form-control-sm" name="email" value=<?php echo htmlentities($_SESSION['email']) ?> required>
</div>
<!--<div class="form-group col-md-4">
<label >Unit</label>
<input type="text" class="form-control form-control-sm" name="unit" value=<php echo $_SESSION['u_unit'] ?> required>
</div>-->
</div>
<div class="form-row justify-content-center">
<div class="form-group col-md-2">
<label >Bed</label>
<input type="text" class="form-control form-control-sm" name="bed" value=<?php echo htmlentities($_SESSION['bed']) ?> required>
</div>
<div class="form-group col-md-2">
<label >Bath</label>
<input type="text" class="form-control form-control-sm" name="bath" value=<?php echo htmlentities($_SESSION['bath']) ?> required>
</div>
<div class="form-group col-md-4">
<label >Web Site - www.myunit.com</label>
<input type="text" class="form-control form-control-sm" name="web" value=<?php echo htmlentities($_SESSION['web']) ?> required>
</div>
</div>
<div class="form-row justify-content-center">
<div class="form-group col-md-3">
<label >Phone 000-000-0000</label>
<input type="text" id="yourphone2" class="form-control form-control-sm <?php echo (!empty($error['phone'])) ? 'is-invalid' : ''; ?>" name="phone" value="<?php echo htmlentities($_SESSION['phone']) ?>">
<span class="invalid-feedback"><?php echo $error['phone']; ?></span>
</div>
<div class="form-group col-md-5">
<label >Managment Co (VRBO, Self,etc)</label>
<input type="text-capitalize" class="form-control form-control-sm" name="manage" value="<?php echo htmlentities( $_SESSION['manage']) ?>" required>
</div> </div>
<!--<div class="form-row justify-content-center">
<div class="form-group col-md-8">
<label >Managment Co - VRBO etc.</label>
<input type="text" class="form-control form-control-sm" name="manage" value="" required>
</div></div>-->
<div class="form-row justify-content-center">
<div class="custom-control custom-checkbox">
<input type="hidden" name="rent" value="0">
<input type="checkbox" value="1" name="rent" class="custom-control-input" id="customCheck1" checked="checked">
<label class="custom-control-label" for="customCheck1">Check to show on the rental site</label>
</div></div>
<p class="text-center mb-1"><small><i class="fas fa-lock"></i>Your Information is Safe With us!<br> You will need to re-login after clicking Update<br>This also updates the HP rental website listing. </small></p>
<button type="submit" class="btn btn-primary btn-sm" name="update">UPDATE HP UNIT</button>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
There are a couple issues here
You are setting $error to a boolean value, trying to define an array key with a value on a boolean doesn't work, it will continue to just be a boolean [Edit] if the value of $error evaluates to false before assigning array key => values to it, it will convert to an array but if it evaluates to true it will result in Warning: Cannot use a scalar value as an array and continue to be a boolean
You are never checking $error to stop the script from executing and updating the database

PDO Update User Information Query

its me again :)
i'm almost done with my project theres only one more thing left.
i am not able to update values in my database using pdo.
this is my script
<a
href="?UpdateUser=' .$ID. '"
class="btn btn-sm btn-icon btn-pure btn-default on-default edit-row"
data-original-title="Bearbeiten"
ref="" data-toggle="modal" data-target="#EditUser">
<i class="icon wb-edit" aria-hidden="true"></i></a>
<div class="modal fade" id="EditUser" aria-hidden="false" aria-labelledby="EditUserModal"
role="dialog" tabindex="-1">
<div class="modal-dialog modal-simple modal-center">
<form class="modal-content" method="POST" role="form" action="">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="EditUserModal">Benutzer bearbeiten</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-xl-12 form-group">
<p><b>Username</b></p>
<input type="text" class="form-control" name="username" value="'.$username.'">
</div>
<div class="col-xl-4 form-group">
<p><b>Vorname</b></p>
<input type="text" class="form-control" name="vorname" value="'.$vorname.'">
</div>
<div class="col-xl-8 form-group">
<p><b>Nachname</b></p>
<input type="text" class="form-control" name="nachname" value="'.$nachname.'">
</div>
<div class="col-xl-8 form-group">
<p><b>Email</b></p>
<input type="email" class="form-control" name="email" value="'.$email.'">
</div>
<div class="col-xl-4 form-group">
<p><b>TelefonNr.</b></p>
<input type="text" class="form-control" name="handy" value="'.$handy.'">
</div>
<div class="col-xl-12 form-group">
<p><b>Admin</b></p>
<input type="text" class="form-control" name="admin" value="'.$admin.'">
</div>
<div class="col-md-12 float-right">
<button class="btn btn-primary btn-outline" data-dismiss="modal" type="submit">Speichern</button>
</div>
</div>
</div>
</form>
</div>
</div>
</td>
</tr>';
}
if(isset($_POST['UpdateUser']))
{
if($_POST['UpdateUser'])
{
$stmt = $odb->execute("UPDATE Account SET username = '$username' , vorname = '$vorname', nachname = '$nachname', email = '$email', handy = '$handy', admin = '$admin' WHERE id=? ");
}
echo "<meta http-equiv='refresh()' content='0'>";
}
am i doing a wrong query ? or why is it not updating?
there is no error showing up on the page, but the values are not updating nor refreshing the page.
You need to use prepare before execute, like this:
$query = 'UPDATE Account SET
username = :username,
vorname = :vorname,
nachname = :nachname,
email = :email,
handy = :handy,
admin = :admin
WHERE id = :id';
$stmt = $pdo->prepare($query);
$stmt->execute(array(
':username' => $username,
':vorname' => $vorname,
':nachname' => $nachname,
':email' => $email,
':handy' => $handy,
':admin' => $admin,
':id' => $id
));
Also, is better to use placeholders for every input value, instead of write variables inside the query string.
And now I figured out this:
You are using a form to send data with method POST and trying to read $_POST['UpdateUser'] to start executing the update, but in that form there is no field called UpdateUser.
You have to add that value inside the form, or change the if (isset($_POST['UpdateUser'])) with some other field.

Data aren't inserting into database PHP

I'm trying to add the data from my form into the database. But it's only refreshing. Here is my code for my form:
<form action="" method="post">
<div id="modal1" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>Bedroom</h4><br><br>
<div class="row">
<div class="input-field col s6">
<i class="material-icons prefix">account_circle</i>
<input name="txt_room_ID" id="txt_room_ID" type="text" class="validate" readonly="true"
value="<?php
$sql= "select * from tblBedroom";
$stmt = sqlsrv_query($con,$sql);
while($rs = sqlsrv_fetch_array($stmt)){
$Setting_adminID = $rs['BedRoomID'];
$adminID_new = str_replace("B","",$Setting_adminID);
$adminID = str_pad($adminID_new + 1,11,0,STR_PAD_LEFT);}
echo htmlentities('B'. $adminID);
?>">
<label for="room_ID">Bedroom ID:</label>
</div>
<div class="input-field col s6">
<i class="material-icons prefix">account_circle</i>
<input name="txt_bedroom_no" id="txt_bedroom_no" type="text" class="validate">
<label for="bedroom_no">Room Number</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<select name="txt_Room_Type">
<option value="" disabled selected>Choose Room Type</option>
<?php
$sql = "select * from tblBedRoomType";
$stmt = sqlsrv_query($con,$sql);
while($rs = sqlsrv_fetch_array($stmt)){
$BedroomTypeID = $rs['BedroomTypeID'];
$BedroomName = $rs['BedroomName'];
echo"<option value='$bedroomTypeID'>$BedroomName</option>";
}
?>
</select>
<label>Room Type</label>
</div>
</div>
</div><!--END OF MODAL CONTENT-->
<div class="modal-footer">
<a class="modal-action modal-close waves-effect waves-green btn-flat ">Cancel</a>
<input id="btn_Save" name="btn_Save" type="submit" value="Save" class="waves-effect waves-green btn-flat " onclick="return confirm('Are You Sure You Want To Save?');">
</div>
</div>
</form>
The php below the form:
<?php
if(isset($_POST['btn_Save'])){
$txt_room_ID = $_POST['txt_room_ID'];
$txt_bedroom_no = $_POST['txt_bedroom_no'];
$txt_Room_Type = $_POST['txt_Room_Type'];
$AcctStat = 1;
$sql = "insert into tblBedRoom (BedRoomID,BedroomType,RoomNo,AcctStat)
values('$txt_room_ID','$txt_Room_Type','$txt_bedroom_no','$AcctStat')";
$stmt = sqlsrv_query($con,$sql);
echo "<meta http-equiv='refresh' content='0'>";
}
?>
And my columns in my tblBedRoom are:
BedRoomID | BedroomType | RoomNo |AcctStat

If value already exists in array then issue an error in PHP

I have a code wherein it checks if a value already exists in the array. Basically, what the program does is that it first stores all the values in the array. Then it will be checked using count(array_keys) function. There are three inputs. If in those 3 inputs, a value occurs twice or thrice, it will issue an error. Now, my problem is that if INPUT A AND INPUT B IS THE SAME BUT INPUT C is different, it will still add to the database, BUT IF INPUT A AND C IS THE SAME BUT INPUT B is different then it will not add (which is correct).
Here is my php code:
<?php
include 'config.php';
if(isset($_POST['update_actual_lupong'])){
$id = isset($_GET['id'])? $_GET['id'] : "";
$id_hearing = $_POST['hearing_lup'];
$lupong = $_POST['act_lupong'];
$actual = array();
foreach($lupong as $aaa) {
$actual[] = $aaa;
}
if ((count(array_keys($actual, $aaa)) > 1)) {
echo '<br><br>this array contains DUPLICATE <br><br>';
}
else {
foreach ($lupong as $lup) {
$updateMemo = mysqli_query($conn, "INSERT INTO actuallupong(Hearing_idHearing, bar_pos2) VALUES ('$id_hearing', (SELECT idtable_position FROM table_position WHERE Person_idPerson = '$lup'));");
}
echo "ADDED ggg";
}
//header ('location: view_case_profile.php?id='.$id);
mysqli_close($conn);
}
?>
HTML code (it's in a modal):
<div class="modal fade bs-example-modal-lg" id="modal_lupong" data-backdrop="static" data-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" >
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel">Update Lupong</h4>
</div>
<form id="update_actual_lupong" class="form-horizontal form-label-left calender" name = "update_actual_lupong" enctype="multipart/form-data" method="post" role="form" novalidate>
<div class="modal-body">
<div class="d item form-group">
<label class="col-sm-3 control-label">Hearing Number</label>
<div class="col-sm-7">
<input type="number" class="form-control" id="hearing_lup" name="hearing_lup" readonly="readonly"/>
</div>
</div>
<div class="f item form-group" id = "act1">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Lupong 1 <span class="required">*</span></label>
<div class="col-sm-7">
<input name="actlupong[]" id="search_keyword_id_act" class="search_keyword_act form-control col-md-7 col-xs-12" required="required" placeholder ="Search first name or last name... " type="text">
<input type="hidden" name="act_lupong[]" id="act_lup1"/>
<div id="result3"></div>
</div>
</div>
<div class="f item form-group" id = "act2">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Lupong 2 <span class="required">*</span></label>
<div class="col-sm-7">
<input name="actlupong[]" id="search_keyword_id_act1" class="search_keyword_act1 form-control col-md-7 col-xs-12" required="required" placeholder ="Search first name or last name... " type="text">
<input type="hidden" name="act_lupong[]" id="act_lup2"/>
<div id="result4"></div>
</div>
</div>
<div class="f item form-group" id = "act3">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Lupong 3 <span class="required">*</span></label>
<div class="col-sm-7">
<input name="actlupong[]" id="search_keyword_id_act2" class="search_keyword_act2 form-control col-md-7 col-xs-12" required="required" placeholder ="Search first name or last name... " type="text">
<input type="hidden" name="act_lupong[]" id="act_lup3"/>
<div id="result5"></div>
</div>
</div>
</div>
<div class="modal-footer" style="margin:0;">
<button type="button" class="btn btn-default" data-dismiss="modal" style="margin-top: 4px;">Close</button>
<button id="send" type="submit" class="btn btn-success" name="update_actual_lupong">Save Record</button>
</div>
</form>
</div>
</div>
</div>
Screenshot:
What seems to be wrong in my code? Which part should I change? Your help will be much appreciated. Thank you.
As you said:- There are three inputs. If in those 3 inputs, a value occurs twice or thrice, it will issue an error.
A bit modification to your code needed:-
<?php
include 'config.php';
if(isset($_POST['update_actual_lupong'])){
$id = isset($_GET['id'])? $_GET['id'] : "";
$id_hearing = $_POST['hearing_lup'];
$lupong = $_POST['act_lupong'];
if (count(array_unique($lupong)) < count($lupong))) { // check that count of unique $lupong and original $lupong is equal or not if not then $lupong have duplicate values
echo '<br><br>this array contains DUPLICATE <br><br>';
}
else {
foreach ($lupong as $lup) {
$updateMemo = mysqli_query($conn, "INSERT INTO actuallupong(Hearing_idHearing, bar_pos2) VALUES ('$id_hearing', (SELECT idtable_position FROM table_position WHERE Person_idPerson = '$lup'));");
}
echo "ADDED ggg";
}
//header ('location: view_case_profile.php?id='.$id);
mysqli_close($conn);
}
?>
You exit the loop with $aaa as the value of c so only check this value for duplication.
You should check for duplicates inside the loop and set a variable i.e.
$dup = false;
foreach($lupong as $aaa) {
$actual[] = $aaa;
if ((count(array_keys($actual, $aaa)) > 1)) {
$dup = true;
}
}
if ($dup) {
echo '<br><br>this array contains DUPLICATE <br><br>';
}
else {
foreach ($lupong as $lup) {
$updateMemo = mysqli_query($conn, "INSERT INTO actuallupong(Hearing_idHearing, bar_pos2) VALUES ('$id_hearing', (SELECT idtable_position FROM table_position WHERE Person_idPerson = '$lup'));");
}
echo "ADDED ggg";
}

Categories