Sending value of the value attribute to other php page? - php

I'm try to send the value from the value attribute in button using a form that use the method POST in "landlord_home.php". The problem was that when I click on the button to go to the next page which is "edit_post.php", it execute the php validation code in that page and display the validation error in that page.
How can I pass the value to "edit_post.php" without using a form(POST or GET method) or is there any other way?
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo '<tr>
<td>' . $row['property_id'] . '</td>
<td>' . $row['username']. '</td>
<td>' . $row['property_type']. '</td>
<td>RM' . $row['property_price']. '</td>
<td>' . $row['address']. '</td>
<td>' . $row['location']. '</td>
<td>
<img src="data:property_type;base64,' .
$row['property_picture'] .
'" class="img-thumbnail" width="100" height="100">
</td>
<td>' . $row['title'] . '</td>
<td>' . $row['description'] . '</td>
<td>' . date('F d, Y h:mA', strtotime($row['reg_date'])) . '</td>
<td>
<form action="edit_post.php" method="POST">
<button class="btn btn-success btn-sm" name="edit" value="' .
$row['property_id'] . '">
Edit
</button>
<br>
<button class="btn btn-danger btn-sm" name="delete"
value="'.$row['property_id'] . '">
Delete
</button>
</form>
</td>
</tr>';
}
echo '</table>';
Above is the code from "landlord_home.php". Below is the part of code that I am talking about from above code.
<form action="edit_post.php" method="POST">
<button class="btn btn-success btn-sm" name="edit" value="' .
$row['property_id'] . '">
Edit
</button>
<br>
<button class="btn btn-danger btn-sm" name="delete" value="' .
$row['property_id'] . '">
Delete
</button>
</form>
And below is the code of the next page "edit_post.php"
session_start();
$user = $_SESSION['username'];
if(!isset($_SESSION['username'])) {
require('login_tools_landlord.php');
load();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Edit Property</title>
<link rel="stylesheet" href="css/add_property.css">
<link rel="stylesheet" href="css/header.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
</head>
<body>
<?php include 'includes/header_landlord.php' ?>
<div class="container wrapper">
<div class="text-center title_bar">
<h3>Fill in your property details</h3>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require ('core/connect_db.php');
$errors = array();
if (isset($_POST['edit'])) {
$edit = $_POST['edit'];
$q = "SELECT * FROM property WHERE property_id = '$edit'";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
$prop_type = $row['property_type'];
$price = $row['property_price'];
$address = $row['address'];
$location = $row['location'];
$pic = $row['property_picture'];
$title = $row['title'];
$desc = $row['description'];
$dt = $row['reg_date'];
if (empty($_POST['property_type'])) {
$errors[] = 'Choose property type.';
} else {
$pr = mysqli_real_escape_string($dbc, trim($_POST['property_type']));
}
if (empty($_POST['price'])) {
$errors[] = 'Enter your property price.';
} else {
$p = mysqli_real_escape_string($dbc, trim($_POST['price']));
}
if (empty($_POST['address'])) {
$errors[] = 'Enter your address.';
} else {
$ad = mysqli_real_escape_string($dbc, trim($_POST['address']));
}
if (empty($_POST['location'])) {
$errors[] = 'Choose your location.';
} else {
$lo = mysqli_real_escape_string($dbc, trim($_POST['location']));
}
// if (empty($_POST['picture'])) {
// $errors[] = 'Pick a picture.';
// } else {
// $pc = mysqli_real_escape_string($dbc, trim($_POST['picture']));
// }
if (isset($_POST['submit'])) {
if (getimagesize($_FILES['picture']['tmp_name']) == FALSE) {
$errors[] = "Please select an image.";
} else {
$picture = addslashes($_FILES['picture']['tmp_name']);
$name = addslashes($_FILES['picture']['name']);
$picture = file_get_contents($picture);
$picture = base64_encode($picture);
}
}
if (empty($_POST['title'])) {
$errors[] = 'Enter your title.';
} else {
$ti = mysqli_real_escape_string($dbc, trim($_POST['title']));
}
if (empty($_POST['description'])) {
$errors[] = 'Enter your description.';
} else {
$de = mysqli_real_escape_string($dbc, trim($_POST['description']));
}
if (empty($errors)) {
$qa = "
UPDATE property
SET property_type = '$pr', property_price = '$p', address = '$ad',
location = '$lo', property_picture = '$picture', title = '$ti',
description = '$de', reg_date = NOW()
WHERE property_type = '$prop_type', property_price = '$price',
address = '$address', location = '$location',
property_picture = '$pic', title = '$title',
description = '$desc', reg_date = '$dt'
";
$ra = mysqli_query($dbc, $qa);
if ($ra) {
echo '<h1 class="sccs_msg">Successful</h1>
<p class="sccs_msg">REDIRECTING YOU TO DASHBOARD in 3 SECOND</p>
<meta http-equiv="refresh" content="3;URL=landlord_home.php" />';
}
mysqli_close($dbc);
exit();
} else {
echo '<h1 class="err_msg">ERROR!</h1>
<p class="err_msg">The following error(s) occurred:<br>';
foreach ($errors as $msg) {
echo "- $msg<br>";
}
echo 'Please try again.</p>';
mysqli_close($dbc);
}
}
}
?>
</div>
<form method="post" action="edit_post.php" enctype="multipart/form-data">
<div class="form-group">
<label for="property_type">Property Type</label>
<select class="form-control" name="property_type" id="property_type"
value="<?php
if (isset($_POST['property_type'])) {
echo $_POST['property_type'];
}
?>">
<option></option>
<option>Room</option>
<option>Whole Unit</option>
</select>
</div>
<div class="form-group">
<label for="price">Unit Price(RM)</label>
<input type="text" class="form-control" name="price" id="unit_price"
placeholder="Unit Price" value="<?php
if (isset($_POST['price'])) {
echo $_POST['price'];
}
?>">
</div>
<div class="form-group">
<label for="address">Address</label>
<textarea class="form-control" name="address" id="address" rows="3"
value="<?php
if (isset($_POST['address'])) {
echo $_POST['address'];
}
?>"></textarea>
</div>
<div class="form-group">
<label for="location">Location</label>
<select class="form-control" name="location" id="location"
value="<?php
if (isset($_POST['location'])) {
echo $_POST['location'];
}
?>">
<optgroup label="Kuala Lumpur">
<option></option>
<option>Puchong</option>
<option>Salak Selatan</option>
<option>Segambut</option>
<option>Sentul</option>
<option>Seputih</option>
</optgroup>
<optgroup label="Selangor">
<option>Cheras</option>
<option>Damansara</option>
<option>Cyberjaya</option>
<option>Kajang</option>
<option>Kelana Jaya</option>
</optgroup>
</select>
</div>
<div class="form-group">
<label for="picture">Picture</label>
<input type="file" class="form-control-file" name="picture"
id="picture" aria-describedby="fileHelp"
value="<?php
if (isset($_POST['picture'])) {
echo $_POST['picture'];
}
?>">
<small id="fileHelp" class="form-text text-muted">
Please provide a photo of your property.
</small>
</div>
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="title" id="title"
placeholder="Post Title" value="<?php
if (isset($_POST['title'])) {
echo $_POST['title'];
}
?>">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" name="description" id="description"
rows="3" value="<?php
if (isset($_POST['description'])) {
echo $_POST['description'];
}
?>"></textarea>
</div>
<button type="submit" class="btn btn-primary" name="submit">
Submit
</button>
</form>
</div>
</body>
</html>

