Update code wont work in php and mysql - php

Hi Guys could please check my code I have written, the problem is it won't update the data in DB, it just reloading and not giving any error.
Here is my update.php
if (isset($_POST['update']) && isset($_POST['update']) != "") {
$name = $_POST['c_name'];
$mobile = $_POST['c_mob'];
$dDate = $_POST['d_date'];
$frame = $_POST['frame'];
$size = $_POST['size'];
$lense = $_POST['lense'];
$descr = $_POST['descr'];
$paid = $_POST['paid'];
$remains = $_POST['remains'];
$refer = $_POST['c_refer'];
}
$setquery = "UPDATE `dep_sale` SET c_name='$name', c_mob='$mobile', d_date='$dDate', frame='$frame', size='$size', lense='$lense', descr='$descr',c_refer='$refer', paid='$paid', remains='$remains' WHERE id='".$_POST["id"]."'";
mysqli_query($link, $setquery);
header("location: reports.php");
And here is the HTML
<form method="POST" action="update.php">
<div class="row">
<div class="col-lg-4 col-md-4">
<input type="hidden" name="id" />
<input type="text" class="form-control" value="<?php echo $row['c_name']; ?>" required id="c_name" name="c_name" placeholder="Name..."/>
</div>
<div class="col-lg-4 col-md-4">
<input type="phone" class="form-control" value="<?php echo $row['c_mob']; ?>" required id="c_mob" name="c_mob" placeholder="Mobile..."/>
</div>
<div class="col-lg-4 col-md-4">
<input type="text" class="form-control" value="<?php echo $row['d_date']; ?>" required id="d_date" name="d_date" onfocus="(this.type='date')" placeholder="Delivery Date..."/>
</div>
</div>
<br>
<div class="row">
<div class="col-lg-4 col-md-4">
<input type="text" class="form-control" value="<?php echo $row['frame']; ?>" required id="frame" name="frame" placeholder="Frame..."/>
</div>
<div class="col-lg-4 col-md-4">
<input type="text" class="form-control" value="<?php echo $row['size']; ?>" required id="size" name="size" placeholder="Size..."/>
</div>
<div class="col-lg-4 col-md-4">
<input type="text" class="form-control" value="<?php echo $row['lense']; ?>" required id="lense" name="lense" placeholder="Lense..."/>
</div>
</div>
<br>
</form>
There is no problem in connection because i am fetching and inserting data perfectly.Please help me guys.Thanks

