Currently looking to implement functionality to edit details in MySQL database via a HTML page. The page itself shows all data in the database which matches the unique id of the user who is is logged in via a PHP session and echos that data to input boxes in a while loop.
When the user makes changes to the input text and hits the save changes link it then calls the edit endpoint which in turn calls the edit SQL function in a functions file.
I'm using an anchor tag wrapped in a button to send the id of the row that is being edited and all this sits inside a POST action form.
However the input texts are only showing as blank as if the endpoint is not receiving the text in the input field, and despite trying quite a few different methods I can't seem to get a result.
Code for Web page (not whole page but only concerned code)
<?php
$connect =mysqli_connect('localhost','root','','micaddy');
$id_query = mysqli_query($connect, "SELECT unique_id FROM users WHERE email = '{$_SESSION['login_user']}'");
$id_array = mysqli_fetch_assoc($id_query);
$uid = $id_array['unique_id'];
$result = mysqli_query($connect, "SELECT * FROM clubs WHERE user_id =
'$uid'");
?>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading clearfix"><h3 class="panel-title"><strong>Your Golfbag</strong><button type="button" class="btn btn-info btn-lg pull-right" data-toggle="modal" data-target="#addModal">Add Club</button></h3></div>
<?php while($row=mysqli_fetch_assoc($result)):?>
  <span><?php if(isset($_SESSION['message'])){ echo $_SESSION['message']; unset($_SESSION['message']);} ?></span>
<div class="panel-body">
<div class="container-fluid">
<div class="row">
<div class="col-md-5">
<div class="panel panel-default">
<div class="panel-heading"><h3 class="panel-title"><strong><?php echo $row['club_type'];?></strong></h3></div>
<div class="panel-body">
<form id="" method="POST" action="editClub.php">
<div class="form-group">
<label for="clubType">Club ID</label>
<input type="text" readonly="" class="form-control" id="inputClubType" value="<?php echo $row['id'];?>" name="clubIdInput">
</div>
<div class="form-group">
<label for="clubBrand">Type</label>
<input type="text" class="form-control" id="inputclubBrand" value="<?php echo $row['club_type'];?>" name="clubTypeInput">
</div>
<div class="form-group">
<label for="clubBrand">Brand</label>
<input type="text" class="form-control" id="inputclubBrand" value="<?php echo $row['brand'];?>" name="clubBrandInput">
</div>
<div class="form-group">
<label for="clubNum">Number or Type</label>
<input type="text" class="form-control" id="inputclubNum" value="<?php echo $row['club_number'];?>" name="clubNumInput">
</div>
<div id="deleteClub">
<button id="submitChange" type="button" class="btn btn-danger btn-lg"><?php echo "<a href='deleteClub.php?id=".$row['id']."'>Delete</a>" ?></button>
<button type="button" class="btn btn-info btn-lg"><?php echo "<a href='editClub.php?id=".$row['id']."'>Save Changes</a>" ?></button>
</div>
<span><?php if(isset($_SESSION['message'])){ echo $_SESSION['message']; unset($_SESSION['message']);} ?></span>
</form>
</div>
</div>
</div>
<div class="col-md-5">
<div class="panel panel-default">
<div class="panel-heading"><h3 class="panel-title"><strong>Club Image</strong></h3></div>
<div class="panel-body">
<div class="form-group">
<img src="club_images/<?php echo $row['clubImg']; ?>" class="img-rounded" width="250px" height="250px" alt="Image"/>
</div>
</div>
</div>
</div>
</div>
</div>
<span><?php if(isset($_SESSION['message'])){ echo $_SESSION['message']; unset($_SESSION['message']);} ?></span>
</div>
<?php endwhile;?>
</div>
</div>
</div>
</div>
The edit endpoint:
<?php
session_start();
$error='';
require_once '../include/DB_Functions.php';
$db = new DB_Functions();
if(empty($_POST['clubBrandInput']) || empty($_POST['clubNumInput'])){
$_SESSION['message'] = "Warning: Some fields are blank! Please try again";
header("Location: golfbag.php");
} else{
if(isset($_POST['clubBrandInput']) && isset($_POST['clubTypeInput']) && isset($_POST['clubNumInput'])){
$brand = $_POST['clubBrandInput'];
$type = $_POST['clubTypeInput'];
$num = $_POST['clubNumInput'];
$id = $_GET['id'];
$club = $db->editclub($brand, $type, $num, $id);
if($club) {
header("Location: golfbag.php");
$_SESSION['message'] = "Success! Details edited.";
}else{
header("Location: golfbag.php");
echo $error;
}
}
}
?>
The function method:
public function editClub($brand, $type, $num, $id){
$stmt = $this->conn->prepare("UPDATE clubs SET brand = '$brand', club_type = '$type', club_number = '$num' WHERE id = '$id'");
$result = $stmt->execute();
$stmt->close();
if($result){
$stmt = $this->conn->prepare("SELECT * FROM clubs WHERE user_id = ?");
$stmt->bind_param("s", $uid);
$stmt->execute();
$club = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $club;
}else{
return false;
}
}
You do not have a <form> defined in this HTML.
You are also clicking an anchor link <button id="submitChange" type="button" class="btn btn-danger btn-lg"><?php echo "<a href='deleteClub.php?id=".$row['id']."'>Delete</a>" ?></button>
even though it is in a button.
Therefore you will only pass the id=".$row['id']." parameter to the endpoint and that will be passed in the $_GET array and not the $_POST array
Related
Good morning, I am dealing with an existing code and I need to solve a problem:
When you write a URL without logging into the Web, you can see the page in question (except the layout), what I need is to redirect to the login to avoid this.
So you can see the page without logging in
Checking the code I have seen that it is like this:
layout.php
<body>
<?php if(isset($_SESSION["user_id"])):?>
HTML code (Logo, menu...)
<?php else:?>
<?php
View::load("login");
?>
<?php endif;?>
</body>
If I change "View::load("login");" to "header("Location: index.php"); exit();", it causes an Infinite loop and does not load anything.
I have investigated a lot in Stackoverflow and other websites but I do not find the solution. Any ideas?
UPDATE:
index-view.php
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>LegoBox</h1>
</div>
</div>
</div>
login-view.php
<?php
if(Session::getUID()!=""){
print "<script>window.location='index.php?view=home';</script>";
}
?>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<?php if(isset($_COOKIE['password_updated'])):?>
<div class="alert alert-success">
<p><i class='glyphicon glyphicon-off'></i> Se ha cambiado la contraseña exitosamente.</p>
<p>Pruebe iniciar sesion con su nueva contraseña.</p>
</div>
<?php setcookie("password_updated","",time()-18600);
endif; ?>
<div class="card">
<div class="card-header" data-background-color="lemon">
<h4 class="title">Acceder</h4>
</div>
<div class="card-content table-responsive">
<form accept-charset="UTF-8" role="form" method="post" action="index.php?view=processlogin">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Usuario" name="mail" type="text">
</div>
<div class="form-group">
<input class="form-control" placeholder="Contraseña" name="password" type="password" value="">
</div>
<input class="btn btn-primary btn-block" type="submit" value="Iniciar Sesion" style="background-color:#339c24">
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
processlogin-view.php
<?php
if(Session::getUID()=="") {
$user = $_POST['mail'];
$pass = sha1(md5($_POST['password']));
$base = new Database();
$con = $base->connect();
$sql = "select * from user where (email= \"".$user."\" or username= \"".$user."\") and password= \"".$pass."\" and is_active=1";
//print $sql;
$query = $con->query($sql);
$found = false;
$userid = null;
while($r = $query->fetch_array()){
$found = true ;
$userid = $r['id'];
}
if($found==true) {
// print $userid;
ini_set('session.cookie_lifetime', 60 * 60 * 24 * 7);
$_SESSION['user_id']=$userid;
// setcookie('userid',$userid);
// print $_SESSION['userid'];
print "Cargando ... $user";
print "<script>window.location='index.php?view=home';</script>";
}else {
print "<script>window.location='index.php?view=login';</script>";
}
}else{
print "<script>window.location='index.php?view=home';</script>";
}
?>
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']
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hope someone can help. I have a profile page that I want to display the logged in users details. So far I have this on the Profile page.
<?php
/* This script pulls the existing name input and displays it when the user logs in. */
session_start();
include("db.php"); ?>
<?php include("includes/header.php") ?>
<?php include("includes/nav.php") ?>
<?php
if(logged_in()) {
$result = mysqli_query($link,$query);
$row = mysqli_fetch_array($result);
if (!$_POST['name'] && $_POST['name']=="") $error.="<br />Please enter your name";
if (!$_POST['email'] && $_POST['email']=="") $error.="<br />Please enter your email";
if (!$_POST['DOB'] && $_POST['DOB']=="") $error.="<br />Please enter your date of birth";
if (!$_POST['country'] && $_POST['country']=="") $error.="<br />Please enter your country";
if ($error) {
echo '<div class="alert alert-success alert-dismissable">'.addslashes($error).'</div>';
}
if(isset($_POST['form-control'])) {
move_uploaded_file($_FILES['file']['tmp_name'],"img/".$_FILES['file']['name']);
$query = mysqli_query("UPDATE users SET image = '".$_FILES['file']['name']."'");
}
} else {
redirect("login.php");
}
?>
<Style>
.alert{
display:none;
}
#profileimg {
height: 100px;
width: auto;
}
</Style>
<div class="container">
<h1>Edit Profile</h1>
<hr>
<div class="row">
<!-- left column -->
<div class="col-md-3">
<div class="text-center">
<img src="//placehold.it/100" class="avatar img-circle" alt="avatar" id="profileimg">
<h6>Upload a different photo...</h6>
<input class="form-control" type="file" name="name">
</div>
</div>
<!-- edit form column -->
<div class="col-md-9 personal-info">
<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>Profile updated.</strong>
</div>
<h3>Personal info</h3>
<form class="form-horizontal" role="form" action="edit_profile.php" method="post">
<div class="form-group">
<label class="col-lg-3 control-label name">name:</label>
<div class="col-lg-8">
<input class="form-control" value="<?php echo $row['name'];?>" type="text" name="name" required>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email:</label>
<div class="col-lg-8">
<input class="form-control" value="<?php echo $row['email'];?>" type="text" name="email" required>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">DOB:</label>
<div class="col-lg-8">
<input class="form-control" value="<?php echo $row['DOB'];?>" type="date" name="DOB" required>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Country</label>
<div class="col-lg-8">
<input class="form-control" value="<?php echo $row['country'];?>" type="text" name="country" required>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label"></label>
<div class="col-md-8">
<input class="btn btn-primary" value="Save Changes" type="submit">
<span></span>
<input class="btn btn-default" id="updated" value="Cancel" type="reset">
</div>
</div>
</form>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<script>
$("#updated").click(function(){
$(".alert").hide().show('medium');
</script>
</body>
</html>
I then have another php file for the updating which is this:
<?php
session_start();
include("db.php");
$name = $_POST['name'];
$email = $_POST['email'];
$DOB = $_POST['DOB'];
$country = $_POST['country'];
$password = md5($salt.$_POST['password']);
$query = "UPDATE users SET name = '".$name."', email = '".$email."', DOB = '".$DOB."', country = '".$country."', password = '".$password."'";
$result = mysqli_query($link,$query);
header('Location: profile.php');
?>
So the short is it doesn't display or update and I am not sure why. I am new to PHP so go easy on me if this is simple, I have searched but can't seem to find the answer.
Thanks in advance.
Im also new to this but normally when I check if a SESSION id is active I use
if(isset($_SESSION['id'])) {
$query = "UPDATE users SET name = '".$name."', email = '".$email."', DOB = '".$DOB."', country = '".$country."', password = '".$password."' WHERE id='".$_SESSION['id']."'";
}
You also need to echo back the indexed rows that you are trying to query to display results
$name = row['username'];
echo $name;
There are lots of errors in your code: You are trying to upload a file in the same page whereas you send the form data to another page. How you handle form validation is also a little overhead. What I did change in the form is: I add name="save" in your submit button and added new hidden input for storing your user profile id. I am not sure what login() function did in your code, better stick to if($id){}.
Try this:
<?php
/* This script pulls the existing name input
and displays it when the user logs in. */
session_start();
include("db.php");
include("includes/header.php");
include("includes/nav.php");
$id = $_SESSION['id'];
if(loginned()) {//you can do if($id){}
$query="SELECT * FROM users WHERE id='$id' LIMIT 1";
$result = mysqli_query($link,$query);
$row = mysqli_fetch_array($result);
?>
<style>
.alert{
display:none;
}
#profileimg {
height: 100px;
width: auto;
}
</style>
<div class="container">
<h1>Edit Profile</h1>
<hr>
<div class="row">
<!-- left column -->
<!-- edit form column -->
<div class="col-md-9 personal-info">
<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert"
aria-hidden="true">×</button>
<strong>Profile updated.</strong>
</div>
<h3>Personal info</h3>
<form class="form-horizontal" role="form"
action="edit_profile.php" method="post">
<div class="form-group">
<label class="col-lg-3 control-label name">name:</label>
<div class="col-lg-8">
<input class="form-control" value="<?php echo $row['name'];?>"
type="text" name="name" required>
</div>
</div>
<div class="col-md-3">
<div class="text-center">
<img src="//placehold.it/100" class="avatar
img-circle" alt="avatar" id="profileimg">
<h6>Upload a different photo...</h6>
<input class="form-control" type="file" name="name">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email:</label>
<div class="col-lg-8">
<input class="form-control" value="<?php echo $row['email'];?>"
type="text" name="email" required>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">DOB:</label>
<div class="col-lg-8">
<input class="form-control" value="<?php echo $row['DOB'];?>"
type="date" name="DOB" required>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Country</label>
<div class="col-lg-8">
<input class="form-control" value="<?php echo $row['country'];?>"
type="text" name="country" required>
</div>
</div>
<div class="form-group">
<input type="hidden" name="id" value="<?php echo $row['id'];?>">
<label class="col-md-3 control-label"></label>
<div class="col-md-8">
<input class="btn btn-primary" name="save"
value="Save Changes" type="submit">
<span></span>
<input class="btn btn-default" id="updated"
value="Cancel" type="reset">
</div>
</div>
</form>
</div>
<?php }else{ redirect("login.php"); } ?>
edit_profile.php First we check whether any post with a name of save is there, We validate the posted data. if validation is successful, we proceed to upload your file and then run your update query.
<?php
session_start();
include("db.php");
if(isset($_POST['save'])){
$id = isset($_POST['id'])? $_POST['id']:'';
$name = isset($_POST['name'])? $_POST['name']:'';
$email = isset($_POST['email'])? $_POST['email']:'';
$dob = isset($_POST['DOB'])? $_POST['DOB']:'';
$pass = isset($_POST['passwrd'])? md5($salt.$_POST['password']):'';
$country = isset($_POST['country'])? $_POST['country']:'';
if(empty($name)){
$error = 'Please enter your name';
}elseif(empty($email)){
$error = 'Please enter your email';
}elseif(empty($dob)){
$error = 'Please enter your date of birth';
}elseif(empty($country)){
$error = 'Please enter your country';
}elseif(empty($pass)){
$error = 'Please enter your password';
}else{
move_uploaded_file($_FILES['file']['tmp_name'],"img/".$_FILES['file']['name']);
$query = mysqli_query("UPDATE users SET image = '".$_FILES['file']['name']."'
WHERE id='$id'");
$query = "UPDATE users SET name = '$name', email = '$email',
DOB = '$DOB', country = '$country', password = '$password'
WHERE id='$id'";
$result = mysqli_query($link,$query);
header('Location: profile.php');
}
}
?>
<?php if(!empty($error)){
echo '<div class="alert alert-success
alert-dismissable">'.addslashes($error).'</div>';
}else{
echo '<div class="alert alert-success">Success</div>';
}
?>
I have added a demo here. At least this will help:
I have a form to enter some details,in that one select control is there,to select some option(Audit ID) .IF the user could not find the correct option,then he can add in using another button in the same form beside of that select control.By clicking that button one modal-form will appear and the input control is there,entering data and saving it,will save that value in one table (table : auditnumber). And the main form will save all entered data in another table(auditplan).So i have two submit buttons saving different value to different tables and the modal form is just optional..in case user didnt find exact option.
Just i tried these code below..but didnt work. the modal form submit button didnt work.
And i dont know whether this one is good idea. Just im beginner in web app.
<?php
include("config.php");
include("header.php");
session_start();
try {
$sql = "SELECT * FROM auditnumber";
$stmt = $DB->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
}
catch (Exception $ex)
{ echo $ex->getMessage(); }
?>
<div class="col-md-10 main">
<form class="form-horizontal" role="form" action="auditplanentry.php" method="POST">
<div class="form-group">
<label class="control-label col-sm-2" for="usr">Audit ID:</label>
<div class="col-sm-5">
<select id="course" name="course" class="form-control" ><option>Select</option>
<?php foreach($result as $row){ ?>
<option><?php echo $row['auditnumber']?></option>
<?php }
?>
</select>
</div>
<button type="button" class="btn btn-primary btn-circle" rel="tooltip" title="Add audit ID,if not present in select option" data-toggle="modal" data-target="#auditidmodal"><i class="glyphicon glyphicon-plus"></i></button>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Year:</label>
<div class="col-sm-5">
<input type="text" class="form-control col-xs-3" id="year" name ="year">
</div>
</div>
<div class="form-group">
<div class=" col-sm-offset-3">
<button type="submit" name="submit" id ="submit" class="btn btn-primary">Save</button>
<button type="submit" name="submit1" id ="clear" class="btn btn-primary">Cancel</button>
</div>
</div>
</form>
</div>
<?php
if(isset($_POST['submit']))
{
if(trim($_POST['auditid'])=='')
{
echo "<script language='javascript'>alert('Please Enter Audit ID.');</script>";
exit;
}
elseif(trim($_POST['year'])=='')
{
echo "<script language='javascript'>alert('Please Enter Year.');</script>";
exit;
}
$audit=trim($_REQUEST['auditid']);
$year=trim($_REQUEST['year']);
$sql = "INSERT INTO auditplan(auditid,year) VALUES " . "(:audit, :year)";
try {
$stmt = $DB->prepare($sql);
// bind the values
$stmt->bindValue(":audit", $audit);
$stmt->bindValue(":year", $year);
// execute Query
$stmt->execute();
}
catch (Exception $ex)
{
$_SESSION["errorType"] = "danger";
$_SESSION["errorMsg"] = $ex->getMessage();
}
}
elseif(isset($_POST['submit1']))
{
echo "<script language='javascript'>document.location.href='Auditplan.php';</script>";
}
?>
<div class="modal" id="auditidmodal" tabindex="-1" role="dialog" aria-labelledby="messageModelLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<form id="auditidform" role="form" action="auditplanentry.php" method="POST">
<div class="control-group">
<label class="control-label" for="leave_status">Enter Audit ID:</label>
<div class="controls">
<input id="audit" class="form-control" name="audit" placeholder="Eg: IA01" ></input>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="submit" name="save" id ="save" >Save</button>
<button class="btn" type="submit" name="clear" id ="clear">Cancel</button>
</div>
</div>
</div>
</div>
<?php
if(isset($_POST['save']))
{
if(trim($_POST['audit'])=='')
{
echo "<script language='javascript'>alert('Please Enter Audit ID.');</script>";
exit;
}
$audit=trim($_REQUEST['audit']);
$sql = "INSERT INTO auditnumber(auditid) VALUES " . "(:audit)";
try {
$stmt = $DB->prepare($sql);
$stmt->bindValue(":audit", $audit);
$stmt->execute();
}
catch (Exception $ex)
{
$_SESSION["errorType"] = "danger";
$_SESSION["errorMsg"] = $ex->getMessage();
}
}
elseif(isset($_POST['clear']))
{
echo "<script language='javascript'>document.location.href='Auditplanentry.php';</script>";
}
?>
Please guys my code isn't working and i don't know what to do anymore. All i'm trying to accomplish is a simple mysql update using php. The header query value works at the top of my code which i use to insert values in the form, but when i attempt to submit, for some reason unknown to me, my script succeeds but it doesn't update the database. The result of clicking the submit will be my "Javascript success alert" then " all the variables in my page become Undefined. My script is below.
<?php
//Catch the id from the header and query database
if(isset($_GET['id']))
$workID= mysqli_real_escape_string($connection, $_GET['id']);
$query = "SELECT * FROM music WHERE musicID = $workID";
$result= mysqli_query($connection, $query);
$row = mysqli_fetch_array($result);
$artID = $row['IDartiste'];
$query2 = mysqli_query($connection,"SELECT music.*, artiste.* FROM music INNER JOIN artiste ON music.IDartiste=artiste.artisteID WHERE artiste.artisteID = $artID");
$row2 = mysqli_fetch_array($query2);
?>
**This is the form for editing**
<form role="form" method="get" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<!-- Artiste name field--> <div class="form-group">
<span><label for="topic" style="color: #55AAFF">Artiste ID: </span> <span><?php echo $row['IDartiste'];?></span></label>
<!-- Article topic field--> <div class="form-group">
<label for="topic" style="color: #55AAFF">Music title:</label>
<input type="text" class="form-control" name="title" value="<?php echo $row['musicTitle'];?>" autofocus>
</div>
<!--Article textarea--> <div class="form-group">
<label for="body" style="color: #55AAFF">Content (text):</label>
<textarea name="article" class="form-control"><?php echo $row['musicArticle'];?>
</textarea>
</div>
<!-- Upload image start--> <div class="col-ms-6 col-xs-12" >
<div class="panel panel-default">
<div class="panel-heading" style="color: #55AAFF">Upload Image</div>
<div class="panel-body">
<iframe src="fileupload.php" width="100%" style="border:none"></iframe>
</div>
</div>
</div>
<!--Image link field--> <div class="form-group">
<label for="image_link" style="color: #55AAFF">Input image link: </label>
<input type="text" name="image" value="<?php echo $row['musicPhoto'];?>" class="form-control"/>
</div>
<!-- Upload music start--> <div class="col-ms-6 col-xs-12" >
<div class="panel panel-default">
<div class="panel-heading" style="color: #55AAFF">Upload Music</div>
<div class="panel-body">
<iframe src="music_file_upload.php" width="100%" style="border:none"></iframe>
</div>
</div>
</div>
<!--Music link field--> <div class="form-group">
<label for="music_link" style="color: #55AAFF">Input music link: </label>
<input type="text" name="file" class="form-control" value="<?php echo $row['musicFile'];?>"/>
</div>
<center>....<button type="submit" class="btn btn-default" id="btnsubmit" name="btnsubmit" style="color: #55AAFF">Update</button>....</center>
<br />
</form>
This is the update script
<?php
if(isset($_GET['btnsubmit'])){
date_default_timezone_set('Africa/Lagos');
$setdate= date('Y-m-d-h-m-s');
$date= strftime($setdate);
$time= strftime('%X');
$title = $_GET["title"];
$article = $_GET["article"];
$artisteImage = $_GET["image"];
$musicFile = $_GET["file"];
$sql_music = "UPDATE kingdomjoy.music SET musicTitle = '$title',
musicFile = '$musicFile',
musicPhoto = '$artisteImage',
musicArticle = '$article',
entryDate = '$date'
WHERE musicID = '$workID' LIMIT 1";
$musicupdate = $connection->query($sql_music);
if ($musicupdate === FALSE) {
echo "Error: " . die(mysqli_error($connection));}
else {echo"<script>swal('Success! music library updated')</script>";}
}
?>