How can I pass the value to "edit_post.php" without using a form(POST or GET method) or is there any other way?
I'm not sure to understand what you mean above, unless you wanted to say without using an additional visible form input.
If so, then the answer is contained in the question: you have merely to add a hidden input to your form (and give up buttons value):
<form action="edit_post.php" method="POST">
<input type="hidden" name="property-id" value=" . $row['property_id'] . '">
<button class="btn btn-success btn-sm" name="edit">
Edit
</button>
<br>
<button class="btn btn-danger btn-sm" name="delete">
Delete
</button>
</form>
Then in edit_post.php you can use $_POST['property-id'] as you want.
BTW I'm a bit surprised looking at your $qa query in edit_post.php: unless I missed something subtle, its WHERE clause is invalid, since it's built like a comma-separated list of condition (while they probably should be ANDed).

Related

Trying to show the updated msql row after successfully updating a form using php

I would like to have a confirmation page where it can show what are the results of an updated form using php.
I have the edit.php form, and I also created an updated.php page, where I want to show the results of the edited rows.
edit.php
<?php
//get ID sent by GET collection
$parentID = $_GET['id'];
ob_start();
include('connection.php');
include('functions.php');
//query the database with client ID
$query = "SELECT * FROM users WHERE id='$parentID'";
$result = mysqli_query( $conn, $query );
//if result is returned
if( mysqli_num_rows($result) > 0 ) {
//we have data
//set some variables
while( $row = mysqli_fetch_assoc($result) ) {
$parentName = $row['p_name'];
$parentEmail = $row['email'];
$studentName = $row['s_name'];
$parentPhone = $row['phone'];
$notes = $row['notes'];
$parentDeposit = $row['deposit'];
$packageNotColl = $row['Package-NotCollected'];
$depositNotColl = $row['deposit-not-collected'];
}
} else {
$alertMessage = "<div class='alert alert-warning'>Nothing to see here.<a href='list.php'>Head back</a></div>";
}
// id update button was submitted
if( isset( $_POST['update'] ) ) {
//set variables
$parentName = validateFormData( $_POST['parentName'] );
$parentEmail = validateFormData( $_POST['parentEmail'] );
$studentName = validateFormData( $_POST['studentName'] );
$parentPhone = validateFormData( $_POST['parentPhone'] );
$notes = validateFormData( $_POST['notes'] );
$parentDeposit = validateFormData( $_POST['parentDeposit'] );
//create new database query result
$query = "UPDATE users
SET p_name = '$parentName',
email = '$parentEmail',
s_name = '$studentName',
phone = '$parentPhone',
notes = '$notes',
deposit = '$parentDeposit'
WHERE id ='$parentID'";
$result = mysqli_query( $conn, $query );
if( $result ) {
//redirect to client page with query string
header("Location: updated.php?alert=updatesuccess");
return $result;
} else {
echo "Error updating record: " . mysqli_error($conn);
}
}
if( isset( $_POST['delete'] ) ) {
$alertMessage = "<div class='alert alert-danger'>
<p>Are you sure you want to delete this profile? This action cannot be undone!</p><br>
<form action='". htmlspecialchars( $_SERVER['PHP_SELF'] ) ."?id=$parentID' method='post'>
<input type='submit' class='btn btn-danger btn-sm' name='confirm-delete' value='Yes, delete!'>
<a type='button' class='btn btn-default btn-sm' data-dismiss='alert'>Maybe not this time.</a>
</form>
</div>";
}
if( isset( $_POST['confirm-delete'] ) ) {
$query = "DELETE FROM users WHERE id='$parentID'";
$result = mysqli_query( $conn, $query );
if($result) {
header("Location: list.php?alert=deleted");
} else {
echo "Error deleting client: " . mysqli_error($conn);
}
}
mysqli_close($conn);
include('header.php');
?>
<h1>Edit Profile</h1>
<?php echo $alertMessage; ?>
<form action="<?php echo htmlspecialchars( $_SERVER['PHP_SELF'] ); ?>?id=<?php echo $parentID; ?>" method="post" class="row">
<div class="form-group col-sm-6">
<label for="parent-name">Parent Name</label>
<input type="text" class="form-control input-lg" id="client-name" name="parentName" value="<?php echo $parentName; ?>">
</div>
<div class="form-group col-sm-6">
<label for="parent-email">Email</label>
<input type="text" class="form-control input-lg" id="client-email" name="parentEmail" value="<?php echo $parentEmail; ?>">
</div>
<div class="form-group col-sm-6">
<label for="student-name">Student Name</label>
<input type="text" class="form-control input-lg" id="student-name" name="studentName" value="<?php echo $studentName; ?>">
</div>
<div class="form-group col-sm-6">
<label for="parent-phone">Phone #</label>
<input type="text" class="form-control input-lg" id="parent-phone" name="parentPhone" value="<?php echo $parentPhone; ?>">
</div><div class="form-group col-sm-6">
<label for="student-name">Notes</label>
<input type="textarea" class="form-control input-lg" id="notes" name="notes" value="<?php echo $notes; ?>">
</div>
<div class="form-group col-sm-6">
<label for="parent-deposit">Deposit</label>
<input type="text" class="form-control input-lg" id="parent-deposit" name="parentDeposit" value="<?php echo $parentDeposit; ?>">
</div>
<hr>
<div class="col-sm-12">
<hr>
<button type="submit" class="btn btn-lg btn-danger pull-left" name="delete">Delete</button>
<div class="pull-right">
Cancel
<button type="submit" class="btn btn-lg btn-success" name="update">Update</button>
<!-- Print -->
</div>
</div>
</form>
<hr>
<div>
<?php if($packageNotColl > 0) { ?>
<div class='col-sm-3 alert alert-danger'>Package not collected 2018: $<?php echo $packageNotColl; ?></div>
<?php } ?>
</div>
<?php
include('footer.php');
?>
updated.php
<?php
//get ID sent by GET collection
$parentID = $_GET['id'];
ob_start();
include('connection.php');
include('functions.php');
//query the database with client ID
$query = "SELECT * FROM users WHERE id='$parentID'";
$result = mysqli_query( $conn, $query );
mysqli_close($conn);
include('header.php');
?>
<table class="table table-striped table-bordered">
<tr>
<th>ID</th>
<th>Parent Name</th>
<th>Email</th>
<th>Student Name</th>
<th>Phone #</th>
<th>Notes</th>
<th>Deposit</th>
<th>Edit</th>
</tr>
<?php
if(isset($_GET['id'])) {
if(mysqli_num_rows($result) > 0) {
//we have data
//output the data
while( $row = mysqli_fetch_assoc($result) ) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td><td>" . $row['p_name'] . "</td><td>" . $row['email'] . "</td><td>" . $row['s_name'] . "</td><td>" . $row['phone'] . "</td><td>" . $row['notes'] . "</td><td>" . $row['deposit'] . "</td>";
echo '<td><span class="glyphicon glyphicon-edit"></span></td>';
echo '</tr>';
}
} else { //if no entries
echo "<div class='alert alert-warning'>You have no clients!</div>";
}
}
?>
<?php
include('footer.php');
?>
The updated.php page shows the table, but does not include any sql query results.
header('Location: ...) returns the uri/url you provide to the browser, which then calls this page. any information your script had, when you called that redirection, is gone, since it's a different request.
Hence, you should add the id to the url you provide. Like
header('Location: /updated.php?id='.$parentID.'&alert=deleted');
However You really should prevent the sql injection that's just waiting to happen. PLEASE read up on how to prevent it, because your script is vulnerable to it. Your script is also vulnerable to XSS. Sanitize ALL externally provided data ($parentID = $_GET['id']; should at the very least be $parentId = intval($_GET['id']) to fight XSS).

PHP Insert data in database from array and output db data in html table

I'm having a problem with inserting data in my MySQL db table from an array. I have a form and an array which stores submitted values and its contents I display in a html table. In each table row there are values from one submit and a button which deletes the row with jQuery.
The problem is I also need the functionality to select a row from the html table and insert in my database table. I would like a button on each row's end that when clicked would insert the rows contents in my database table, similar to what i have now with deleting a row from my html table.
Deleting can be done with simple jQuery, but with this I have no idea how to continue, thanks for answers in advance.
This is how far i have gotten:
<div class="row">
<div class="col-7"> <!-- array table col -->
<div class="arraytable" style="margin-left: 15px; margin-top:15px;">
<table id="arraytable" class="table table-hover">
<tbody>
<thead>
<tr>
<th></th>
<th>Code:</th>
<th>Title:</th>
<th>Inventory nr.:</th>
<th>Inventory value.:</th>
<th>Retail value.:</th>
<th></th>
<th></th>
</tr>
</thead>
<?php
session_start();
$code = $title = $number = $value = $retailValue = "";
$code_err = $number_err = $value_err = $title_err = $retailValue_err = "";
if( isset($_POST["add"]) ){
if( empty(trim($_POST["code"])) ){
$code_err = "Enter code.";
}
else{
$code = trim($_POST["code"]);
}
if ( empty(trim($_POST["title"])) ) {
$title_err = "Enter title.";
}
else {
$title = trim($_POST["title"]);
}
if ( empty(trim($_POST["number"])) || !is_numeric($_POST["number"]) ) {
$number_err = "Inventory nr. must be entered, must be numeric";
}
else{
$number = trim($_POST["number"]);
}
if ( empty(trim($_POST["value"])) || !is_numeric($_POST["value"]) ) {
$value_err = "Inventory value must be entered, must be numeric";
}
else {
$value = trim($_POST["value"]);
}
if ( empty(trim($_POST["retailvalue"])) || !is_numeric($_POST["retailvalue"]) || $_POST["retailvalue"] < $_POST["value"] ) {
$retailValue_err = " Retail value must be entered, must be numeric. Must be smaller than inventory value.";
}
else {
$retailValue = trim($_POST["retailvalue"]);
}
if(empty($code_err) && empty($number_err) && empty($value_err) && empty($title_err) && empty($retailValue_err)) {
$_SESSION['info'][] = array($code, $title, $number, $value, $retailValue);
if(isset($_SESSION['info'])) {
for($i = 0; $i < count($_SESSION['info']); $i++) {
echo "<tr> <td></td>";
foreach($_SESSION['info'][$i] as $key){
echo " <td>$key</td>";
}
echo "<td><a class=\"remove\" href=\"\"> <i class=\"fa fa-trash\" aria-hidden=\"true\"></i> </a></td> ";
echo "</tr>";
}
}
}
}
?>
</tbody>
</table>
</div>
</div> <!-- end arraytable col -->
<div class="col-3" style="margin-left:15px; margin-top:15px;"> <!-- form colum -->
<form name="form" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method = "POST">
<div class="form-group <?php echo (!empty($code_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Code:" id="code" name="code" class="form-control" value="<?php echo $code; ?>"/>
<span class="help-block"><?php echo $code_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($title_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Title:" id="title" name="title" class="form-control" value="<?php echo $title; ?>" />
<span class="help-block"><?php echo $title_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($number_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Inventory nr:" id="number" name="number" class="form-control" value="<?php echo $number; ?>" />
<span class="help-block"><?php echo $number_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($value_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Inventory value:" id="value" name="value" class="form-control" value="<?php echo $value; ?>" />
<span class="help-block"><?php echo $value_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($retailValue_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Retail value:" id="retailvalue" name="retailvalue" class="form-control" value="<?php echo $retailValue; ?>" />
<span class="help-block"><?php echo $retailValue_err; ?></span>
</div>
<div class="form-group text-center">
<input type="submit" class="btn btn-primary" name="add" id="add" value="Add" >
</div>
</form>
</div> <!-- end form colum -->
</div> <!-- end array table, form row -->
<script>
$('#arraytable').on('click','tr a.remove',function(e){
e.preventDefault();
$(this).closest('tr').remove();
});
</script>
You might want something like this
if(empty($code_err) && empty($number_err) && empty($value_err) && empty($title_err) && empty($retailValue_err)) {
// insert all inputs to an a new array
$newInfo = array($_POST['code'], $_POST['title'], $_POST['number'], $_POST['value'], $_POST['retailvalue']);
// push the new array to session variable 'info'
array_push($_SESSION['info'], $newInfo);
// as you already have, loop thru each session info
for($i = 0; $i < count($_SESSION['info']); $i++) {
echo "<tr><td></td>";
// echo each value to table cells
foreach($_SESSION['info'][$i] as $value){
echo "<td>".$value."</td>";
}
echo "<td><a class=\"remove\" href=\"\"> <i class=\"fa fa-trash\"></i>Delete</a></td> ";
echo "</tr>";
}
}
Plus the condition for checking error on retail value is wrong if you want it to be smaller than inventory value. Please double check
I decided to use Ajax to post the data to Database.
You could see that I used javascript method called postToDatabase to post the data and the data has been passed as arguments to the method.
Check out the code below.
<?php
// your database connection and database selection using PDO ( Safe and better to use PDO)
//BEGINNING OF DATABASE CONNECTION
$servername = "localhost";
$username = "root";
$password = "password";
$db_name = "db";
$db_engine = 'mysql';
try {
$conn = new PDO("$db_engine:host=$servername;dbname=$db_name", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{ echo "Connection failed: " . $e->getMessage(); }
// END OF DATABSE CONNECTION
//DATA POSTED VIA AJAX
$code = trim($_POST["code"]);
$title = trim($_POST["title"]);
$number = trim($_POST["number"]);
$value = trim($_POST["value"]);
$retailValue = trim($_POST["retailvalue"]);
// BEGINNING OF INSERT QUERY
$sql = $conn ->prepare("INSERT INTO books (code, title, number, value, retailvalue) VALUES (?, ?, ?, ?, ?)"); // ? WILL BE REPLACED BY THEIR RESPECTIVE VALUES IN THE EXEC() METHOD.
$sql->execute(array($code, $title, $number, $value, $retailValue));
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet" type="text/css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div id="success_msg" class="alert alert-success fade in" style="display:none;">
×
<strong>Success!</strong> Data Saved.
</div>
<div class="col-7"> <!-- array table col -->
<div class="arraytable" style="margin-left: 15px; margin-top:15px;">
<form name="form">
<table id="arraytable" class="table table-hover">
<tbody>
<thead>
<tr>
<th></th>
<th>Code:</th>
<th>Title:</th>
<th>Inventory nr.:</th>
<th>Inventory value.:</th>
<th>Retail value.:</th>
<th></th>
<th></th>
</tr>
</thead>
<?php
session_start();
$code = $title = $number = $value = $retailValue = "";
$code_err = $number_err = $value_err = $title_err = $retailValue_err = "";
if( isset($_POST["add"]) ){
if( empty(trim($_POST["code"])) ){
$code_err = "Enter code.";
}
else{
$code = trim($_POST["code"]);
}
if ( empty(trim($_POST["title"])) ) {
$title_err = "Enter title.";
}
else {
$title = trim($_POST["title"]);
}
if ( empty(trim($_POST["number"])) || !is_numeric($_POST["number"]) ) {
$number_err = "Inventory nr. must be entered, must be numeric";
}
else{
$number = trim($_POST["number"]);
}
if ( empty(trim($_POST["value"])) || !is_numeric($_POST["value"]) ) {
$value_err = "Inventory value must be entered, must be numeric";
}
else {
$value = trim($_POST["value"]);
}
if ( empty(trim($_POST["retailvalue"])) || !is_numeric($_POST["retailvalue"]) || $_POST["retailvalue"] < $_POST["value"] ) {
$retailValue_err = " Retail value must be entered, must be numeric. Must be smaller than inventory value.";
}
else {
$retailValue = trim($_POST["retailvalue"]);
}
if(empty($code_err) && empty($number_err) && empty($value_err) && empty($title_err) && empty($retailValue_err)) {
$_SESSION['info'][] = array($code, $title, $number, $value, $retailValue);
if(isset($_SESSION['info'])) {
for($i = 0; $i < count($_SESSION['info']); $i++) {
echo "<tr> <td></td>";
foreach($_SESSION['info'][$i] as $key){
echo " <td>$key</td>";
$vals .= "'$key',";
}
echo "<td><a class=\"remove\" href=\"\"> <i class=\"fa fa-trash\" aria-hidden=\"true\"></i> </a></td> "; ?>
<td>
<a onclick="postToDatabase(<?php echo substr($vals,0,-1); $vals=NULL; ?>);" class="add" href="#"> <i class="fa fa-plus" aria-hidden="true"></i>
</a>
</td>
<?php echo "</tr>";
}
}
}
}
?>
</tbody>
</table>
</form>
</div>
</div> <!-- end arraytable col -->
<div class="col-3" style="margin-left:15px; margin-top:15px;"> <!-- form colum -->
<form name="form" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method = "POST">
<div class="form-group <?php echo (!empty($code_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Code:" id="code" name="code" class="form-control" value="<?php echo $code; ?>"/>
<span class="help-block"><?php echo $code_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($title_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Title:" id="title" name="title" class="form-control" value="<?php echo $title; ?>" />
<span class="help-block"><?php echo $title_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($number_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Inventory nr:" id="number" name="number" class="form-control" value="<?php echo $number; ?>" />
<span class="help-block"><?php echo $number_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($value_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Inventory value:" id="value" name="value" class="form-control" value="<?php echo $value; ?>" />
<span class="help-block"><?php echo $value_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($retailValue_err)) ? 'has-error' : ''; ?>">
<input type="text" placeholder="Retail value:" id="retailvalue" name="retailvalue" class="form-control" value="<?php echo $retailValue; ?>" />
<span class="help-block"><?php echo $retailValue_err; ?></span>
</div>
<div class="form-group text-center">
<input type="submit" class="btn btn-primary" name="add" id="add" value="Add" >
</div>
</form>
</div> <!-- end form colum -->
</div> <!-- end array table, form row -->
</div>
<script>
$('#arraytable').on('click','tr a.remove',function(e){
e.preventDefault();
$(this).closest('tr').remove();
});
function postToDatabase(code, title,number,value,retailvalue){
$.ajax({
type: "POST",
url: 'index.php',
data: "code=" + code + "&title=" + title + "&number=" + number + "&value=" + value + "&retailvalue=" + retailvalue,
success: function (msg) {
$('#success_msg').show();
}
});
}
</script>
</body>
</html>

DELETE query ears the last upload? [UPDATE]

I can not understand why the application delete the las upload.I am new in php and I hope to help me. Thank you.
Code: HTML
<div class="row">
<div class="col-md-6 col-centered">
<div class="newboxes" id="newboxes3">
<form class="form" method="POST">
<input type="text" id="nmPic" name="nmPic" placeholder="име на снимката" onfocus="this.placeholder = ''" onblur="this.placeholder = 'име на снимката'"></br>
<input type="text" id="price" class="priceFrom" name="priceFrom" placeholder="цена от" onfocus="this.placeholder = ''" onblur="this.placeholder = 'цена от'"></br>
<input type="text" id="price" class="priceTo" name="priceTo" placeholder="цена до" onfocus="this.placeholder = ''" onblur="this.placeholder = 'цена до'"></br>
<select name="picCat" id="picCat">
<option value="" selected disabled>Изберете категория</option>
<option value="Детски">Детски</option>
<option value="Сватби">Сватби</option>
<option value="Рожден ден">Рожден ден</option>
<option value="18+">18+</option>
<option value="Други">Други</option>
</select></br>
<input type="text" id="numPic" name="numPic" placeholder="номер на снимката" onfocus="this.placeholder = ''" onblur="this.placeholder = 'номер на снимката'"></br>
<input type="submit" name="showFilter" value="покажи" />
</form>
</div>
</div>
</div>
Code: php
<div class="row">
<div class="col-md-12 col-centered pic">
<form class='form' method='POST'>
<?php
if (isset($_POST["showFilter"]))
{
$picName = $_POST['nmPic'];
$priceFrom = $_POST['priceFrom'];
$priceTo = $_POST['priceTo'];
$picCat = isset($_POST['picCat']) ? $_POST['picCat'] : '';
$numPic = $_POST['numPic'];
$filter = " SELECT * FROM images WHERE status = '1'";
if ($numPic && !empty($numPic)) {
$filter .= " AND id='$numPic'";
}
if ($picName && !empty($picName)) {
$filter .= " AND img_content='$picName'";
}
if ($picCat && !empty($picCat)) {
$filter .= " AND category='$picCat'";
}
if ($priceTo && !empty($priceTo)) {
$filter .= " AND price < '$priceTo'+1";
}
if ($priceFrom && !empty($priceFrom)) {
$filter .= " AND price > '$priceFrom'";
}
$resFilter = $connect->query($filter);
if ($resFilter->num_rows > 0) {
while($row = mysqli_fetch_array($resFilter))
{
echo "<div class='col-md-3 picture'>
<img class='child-img' src='".$row["picture"]." '/></br>
<div class='number'>
<span class='id'>№ ".$row['id']."</br>
име: ".$row['img_content']."</br> категория: ".$row['category']."</br>
цена: ".$row['price']."лв.</br>
дата: ".$row['time']."ч.</br>
</span>
<input type='hidden' name='del' value=" .$row['id'].">
<input class='btn btn-danger' name='delete' type='submit' value='истрии'/>
</div>
</div>";
}
}
}
?>
</form>
</div>
</div>
<form method="POST">
<?php
if (isset($_POST['delete']))
{
$sql = "SELECT * FROM images WHERE status = '1'";
$res = $connect->query($sql);
while($row = mysqli_fetch_array($res))
{
$id = $_POST['del'];
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'paspartu';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'DELETE FROM images
WHERE id='.$id;
mysql_select_db('login');
mysql_query($sql);
mysql_close($conn);
}
}
?>
</form>
If pressed the delete button <input class="btn btn-danger" name="delete" type="submit" value="истрии"> , this delete the last upload image???
And can you tell me how to delete the image from upload folder "uploads/"? Thank you verry much.
It's because you don't have an input in your form that's named "showFilter". You need to either rewrite or remove:
if (isset($_POST["showFilter"]))
Try modified query delete
$sql = "DELETE FROM `your_database`.`images` WHERE `your_database`.`id` = $del_id";
As I can see your submit button is in separate form tag. That is why the button is responsible only for the first parent form and if it is pressed the page is only reloaded. It should be placed in the general form you use, so that it will be related with the general form action.
You need to take your submit button inside the form. You have used two different forms. It is the problem.
Try to write your code as below:-
<?php
// Take div and form tag outside the loop
echo "<div class='col-md-3 picture'>
<form class='form' method='POST'>";
// Loop start
while($row = mysqli_fetch_array($resFilter))
{
echo "<img class='child-img' src='".$row["picture"]." '/></br>
<div class='number'>
<span class='id'>№ ".$row['id']."
<input class='check' name='checkbox[]' type='checkbox' value='". $row['id']."'></br>
име: ".$row['img_content']."</br> категория: ".$row['category']."</br>
цена: ".$row['price']."лв.</br>
дата: ".$row['time']."ч.
</br></span>
<br></div>";
}
// Loop End
?>
<!-- submit button -->
<input class="btn btn-danger" name="delete" type="submit" value="истрии маркираните">
<?php
// end div and form tag outside the loop
echo "</form>
</div>";
if (isset($_POST['delete']) && isset($_POST['checkbox'])) {
foreach($_POST['checkbox'] as $del_id){
$del_id = (int)$del_id;
$sql = "DELETE FROM images WHERE id = $del_id";
mysql_query($sql);
}
header('Location: admin.php');
}
Hope it will help you :)

html radio button not POSTing

I am using a form with radio buttons to post a value to PHP. However, the value is not being sent. This is my code:
HTML:
<form action="voteupdate.php" id="form-id" method="post"onclick="document.getElementById(\'form-id\').submit();">
<input type="hidden" name="type" id="type" value="' . $type . '">
<input type="hidden" name="id" id="id" value="' . $id . '">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default '.$vup.'">
<input type="radio" name="vote" id="1" value="1">
<span class="glyphicon glyphicon-chevron-up"></span> Vote up
</label>
<label class="btn btn-default '.$vd.'">
<input type="radio" name="vote" id="2" value="2">
<span class="glyphicon glyphicon-chevron-down"></span> Vote down
</label>
</div>
</form>
PHP:
<?php session_start();
include('config.php');
$type = $_POST['type'];
$id = $_POST['id'];
echo $_POST['vote'];
if ($type == "images"){
$tid = "imgid";
}
if ($type == "pages"){
$tid = "pageid";
}
if ($type == "posts"){
$tid = "postid";
}
$table = str_replace(""," ",$type);
$table = str_replace('"'," ",$table);
$table = str_replace("'"," ",$table);
$stmt= $pdo->prepare("SELECT * FROM '".$table."' WHERE ".$tid." = :imgid");
$stmt->execute(array(':imgid' => $id));
$stmt = $stmt->fetch();
$vreg = explode(",", $stmt['votereg']);
foreach ($vreg as $v) {
$temp = explode("-", $v);
if ($_SESSION['uid'] == $temp['0']){
if (1 == $temp['1']){
header( 'Location: votesys.php' ) ;
}
else
{
$instruction = "update-exists";
}
}
}
echo $instruction;
?>
<form action="voteupdate.php" id="form-id" method="post"onclick="document.getElementById(\'form-id\').submit();">
is missing a space between method and onclick attributes:
<form action="voteupdate.php" id="form-id" method="post" onclick="document.getElementById(\'form-id\').submit();">

Trying to integrate CKEditor in a php page

I'm trying to integrate CKEditor into my simple CMS. I got it to show up on the page, but it's just above everything. I'm wondering how to get it into the correct spot, below my title textbox? Here is my code:
require_once 'conn.php';
include_once 'ckeditor/ckeditor.php';
$CKEditor = new CKEditor();
$CKEditor->editor('body');
$title= '';
$body= '';
$article= '';
$author_id= '';
if (isset($_GET['a'])
and $_GET['a'] == 'edit'
and isset($_GET['article'])
and $_GET['article']) {
$sql = "SELECT title, body, author_id FROM cms_articles " .
"WHERE article_id=" . $_GET['article'];
$result = mysql_query($sql, $conn) or
die ('Could not retrieve article data: ' . mysql_error());
$row = mysql_fetch_array($result);
$title = $row['title'];
$body = $row['body'];
$article = $_GET['article'];
$author_id = $row['author_id'];
}
require_once 'header.php';
?>
<form method="post" action="transact-article.php">
<h2>Compose Article</h2>
<p>
Title: <br />
<input type="text" class="title" name="title" maxlength="255" value="<?php echo htmlspecialchars($title); ?>" />
</p>
<p>
Body: <br />
<textarea class="body" name="body" id="body" rows="10" cols="60"><?php echo htmlspecialchars($body); ?></textarea>
</p>
<p>
<?php
echo '<input type="hidden" name="article" value="' .
$article . "\" />\n";
if ($_SESSION['access_lvl'] < 2) {
echo '<input type="hidden" name="author_id" value="' .
$author_id . "\" />\n";
}
if ($article) {
echo '<input type="submit" class="submit" name="action" ' .
"value=\"Save Changes\" />";
} else {
echo '<input type="submit" class="submit" name="action" ' .
"value=\"Submit New Article\" />";
}
?>
</p>
</form>
Personally I don't think you need the PHP library. Just add
<div contenteditable="true">
Editable text
</div>
as your editable and then just the script to get it running:
<script type="text/javascript" src="/path/to/ckeditor/ckeditor.js"></script>
That said, you may be able to pass the id of your textarea to the PHP library. To avoid confusion with the body tag, rename the id and name of this control to editable_content or similar. And as I mention above, try using a div instead.

Categories