To see the errors set the following at first lines:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Your if is wrong. Try this:
if (isset($_POST['update']) && $_POST['update'] != "") {
Or more shorter version
if (!empty($_POST['update'])) {
Hope this helped you!

Related

Insert data from forms inside a while loop php

Good day. I just wanna ask how can I insert the data from the forms generated from a while loop. This is what I tried so far. I added a loop where they will have different id or names but when I tried on clicking the button the first form is the only one working. Thank you so much in advance.
<?php
include "../config/dbconfig.php";
$data['productCode'] = "1"; // sample data
$stmt = $conn->prepare("SELECT * FROM tbl_category");
//$stmt->bind_param("i", $data['productCode']);
$stmt->execute();
$result = $stmt->get_result();
$i = 1;
while ($stuff = $result->fetch_assoc()) {
?>
<div class="col-sm-6" style="margin-top:20px;">
<div class="card">
<div class="card-header"><?php echo $stuff['categoryname']; ?>
</div>
<div class="card-body outermydiv">
<div class="myDIV">
<form method="POST" name="itemform" action="">
<div class="form-row">
<div class="col-5">
<input type="text" class="form-control" name="name[<?php echo $i; ?>]" id="itemname[<?php echo $i; ?>]" placeholder="Item name" required autocomplete="off">
</div>
<div class="col">
<input type="number" class="form-control" name="cost[<?php echo $i; ?>]" id="itemcost[<?php echo $i; ?>]" placeholder="Cost" required>
</div>
<div class="col">
<input type="number" class="form-control" name="price[<?php echo $i; ?>]" id="itemprice[<?php echo $i; ?>]" placeholder="Price" required>
<input type="hidden" class="form-control" name="code[<?php echo $i; ?>]" id="forcatcode[<?php echo $i; ?>]" value="<?php echo $stuff['categorycode'] ?>">
</div>
<div class="col">
<button type="submit" class="btn btn-success" name="btnsaveitem" id="btnsaveitem">Save</button>
</div>
<?php $i++; ?>
<input type="hidden" name="count" value="<?php echo $i; ?>" />
</div>
</form>
</div>
<br>
</div>
</div>
</div>
<?php
}
?>
and here is my insert code
<?php
if (isset($_POST['btnsaveitem'])) {
$count = $_POST['count'];
for ($i = 1; $i < $count; $i++) {
//$code = $_POST['code'][$i]; // check empty and check if interger
$foritemname = $_POST['name'][$i]; // check empty and strip tags
//$qty = $_POST['qty'][$i]; // check empty and check if interger
$stmt = $conn->prepare("INSERT INTO tbl_items(`itemname`) VALUES ('".$foritemname."')");
//$stmt->bind_param("iss",$name);
$stmt->execute();
}
}
?>
Starting by rewriting your form...
You don't need $i for anything, but I'll leave the declaration in case you want it for something else.
Don't submit array type data, each form will submit its own set of fields.
It probably makes more sense to add $stuff['categorycode'] as the value of each submit to avoid needing the hidden field. I'll leave it your way for now.
Form:
foreach ($stmt->get_result() as $i => $stuff) { ?>
<div class="col-sm-6" style="margin-top:20px;">
<div class="card">
<div class="card-header"><?php echo $stuff['categoryname']; ?></div>
<div class="card-body outermydiv">
<div class="myDIV">
<form method="POST">
<div class="form-row">
<div class="col-5">
<input type="text" class="form-control" name="name" placeholder="Item name" required autocomplete="off">
</div>
<div class="col">
<input type="number" class="form-control" name="cost" placeholder="Cost" required>
</div>
<div class="col">
<input type="number" class="form-control" name="price" placeholder="Price" required>
</div>
<div class="col">
<button type="submit" class="btn btn-success" name="btnsaveitem">Save</button>
</div>
</div>
<input type="hidden" class="form-control" name="code" value="<?php echo $stuff['categorycode']; ?>">
</form>
</div>
<br>
</div>
</div>
</div>
<?php
}
Receiving script: (extend with additional fields as desired)
if (isset($_POST['btnsaveitem'])) {
$stmt = $conn->prepare("INSERT INTO tbl_items(`itemname`) VALUES (?)");
$stmt->bind_param("s",$_POST['name']);
$stmt->execute();
}
This is all untested code.

Php Prepared Statement Fails to insert data into database through form

I'm trying to insert data into a database, the script executes all the way down and redirect the user to the page but no record gets inserted. I've been trying to figure out why for hours. I keep creating new scripts but i'm missing something apparently.
init.php
<?php
/*for error 1045 config.inc.php*/
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "");
define("DB_DATABASE", "databasename");
$db = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()){
echo "database failed to connect with following errors:". mysqli_connect_error();
die();
}
require_once $_SERVER['DOCUMENT_ROOT'].'/ecommerce/config.php';
require_once BASEURL.'helpers/helpers.php';
form.php
<?php
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once $_SERVER['DOCUMENT_ROOT'].'/HeleneQuirion/core/init.php';
include 'includes/header.php';
if(isset($_GET['add'])){
$parentQuery = $db->query("SELECT * FROM categories WHERE parent= 0" );
if (isset($_POST['submit'])) {
// prepare and bind
$stmt = $db->prepare("INSERT INTO product (prod_name, categories, list_price, price,prod_width,prod_depth,prod_height,prod_material,quantity,image_1,image_2,image_3,image_4,description,care_instructions) VALUES (?,?, ?,?,?,?,?,?,?,?,?,?,?,?,?)");
$stmt->bind_param("ssiiiiisissssss" ,$prod_name, $child,$list_price,$price,$prod_width,$prod_depth,$prod_height,$prod_material,$quantity,$image_1,$image_2,$image_3,$image_4,$description,$care_instructions);
// set parameters and execute
if(isset($_POST['prod_name']))
{
$prod_name = sanitize($_POST)['prod_name'];
}
if(isset($_POST['child']))
{
$categories = sanitize($_POST)['child'];
}
if(isset($_POST['list_price']))
{
$prod_name = sanitize($_POST)['list_price'];
}
if(isset($_POST['price']))
{
$price = sanitize($_POST)['price'];
}
if(isset($_POST['prod_width']))
{
$prod_width = sanitize($_POST)['prod_width'];
}
if(isset($_POST['prod_depth']))
{
$prod_depth = sanitize($_POST)['prod_depth'];
}
if(isset($_POST['prod_height']))
{
$prod_height = sanitize($_POST)['prod_height'];
}
if(isset($_POST['prod_material']))
{
$prod_material = sanitize($_POST)['prod_material'];
}
if(isset($_POST['quantity']))
{
$quantity = sanitize($_POST)['quantity'];
}
if(isset($_POST['care_instructions']))
{
$care_instructions = sanitize($_POST)['care_instructions'];
}
if(isset($_POST['image_1']))
{
$image_1 = $_FILES['image_1'];
}
if(isset($_POST['image_2']))
{
$image_2 = $_FILES['image_2'];
}
if(isset($_POST['image_3']))
{
$image_3 = $_FILES['image_3'];
}
if(isset($_POST['image_4']))
{
$image_4 = $_FILES['image_4'];
}
if(isset($_POST['description']))
{
$description = sanitize($_POST)['description'];
}
$stmt->execute() or die(mysqli_error($db));
header('Location: products.php');
$stmt->close();
$conn->close();
}
?>
<form action="products.php?add=1" method="POST" enctype="multipart/form-data">
<div class='container_12'>
<div class="form-group col-md-3">
<label for="prod_name">Product Name*:</label>
<input type="text" name="prod_name" id="prod_name" class="form-control" value="<?=((isset($_POST['prod_name']))?sanitize($_POST['prod_name']):' ');?>">
</div>
<div class="form-group col-md-3">
<label for="parent">Parent Category*:</label>
<select class="form-control" id="parent" name="parent">
<option value=""<?=((isset($_POST['parent']) && $_POST['parent'] == '')?'selected':'');?>></option>
<?php while($parent = mysqli_fetch_assoc($parentQuery)): ?>
<option value=" <?=$parent['id'];?>"<?=((isset($_POST['parent']) && $_POST['parent'] == $parent['id'])?' select':'');?>><?=$parent['category_name'];?></option>
<?php endwhile; ?>
</select>
</div>
<div class='form-group col-md-3'>
<label for='child'>Second Category*:</label>
<select id='child' name='child' class='form-control'></select>
</div>
</div>
<div class='container_12'>
<div class='form-group col-md-3'>
<label for='list_price'>List Price(OPTIONAL): </label>
<input type="text" id="list_price" name="list_price" class="form-control" value="<?=((isset($_POST['list_price']))?sanitize($_POST['list_price']):'');?>">
</div>
<div class="form-group col-md-3">
<label for="price">Price*:</label>
<input type="text" id="price" name="price" class="form-control" value="<?=((isset($_POST['price']))?sanitize($_POST['price']):'');?>">
</div>
<div class='form-group col-md-3'>
<label for='prod_width'>Width* (in inches):</label>
<input type="text" id="prod_width" name="prod_width" class="form-control" value="<?=((isset($_POST['prod_width']))?sanitize($_POST['prod_width']):'');?>">
</div>
<div class='form-group col-md-3'>
<label for='prod_depth'>Height*(in inches):</label>
<input type="text" id="'prod_depth" name="'prod_depth" class="form-control" value="<?=((isset($_POST['prod_depth']))?sanitize($_POST['prod_depth']):'');?>">
</div>
</div>
<div class='container_12'>
<div class='form-group col-md-3'>
<label for='prod_height'>Depth*(in inches):</label>
<input type="text" id="prod_height" name="prod_height" class="form-control" value="<?=((isset($_POST['prod_height']))?sanitize($_POST['prod_height']):'');?>">
</div>
<div class='form-group col-md-3'>
<label for='prod_material'>Construction Material:</label>
<input type="text" id="prod_material" name="prod_material" class="form-control" value="<?=((isset($_POST['prod_material']))?sanitize($_POST['prod_material']):'');?>">
</div>
<div class='form-group col-md-6'>
<label>Quantity * :</label>
<input type="text" id="quantity" name="quantity" class="form-control" value="<?=((isset($_POST['quantity']))?sanitize($_POST['quantity']):'');?>">
</div>
</div>
<div class='container_12'>
<div class="form-group col-md-3"> <label for="image_1">Product Photo #1:</label>
<input type="file" name="image_1" id="image_1" class="form-control">
</div>
<div class="form-group col-md-3"> <label for="image_2">Product Photo #2:</label>
<input type="file" name="image_2" id="image_2" class="form-control">
</div>
<div class="form-group col-md-3"> <label for="image_3">Product Photo #3:</label>
<input type="file" name="image_3" id="image_3" class="form-control">
</div>
<div class="form-group col-md-3"> <label for="image_4">Product Photo#4:</label>
<input type="file" name="image_4" id="image_4" class="form-control">
</div>
</div>
<div class='container_12'>
<div class="form-group col-md-6">
<label for="description">Description:</label>
<textarea id="description" name="description" class="form-control" rows="6"><?=((isset($_POST['description']))?sanitize($_POST['description']):'');?></textarea>
</div>
<div class="form-group col-md-6">
<label for="care_instructions">Care Instructions*:</label>
<textarea id="care_instructions" name="care_instructions" class="form-control" rows="6"><?=((isset($_POST['care_instructions']))?sanitize($_POST['care_instructions']):'');?></textarea>
</div></div>
<div class='container_12'>
<div class="form-group pull-right">
<input type='submit' name='submit' value='Add Product' class='form-control btn-success pull-right'>
</div></div>
</form>
This is just to clarify one of the points in the comments above...
So I knocked up some test code to check what is going on...
<?php
$_POST['prod_name'] = 'fred';
function sanitize($thing){
var_dump("Inside Sanitize- ", $thing);
return $thing;
}
// Original Code - sends an array to sanitize
if(isset( $_POST['prod_name'] )) {
$prod_name = sanitize($_POST)['prod_name'];
}
var_dump('Original Version '.$prod_name);
// New Code 1 - Sends a String to sanitize
if(isset( $_POST['prod_name'] )) {
$prod_name = sanitize($_POST['prod_name']);
}
// New Code 2 - Should use this one, or could make this a function.
$prod_name = isset($_POST['prod_name'])? sanitize($_POST['prod_name']):'';
var_dump($prod_name);

Submit button won't work in PHP

PHP Code
<?php
if (!isset($_SESSION)) { session_start(); }
include "connect.php";
include "functions.php";
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
header('location: no_acces.php');
exit();
} else {
$id_user = $_SESSION['userid'];
$q_user = mysqli_query($conn, "SELECT * FROM users WHERE id = $id_user");
if (mysqli_num_rows($q_user) === 1) {
$r_user = mysqli_fetch_assoc($q_user);
} else {
unset($_SESSION['login']);
unset($_SESSION['userid']);
header('location: no_acces.php');
exit();
}
}
$error = "";
$userQuery = mysqli_query($conn, "SELECT username FROM users");
$user = mysqli_fetch_assoc($userQuery);
$id = $_GET['id'];
if (isset($_POST['edit_contact'])) {
$roepnaam = $_POST['roepnaam'];
$naam = $_POST['naam'];
$land = $_POST['land'];
$bedrijf = $_POST['bedrijf'];
$adres1 = $_POST['adres1'];
$adres2 = $_POST['adres2'];
$stad = $_POST['stad'];
$postcode = $_POST['postcode'];
$provincie = $_POST['provincie'];
$telefoon = $_POST['telefoon'];
$email = $_POST['email'];
$captcha= $_POST['g-recaptcha-response'];
if(!$captcha){
$error = "Er is een fout opgetreden";
}
if ($error == "") {
$insertUser = ("UPDATE address SET
roepnaam = '$roepnaam', naam = '$naam', bedrijf = '$bedrijf', telefoon = '$telefoon', email = '$email', adres1 = '$adres1', adres2 = '$adres2', stad = '$stad', postcode = '$postcode', provincie = '$provincie', land = '$land' WHERE id = $id");
if (mysqli_query($conn, $insertUser)) {
$_SESSION['edit_contact'] = true;
header('location: address_book.php');
} else {
$error = "Er is een fout opgetreden";
}
}
}
?>
HTML Code
<!DOCTYPE html>
<html lang="en">
<body>
<form action="" method="post">
<?php if ($error !== "") { ?>
<div class="row">
<div class="col-md-12 error">
<?php echo $error; ?>
</div>
</div>
<?php } ?>
<label for="firstName" class="control-label">Naam:</label>
<div class="row ">
<div class="col-md-6">
<input type="text" class="form-control" id="firstName" placeholder="Roepnaam" name="roepnaam" value="<?php if (isset($_POST['roepnaam'])) { echo $_POST['roepnaam']; } ?>" required/>
</div>
<div class="col-md-6">
<input type="text" class="form-control" id="lastName" placeholder="Naam" name="naam" value="<?php if (isset($_POST['naam'])) { echo $_POST['naam']; } ?>" required/>
</div>
</div>
<label for="username" class="control-label">Bedrijf:</label>
<div class="row ">
<div class="col-md-12">
<input type="text" class="form-control" id="username" placeholder="Bedrijf" name="bedrijf" value="<?php if (isset($_POST['bedrijf'])) { echo $_POST['bedrijf']; } ?>" required/>
</div>
</div>
<label for="password" class="control-label">Telefoonnummer:</label>
<div class="row ">
<div class="col-md-12">
<input type="text" class="form-control" id="password" placeholder="Telefoonnummer" name="telefoon" value="<?php if (isset($_POST['telefoon'])) { echo $_POST['telefoon']; } ?>" required/>
</div>
</div>
<label for="email" class="control-label">Email:</label>
<div class="row ">
<div class="col-md-12">
<input type="text" class="form-control" id="email" placeholder="E-mailadres" name="email" value="<?php if (isset($_POST['email'])) { echo $_POST['email']; } ?>" required/>
</div>
</div>
<label for="adres1" class="control-label">Adres:</label>
<div class="row">
<div class="col-md-12">
<input type="text" class="form-control" id="adres1" placeholder="Adres 1" name="adres1" value="<?php if (isset($_POST['adres1'])) { echo $_POST['adres1']; } ?>" required/>
</div>
</div>
<div class="row padding-top-10">
<div class="col-md-12">
<input type="text" class="form-control" id="adres2" placeholder="Adres 2" name="adres2" value="<?php if (isset($_POST['adres2'])) { echo $_POST['adres2']; } ?>"/>
</div>
</div>
<div class="row">
<div class="col-md-3">
<label for="postcode" class="control-label">Postcode:</label>
</div>
<div class="col-md-5">
<label for="city" class="control-label">Stad:</label>
</div>
<div class="col-md-4">
<label for="regio" class="control-label">Regio:</label>
</div>
</div>
<div class="row ">
<div class="col-md-3">
<input type="text" class="form-control" id="postcode" placeholder="Postcode" name="postcode" value="<?php if (isset($_POST['postcode'])) { echo $_POST['postcode']; } ?>" required/>
</div>
<div class="col-md-5">
<input type="text" class="form-control" id="city" placeholder="Stad" name="stad" value="<?php if (isset($_POST['stad'])) { echo $_POST['stad']; } ?>" required/>
</div>
<div class="col-md-4">
<input type="text" class="form-control" id="regio" placeholder="Provincie" name="provincie" value="<?php if (isset($_POST['provincie'])) { echo $_POST['provincie']; } ?>" required/>
</div>
</div>
<label for="land" class="control-label">Land:</label>
<div class="row ">
<div class="col-md-12">
<input type="text" class="form-control" id="password" placeholder="Land" name="land" value="<?php if (isset($_POST['land'])) { echo $_POST['land']; } ?>" required/>
</div>
</div>
<div class="row">
<div class="col-md-8 padding-top-10 ">
<div class="g-recaptcha " data-sitekey="6LcCsBoTAAAAAK72uzyJSrgWwD8xuF6jFIfgFaHX"></div>
</div>
</div>
<div class="row">
<div class="col-md-2 padding-top-10">
<input type="submit" name="edit_contact" class="btn btn-succes" value="Wijzigen">
</div>
<div class="col-md-2 padding-top-10">
<input type="text" name="delete_contact" action="delete_contact.php" class="btn btn-succes" value="Contact verwijderen">
</div>
</div>
</form>
</body>
</html>
PHP Code
<?php
if (!isset($_SESSION)) { session_start(); }
include "connect.php";
include "functions.php";
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true || !isset($_SESSION['userid']) || $_SESSION['userid'] == "") {
header('location: login.php');
exit();
} else {
session_regenerate_id();
}
$id = $_GET['id'];
$query = "DELETE FROM address WHERE id= $id";
mysqli_query ($query);
if (mysql_affected_rows() == 1) {
header('location: addressbook.php');
} else {
echo "Verwijderen mislukt";
}
?>
I'm trying to make a delete button for my contacts within the addressbook. but everytime I click "Contact verwijderen" the webpage resets it self and the contact won't be deleted. Could anyone help me to fix this?
You input is a text input and you don't have a form asociated with it,create one and change the type of submit to submit
<form action="delete_contact.php" method="post">
//other inputs
<input type="submit" name="delete_contact" class="btn btn-succes" value="Contact verwijderen">
</form>
You are mixing MySQL and MySQLi functions:
mysqli_query ($query);
if (mysql_affected_rows() == 1)
You cannot mix MySQL with MySQLi, your code should be:
mysqli_query ($query);
if (mysqli_affected_rows($conn) == 1)
Add a normal link to delete the contact, you don't need a form.
<a href="delete_contact.php?id=<?php echo $id ?>">
Contact verwijderen
</a>

Form won't submit info to database

I've been building a site recently for a friend and I've gotten stuck on this one form. A button links to url in which this form is on and then once you fill out all the information and click submit, instead of returning you back to home.php it just removes the form from view and all you see is a blank new.php and it doesn't submit the information.
<?php
function renderForm($user, $rank, $position, $error)
{
?>
<?php
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<center>
<form action="" method="post">
<div class="form-group">
<label for="username">Username*</label>
<input id="username" class="form-control" type="text" name="user" placeholder="Username" value="<?php echo $user; ?>" />
</div>
<div class="form-group">
<label for="rank">Rank</label>
<select class="form-control" name="rank">
<option value="1">Pending Rank</option>
<option value="2">PVT</option>
</select>
</div>
<div class="form-group">
<label for="position">Position</label>
<input id="position" class="form-control" type="text" name="position" placeholder="MOG/GG" value="<?php echo $position; ?>" />
</div>
<div class="form-group">
<label for="Date">Date*</label>
<input id="Date" class="form-control" type="text" name="date" placeholder="<?php echo date('d M y'); ?>" value="<?php echo $date; ?>" />
</div>
<div class="form-group">
<label for="Tag">Tag*</label>
<input id="Tag" class="form-control" type="text" name="tag" placeholder="[]" value="<?php echo $tag; ?>" />
</div>
<div class="form-group">
<label for="adt">ADT</label>
<input id="adt" class="form-control" type="text" name="adt" placeholder="{TEST}" value="<?php echo $adt; ?>" />
</div>
<div class="form-group">
<label for="exp">EXP</label>
<input id="exp" class="form-control" type="text" name="exp" placeholder="420" value="<?php echo $exp; ?>" />
</div>
<div class="form-group">
<label for="reg">Regiment</label>
<input id="reg" class="form-control" type="text" name="reg" placeholder="[P]" value="<?php echo $reg; ?>" />
</div>
<div class="form-group">
<label for="Notes">Notes</label>
<input id="Notes" class="form-control" type="text" name="notes" placeholder="Notes" value="<?php echo $notes; ?>" />
</div>
<button type="submit" name="submit" class="btn btn-default" value="Submit">Submit</button>
</form>
<script>
$('.modal').on('hidden.bs.modal', function(){
$(this).find('form')[0].reset();
});
</script>
<?php
}
include('config/db.php');
if (isset($_POST['submit']))
{
$user = mysql_real_escape_string(htmlspecialchars($_POST['user']));
$rank = mysql_real_escape_string(htmlspecialchars($_POST['rank']));
$position = mysql_real_escape_string(htmlspecialchars($_POST['position']));
$date = mysql_real_escape_string(htmlspecialchars($_POST['date']));
$tag = mysql_real_escape_string(htmlspecialchars($_POST['tag']));
$adt = mysql_real_escape_string(htmlspecialchars($_POST['adt']));
$exp = mysql_real_escape_string(htmlspecialchars($_POST['exp']));
$reg = mysql_real_escape_string(htmlspecialchars($_POST['reg']));
$notes = mysql_real_escape_string(htmlspecialchars($_POST['notes']));
$datej = mysql_real_escape_string(htmlspecialchars($_POST['date']));
if ($user == '' || $rank == '' || $date == '' || $tag == '')
{
$error = '<center>ERROR: Please fill in all required fields!</center>';
#renderForm($user, $rank, $position, $error);
}
else
{
mysql_query("INSERT per SET user='$user', rank='$rank', position='$position', date='$date', tag='$tag', adt='$adt', exp='$exp', reg='$reg', notes='$notes', datej='$datej'", $db1)
or die(mysql_error());
include('logsadd.php');
write_mysql_log('has added member <font color="black"><b>'. $user .'</b></font>.', $db);
header("Location: home.php");
}
}
else
header("home.php");
{
#renderForm('','','');
}?>
Your else looks like this
else
header("home.php");
{
#renderForm('','','');
it should be
else
{
// header should be inside the else part
header("Location:home.php");
#renderForm('','','');

wrong <select> value when editing php form

I really hope you can help me.
I've done a form, where I can opt if a client I'm adding to the database is "Active or "Inactive", using a dropdown select box.
My code saves all the data correctly to the datbase, but when I want to edit the client, the option displays always as "Active", ignoring the value from the database.
I have 2 files:
edita_clientes.php - the form where I can edit the clients values
salvar_edicao.php - the file that saves the edition.
Here are the codes:
edita_clientes.php:
<?php
#ini_set('display_errors', '1');
error_reporting(E_ALL);
$id = $_GET["id_cliente"];
settype($id, "integer");
mysql_connect("localhost", "root", "");
mysql_select_db("sistema");
$resultado = mysql_query("select * from tabela where id_cliente = $id");
$dados = mysql_fetch_array($resultado);
mysql_close();
?>
<form id="edita_pj" name="edita_pj" method="post" action="salvar_edicao.php">
<input type="hidden" name="id_cliente" id="id_cliente" value="<?php echo $id;?>" />
<div class="box-body">
<div class="form-group">
<label>Razão Social</label>
<input type="text" name="razao" id="razao" class="form-control" value="<?php echo $dados["razao"];?>" />
</div>
<div class="form-group">
<label>Nome Fantasia</label>
<input type="text" name="fantasia" id="fantasia" class="form-control" value="<?php echo $dados["fantasia"];?>" />
</div>
</div>
<div class="box-body">
<div class="form-group">
<label>CNPJ</label>
<input type="text" name="cnpj" id="cnpj" class="form-control" data-inputmask='"mask": "999.999.999-99"' data-mask value="<?php echo $dados["cnpj"];?>">
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-9">
<label>Logradouro</label>
<input type="text" name="logradouro" id="logradouro" class="form-control" value="<?php echo $dados["logradouro"];?>">
</div>
<div class="col-xs-3">
<label>Número</label>
<input type="text" name="numero" id="numero" class="form-control" value="<?php echo $dados["numero"];?>">
</div>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-9">
<label>Bairro</label>
<input type="text" name="bairro" id="bairro" class="form-control" value="<?php echo $dados["bairro"];?>">
</div>
<div class="col-xs-3">
<label>CEP</label>
<input type="text" name="cep" id="cep" class="form-control" data-inputmask='"mask": "99999-999"' data-mask value="<?php echo $dados["cep"];?>">
</div>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-10">
<label>Cidade</label>
<input type="text" name="cidade" id="cidade" class="form-control" value="<?php echo $dados["cidade"];?>">
</div>
<div class="col-xs-2">
<label>UF</label>
<input type="text" name="uf" id="uf" class="form-control" value="<?php echo $dados["uf"];?>">
</div>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-9">
<label>E-mail</label>
<input type="text" name="email" id="email" class="form-control" value="<?php echo $dados["email"];?>">
</div>
<div class="col-xs-3">
<label>Telefone</label>
<input type="text" name="telefone" id="telefone" class="form-control" data-inputmask='"mask": "(99) 9999.9999"' data-mask value="<?php echo $dados["telefone"];?>"/>
</div>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-9">
<label>Contato</label>
<input type="text" name="contato" id="contato" class="form-control" value="<?php echo $dados["contato"];?>">
</div>
<div class="col-xs-3">
<label>Estado</label>
<select class="form-control" name="estado" id="estado" value=""><?php echo $dados["estado"];?>
<option>Ativo</option>
<option>Inativo</option>
</select>
</div>
</div>
<div class="form-group">
<label>Observações</label>
<textarea class="form-control" name="obs" id="obs" rows="6" ><?php echo $dados["obs"];?>
</textarea>
</div>
</div>
<div class="box-footer">
<button type="submit" name="Submit" class="btn btn-primary">Salvar</button>
</div>
</form>
salvar_edicao.php:
<?php
#ini_set('display_errors', '1');
error_reporting(E_ALL);
$razao = $_POST["razao"];
$fantasia = $_POST["fantasia"];
$cnpj = $_POST["cnpj"];
$logradouro = $_POST["logradouro"];
$numero = $_POST["numero"];
$bairro = $_POST["bairro"];
$cep = $_POST["cep"];
$cidade = $_POST["cidade"];
$uf = $_POST["uf"];
$email = $_POST["email"];
$telefone = $_POST["telefone"];
$contato = $_POST["contato"];
$estado = $_POST["estado"];
$obs = $_POST["obs"];
$id = $_POST["id_cliente"];
mysql_connect("localhost", "root", "");
mysql_select_db("sistema");
mysql_query("UPDATE tabela SET razao = '$razao', fantasia = '$fantasia', cnpj = '$cnpj', logradouro = '$logradouro', numero='$numero', bairro='$bairro', cep='$cep', cidade = '$cidade', uf='$uf', email = '$email', telefone = '$telefone', contato = '$contato', estado = '$estado', obs = '$obs' WHERE tabela.id_cliente = $id");
mysql_close();
header("Location: consulta.php");
?>
You need to add 'selected' to the option that you want to be selected, based on a value from the form/db. Here is an example using $value as the option value that you want selected.
<select class="form-control" name="estado" id="estado">
<option <?php echo $value == 'Ativo' ? selected : '' ?>>Ativo</option>
<option <?php echo $value == 'Inativo' ? selected : '' ?>>Inativo</option>
</select>
Also, your <select> tag does not require a 'value' element..
The HTML select element does not have a value attribute. For the select to do what you want you need to add the selected attribute to the option you want selected. It's always showing as 'Active' because that's the first option and it is the default.
The resulting post-php HTML will need to look something like this stripped back example for 'Inactive' to be selected.
<select>
<option>Active</option>
<option selected>Inactive</option>
</select>
Thank's for all the help!
The solution I've found was:
<?php
$resultado = mysql_query("select * from tabela where id_cliente = $id");
$dados = mysql_fetch_array($resultado);
$query = mysql_query("SELECT * FROM estado");
?>
And the html part:
<select class="form-control" name="estado" id="estado">
<option selected="selected"><?php echo $dados["estado"];?></option>
<option value="Ativo">Ativo</option>
<option value="Inativo">Inativo</option>
</select>

Categories