This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP: “Notice: Undefined variable” and “Notice: Undefined index”
In html code:
<select name="123023d">
<option value="default">Not Share</option>
<option value="read">Read Only</option>
<option value="edit">Editable</option>
</select>
In php code:
$rights=$_POST['123023d'];
Why i can not retrieve the value of this select box?
Notice: Undefined index: 123023d in C:\xampp\htdocs\fyp\list\add.php on line 87
Thank you.
I am sure it is in the form and it is a post method. It is located after foreach ($result as $set) as you can see i draw some sql value to generate that select box and the name of the select box is userID
Whole part:
<form id="addlist" method="post" action="add.php" >
<h1>Create your new subscriber list</h1>
<p>Create a new list before adding subscriber <label class="right"><em class="dot">*</em> indicates required</label></p>
<label><em class="dot">*</em> List name:
<span class="small">Add your list name</span>
</label>
<input id="lname" name="lname" class="required" />
<div class="spacer"></div>
<label>Reminder:
<span class="small">Remind the details of your list</span>
</label>
<textarea id="creminder" name="creminder" cols="52" ></textarea>
<div class="spacer"></div>
<div class="spacer"></div>
<p>Email me when ...</p>
<label>People subscribe:</label> <input type="checkbox" class="checkbox" name="subscribe" value="1">
<label>People unsubscribe:</label> <input type="checkbox" class="checkbox" name="unsubscribe" value="1">
<div class="spacer"></div>
</div>
</br>
<div id="stylized" class="myform">
<p>Permission Setting ...</p>
<label>Open to other users:</label> <input type="checkbox" class="checkbox" name="public" value="1">
Or
<div class="spacer"></div>
Select the permission for individual user:
<?
$sql =
"SELECT UserID,Name,Rights,Position
FROM user
WHERE UserID != ?
AND Rights != 'Admin'
";
$stmt = $conn->prepare($sql);
$stmt->execute(array($_SESSION['username']));
$num_rows= $stmt->rowCount();
if ($num_rows != 0){
$result = $stmt->fetchAll();
?>
<table width="100%" class="display" id="viewSub">
<thead>
<tr>
<th field="col1" width="40%">Name:</th>
<th field="col2" width="40%">Position:</th>
<th field="col2" width="20%">Permission:</th>
</tr>
</thead>
<tbody>
<?
foreach ($result as $set)
{
echo "<tr><td>".$set['Name']."</td><td>".$set['Position']."</td><td><select name=".$set['UserID']."><option value='default'>Not Share</option><option value='read'>Read Only</option><option value='edit'>Editable</option></select></td></tr>";
}
?>
</tbody>
</table>
<?
}
else
echo "There is no another user in this system";
?>
<input class="submit" type="submit" name="submit" value="Submit"/>
<div class="spacer"></div>
</form>
add.php which is the form and the result process
<?
include("../connection/conn.php");
session_start();
if($_SERVER['REQUEST_METHOD'] == "POST"){
print_r($_POST);
exit();
if (!isset($_POST['subscribe']))
$_POST['subscribe']=0;
if (!isset($_POST['unsubscribe']))
$_POST['unsubscribe']=0;
if (!isset($_POST['public']))
$_POST['public']=0;
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$listName = $_POST['lname'];
$listRemindSub = $_POST['subscribe'];
$creator = $_SESSION['username'];
$listRemindUnSub = $_POST['unsubscribe'];
$isPublic = $_POST['public'];
$listReminder = $_POST['creminder'];
$query="INSERT INTO list (ListID,ListName,Creator,IsRemindSub,IsRemindUnSub,IsPublic,CreateDate,Reminder) VALUES ('',?,?,?,?,?,CURDATE(),?)";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $listName , PDO::PARAM_STR);
$stmt->bindParam(2, $creator, PDO::PARAM_STR);
$stmt->bindParam(3, $listRemindSub, PDO::PARAM_INT);
$stmt->bindParam(4, $listRemindUnSub, PDO::PARAM_INT);
$stmt->bindParam(5, $isPublic, PDO::PARAM_INT);
$stmt->bindParam(6, $listReminder, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
die ($e->getMessage().' Back');
$conn->rollBack();
}
try {
$lastID=$conn->lastInsertId();
$query="INSERT INTO require_attributes (ReqID,ListID,Attribute,Tag) VALUES ('',$lastID,'Email','{email}')";
$stmt = $conn->prepare($query);
$stmt->execute();
$query="INSERT INTO require_attributes (ReqID,ListID,Attribute,Tag) VALUES ('',$lastID,'FirstName','{fname}')";
$stmt = $conn->prepare($query);
$stmt->execute();
$query="INSERT INTO require_attributes (ReqID,ListID,Attribute,Tag) VALUES ('',$lastID,'LastName','{lname}')";
$stmt = $conn->prepare($query);
$stmt->execute();
}
catch(PDOException $e)
{
die ($e->getMessage().' Back');
$conn->rollBack();
}
try{
$sql = '
SELECT UserID
FROM user
WHERE Rights != ?';
$stmt = $conn->prepare($sql);
$stmt->execute(array('admin'));
$result= $stmt->fetchAll();
}
catch(PDOException $e)
{
die ($e->getMessage().' Back');
}
foreach ($result as $set)
{
if ($set['UserID']==$_SESSION['username'])
$rights='edit';
else
{$rights=$_POST[$set["UserID"]];
$rights=$_POST['123023d'];}
if ($rights != 'default' || $set['UserID']==$_SESSION['username'] || $_POST['public']==0)
{
$user=$set['UserID'];
try {
$query="INSERT INTO user_list(UserID,ListID,UserRights) VALUES ('$user',$lastID,'$rights')";
$stmt = $conn->prepare($query);
$stmt->execute();
}
catch(PDOException $e)
{
die ($e->getMessage().' Back');
$conn->rollBack();
}
}
}
$conn = null;
?>
<div id="stylized" class="myform">
<div style="text-align:center;font-weight:bold;">You have created a list. By default Mail Address, First Name , Last Name is in your list. Add more field if you want. <a href='add.php'>Back</a></div>
<div class="spacer"></div>
</div>
<?
}else{?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
#import "../plugin/easyui/themes/default/easyui.css";
#import "../plugin/easyui/themes/icon.css";
#import "../style/form.css";
#import "../plugin/datatable/media/css/demo_page.css";
#import "../plugin/datatable/media/css/demo_table.css";
</style>
<script src="../plugin/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="../plugin/easyui/jquery.easyui.min.js"></script>
<script src="../plugin/jquery.validate.min.js"></script>
<script type="text/javascript" src="../plugin/datatable/media/js/jquery.dataTables.js"></script>
<script src="../plugin/jquery.form.js"></script>
<script>
$(document).ready(function(){
$("#addlist").validate();
});
$(document).ready(function() {
$('#viewSub').dataTable();
} );
</script>
</head>
<body>
<div id="stylized" class="myform">
<form id="addlist" method="post" action="add.php" >
<h1>Create your new subscriber list</h1>
<p>Create a new list before adding subscriber <label class="right"><em class="dot">*</em> indicates required</label></p>
<label><em class="dot">*</em> List name:
<span class="small">Add your list name</span>
</label>
<input id="lname" name="lname" class="required" />
<div class="spacer"></div>
<label>Reminder:
<span class="small">Remind the details of your list</span>
</label>
<textarea id="creminder" name="creminder" cols="52" ></textarea>
<div class="spacer"></div>
<div class="spacer"></div>
<p>Email me when ...</p>
<label>People subscribe:</label> <input type="checkbox" class="checkbox" name="subscribe" value="1">
<label>People unsubscribe:</label> <input type="checkbox" class="checkbox" name="unsubscribe" value="1">
<div class="spacer"></div>
</div>
</br>
<div id="stylized" class="myform">
<p>Permission Setting ...</p>
<label>Open to other users:</label> <input type="checkbox" class="checkbox" name="public" value="1">
Or
<div class="spacer"></div>
Select the permission for individual user:
<?
$sql =
"SELECT UserID,Name,Rights,Position
FROM user
WHERE UserID != ?
AND Rights != 'Admin'
";
$stmt = $conn->prepare($sql);
$stmt->execute(array($_SESSION['username']));
$num_rows= $stmt->rowCount();
if ($num_rows != 0){
$result = $stmt->fetchAll();
?>
<table width="100%" class="display" id="viewSub">
<thead>
<tr>
<th field="col1" width="40%">Name:</th>
<th field="col2" width="40%">Position:</th>
<th field="col2" width="20%">Permission:</th>
</tr>
</thead>
<tbody>
<?
foreach ($result as $set)
{
echo "<tr><td>".$set['Name']."</td><td>".$set['Position']."</td><td><select name=".$set['UserID']."><option value='default'>Not Share</option><option value='read'>Read Only</option><option value='edit'>Editable</option></select></td></tr>";
}
?>
</tbody>
</table>
<?
}
else
echo "There is no another user in this system";
?>
<input class="submit" type="submit" name="submit" value="Submit"/>
<div class="spacer"></div>
</form>
<div class="spacer"></div>
</div>
<br><br><br>
<div id="stylized" class="myform">
<?
try{
$sql = '
SELECT *
FROM list,user_list
WHERE user_list.UserID=?
AND list.ListID=user_list.ListID
';
$stmt = $conn->prepare($sql);
$stmt->execute(array($_SESSION['username']));
$result= $stmt->fetchAll();
$num_rows= $stmt->rowCount();
}
catch(PDOException $e)
{
die ($e->getMessage().' Back');
}
$conn = null;
if ($num_rows == 0) {
echo '<div style="text-align:center;font-weight:bold;">You have not created any list yet.</div>';}
else {
echo '<h1>Your Subscriber List</h1> <p>You have created '.$num_rows.' list(s).</p>';
foreach ($result as $set)
{
echo '<div style="font-weight:bold;">List Name : '.$set['FromName'].'</div><br>';
echo '<div style="font-weight:bold;">Subscriber : </div><br>';
echo '<div style="font-weight:bold;">Create Date : '.$set['CreateDate'].'</div><br>';
echo '<hr>';
}}
?>
<div class="spacer"></div>
</div>
</div>
</body>
</html>
<?
}
?>
Note the method you are using to submit the form. There are two general ways
GET Method <form method="GET" ... >
This is generally retrieved by using
echo $_GET['123023d'];
POST Method <form method="POST" ... >
This is generally retrieved by using
echo $_POST['123023d'];
If no method is defined, by default, it will be submitted using GET method so, use
$rights=$_GET['123023d'];
Update
I found your problem, there is no quotes in the title of select box
<select name=".$set['UserID'].">
Change it to this. You have to provide the quotes and escape them as well.
<select name=\"".$set['UserID']."\">
Update 2
Credit to #zerkms
The another problem was starting the name with a numeric value instead of a alphabetically character.
<select name="123023d">
Make sure you dont start with numbers like
<select name="a123023d">
How to retrieve value from a select box?
it is stored in the $_POST['123023d'] or $_GET['123023d'] variable depends on the method used.
If it is a 'post' request , use :
$rights=$_POST['123023d'];
For 'get' requests :
$rights=$_GET['123023d'];
Related
I'm new to PHP. I'm trying to display search result based on user query. My issue is that I'm not getting all other similar search results (only the exact results are showing). Is it the right method I'm implementing from security point of view? Thanks in advance.
define('HOST','localhost');
define('USER','root');
define('PASSWORD_HOST','');
define('DATABASE','test');
if(defined('HOST') && defined('USER') && defined('PASSWORD_HOST') && defined('DATABASE')){
$conn = mysqli_connect(HOST, USER, PASSWORD_HOST, DATABASE);
}else{
die(connection_failed.mysqli_connection_error());
}
Here is HTML
<div class="container">
<div class="row">
<div class="col-sm-12">
<form action="" method="POST">
<h4>Search By</h4>
<input type="text" name="delName"/>
<button type="submit" name="submit">search</button>
</form>
</div>
</div>
</div>
Here is PHP
if(isset($_POST['submit'])){
$delName = "%{$_POST['delName']}%";
$stmt =$conn->prepare("SELECT id, delName, medName, contact1, contact2, address, pin, creditLimitDealer FROM dealerentrytable WHERE delName LIKE ?");
$stmt->bind_param("s", $delName);
$stmt->execute();
$stmt->bind_result($id, $delName, $medName, $contact1, $contact2,$address,$pin,$creditLimitDealer);
while ($stmt->fetch()) {
echo "<table>";
echo "<tr><td>ID: $id</td>";
echo "<td>delName: $delName</td>";
echo "<td>medName: $medName</td>";
echo "<td>contact1: $contact1</td>";
echo "<td>contact2: $contact2</td>";
echo "<td>address: $address</td>";
echo "<td>pin: $pin</td>";
echo "<td>creditLimitDealer: $creditLimitDealer</td></tr>";
echo "</table>";
}
$stmt->close();
}
?>
I have 2 problems, my first problem is that I have an error with my PHP script. It basically give me this
Fatal error: Uncaught Error: Cannot pass parameter 2 by reference in /customers/1/d/9/the-scientist.fr/httpd.www/api/addPost.php:30 Stack trace: #0 {main} thrown in /customers/1/d/9/the-scientist.fr/httpd.www/api/addPost.php on line 30
And my second problem is that I'm trying to insert an image in a row in MariaDB, I want to do the same thing as PHPMyAdmin for the image insertion in a BLOB row. So, this is my PHP script:
<?php
try
{
$db = new PDO('mysql:host=the-scientist.fr.mysql;dbname=the_scientist_fr_appli_posts;charset=utf8', 'the_scientist_fr_appli_posts', 'arthur2205');
}
catch(Exception $e)
{
die('Erreur : '.$e->getMessage());
}
// $security = new White\Security;
$post = $_POST;
$img = base64_encode(file_get_contents($_FILES['img']['tmp_name']));
$title = addslashes($post['title']);
$description = addslashes($post['description']);
$fullDesc = addslashes($post['full']);
// if (!empty($title) & !empty($description) & !empty($fullDesc) & !empty($img)) {
// }
// else {
// // header("Location: form.php?error=Fill the form!");
// }
$stmt = $db->prepare("INSERT INTO posts (title, description, img, fullDesc, likes) VALUES (:title, :description, :img, :fullDesc, :likes)");
$stmt->bindParam(':title', $title);
$stmt->bindParam(':description', $description);
$stmt->bindParam(':img', $img);
$stmt->bindParam(':fullDesc', $fullDesc);
$stmt->bindParam(':likes', 0);
$stmt->execute();
// header("Access-Control-Allow-Origin: *");
header("Location: form.php?error=$sql");
Also, this is the form:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionic/1.3.2/css/ionic.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form enctype="multipart/form-data" class="form" id="form" action="./addPost.php" method="POST">
<div class="list">
<label class="item item-input">
<input type="text" placeholder="Titre" class="AddPosttitle" name="title">
</label>
<label class="item item-input">
<input class="description" type="text" placeholder="Mot Clés" maxlength="60" name="description">
</label>
<label class="item item-input">
<div>
<span id='button_upload'>Image : </span>
<input type='file' class="img" name="img">
</div>
</label>
<label class="item item-input">
<textarea placeholder="Description" class="full" name="full"></textarea>
</label>
<div class="padding">
<button class="button button-block button-positive submit-btn" type="submit">
Envoyer
</button>
</div>
</div>
</form>
<style type="text/css">
.form {
background: #FFF;
}
</style>
<?php
if (!empty($_GET['error'])){
?>
<script type="text/javascript">
function findGetParameter(parameterName) {
var result = null,
tmp = [];
var items = location.search.substr(1).split("&");
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
}
return result;
}
alert(findGetParameter("error"));
</script><?php
}
?>
I think that at this point, my problem is pretty clear, if you need more informations, ask in the comment section 😄.
About the first problem: You are using:
$stmt->bindParam(':likes', 0);
bindParam() expects a parameter, a variable.
If you just want to bind a value, you should use bindValue() instead:
$stmt->bindValue(':likes', 0);
I'm working with a group in my Comp. Sci class on this website project with PHP, mySQL and HTML, and we're having some trouble with a search function.
Here is the full code:
<html>
<head>
<title>US Cities Database</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="index.css" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<script>
function doWhenReady () {
$('a').click(showMap);
};
function showMap(event) {
var element = $(event.currentTarget);
var lat = element.attr('lat');
var long = element.attr('long');
var url = "https://maps.google.com/maps?q="+lat+","+long+"&h1=es&z=12&t=m&output=embed";
$('iframe').attr('src', url);
}
$(document).ready(doWhenReady);
</script>
<body class="container">
<h4>US Cities Zip Code and Latitude / Longitude Locator</h4>
<p><strong>Make sure to enter the smaller Zip Code in the first box, and the larger Zip Code in the second box.</strong></p>
<form action="index.php" method="POST" class="form-inline">
<div class="form-group">
<label for="city">City</label>
<input type="text" class="form-control" name="city" />
</div>
<div class="form-group">
<label for="state">State</label>
<input type="text" class="form-control" name="state" />
</div>
<div class="form-group">
<label for="zipFrom">Zipcode from:</label>
<input type="text" class="form-control" name="zipFrom" />
</div>
<div class="form-group">
<label for="zipTo">to:</label>
<input type="text" class="form-control" name="zipTo" />
</div>
<button type="submit" class="btn btn-default btn-primary">Search</button>
</form>
<hr>
<div class="row">
<div class="col-md-5 scrollable">
<div class="search-results">
<h4>Search results:</h4>
<?php
$host = 'localhost';
$username = 'caleyhalpern';
$password = '';
$dbName = 'project224';
$db = mysqli_connect ($host, $username, $password, $dbName);
if (!$db) {
die("Failed to connect to MySQL: (" . mysqli_connect_errno() . ") " . $mysqli->connect_error);
}
$searchCity = $_POST['city'];
$searchState = $_POST['state'];
$searchZipCode = $_POST['zipcode'];
if ((isset($searchCity) || isset($searchState)) && (($searchCity != '') || ($searchState != '')))
$query = 'SELECT * FROM zips WHERE city LIKE "%'.$searchCity.'%" AND state LIKE "%'.$searchState.'%"';
$results = mysqli_query($db, $query);
$resultArray = mysqli_fetch_all($results, MYSQLI_ASSOC);
?>
<table class="table table-striped table-condensed small">
<thead>
<tr>
<th>Show</th>
<th>Zip</th>
<th>State</th>
<th>City</th>
<th>Lat</th>
<th>Long</th>
</tr>
</thead>
<tbody>
<?php
foreach($resultArray as $city) {
echo "<tr>";
echo '<td>Show</td>';
echo "<td>".$city['zip']."</td>";
echo "<td>".$city['state']."</td>";
echo "<td>".$city['city']."</td>";
echo "<td>".$city['lat']."</td>";
echo "<td>".$city['lng']."</td>";
echo "</tr>";
}
?>
</tbody>
</table>
<?php
}
?>
</div>
</div>
<div class="col-md-7">
<div class="map">
<h4>Map:</h4>
<iframe src=""></iframe>
</div>
</div>
</div>
</body>
</html>
Sorry it's kind of lengthy, but if you scroll down to the PHP section, you'll see the "if((isset(...", and that's where we are having trouble. We have the search function for the cities and states, yet we're having trouble with the Zip Codes search function. We're trying to make it so the user inputs two zip codes, the smaller zip code going in the first search box, and the larger zip code going in the second search box. (For ex: 1st: 82190, and 2nd: 92120). And it will search for every zip code in between those two that the user put in. I understand that the search function will be similar to that of the city's/state's- we're just new to PHP and MySQL and are struggling a bit.
First, you need to check that the two zip code fields are numeric, and if not, then set a default value, say 00000 for $zipFrom and 99999 for $zipTo.
$zipFrom = $_POST['zipFrom'];
if (!is_numeric($zipFrom))
$zipFrom = 0;
Handle the value of $zipTo similarly. You should also check that $zipFrom <= $zipTo and swap them if not. (Always, always, always program defensively!) After that, the query itself is simple. Here's how to do it with a prepared statement:
$query = 'SELECT * FROM zips
WHERE zipcode >= ?
AND zipCode <= ?';
$stmt = $db->prepare($query);
$stmt->bind_param('ii', $zipFrom, $zipTo);
$stmt->execute();
$rslt = $stmt->get_result();
$resultArray = $rslt->fetch_all(MYSQLI_ASSOC);
The call to bind_param maps the two variables to the two question-mark placeholders in the query. The first argument ('ii') specifies the data types of the values.
I leave error handling as an exercise for the reader.
You could try something like this...
$query = "SELECT * FROM zips WHERE city LIKE '%".$searchCity."%')";
$result = mysqli_query($db, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['zip'];
// echo any others you need
}
}
I am trying to update the records but the update query is not working for some reason.It is deleting and inserting fine but somehow the update doesn't work.I have checked various questions but couldn't find the answer.I have checked the data inserted in the query and its fine too.This is my code.
<?php
require 'database.php';
$ido = 0;
if ( !empty($_GET['id'])) {
$ido = $_REQUEST['id'];
echo $ido;
}
if ( !empty($_POST)) {
// keep track validation errors
$nameError = null;
$descError = null;
$priceError = null;
// keep track post values
$name = $_POST['name'];
$desc = $_POST['desc'];
$price = $_POST['price'];
// validate input
$valid = true;
if (empty($name)) {
$nameError = 'Please enter Name';
$valid = false;
}
if (empty($desc)) {
$descError = 'Please enter Valid descriptin';
$valid = false;
}
if (empty($price) || filter_var($price, FILTER_VALIDATE_INT) == false) {
$priceError = 'Please enter a valid price';
$valid = false;
}
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE Items SET I_name = ? , I_desc = ? ,I_price = ? WHERE I_id = ?"; <---This is the update query part
$q = $pdo->prepare($sql);
$q->execute(array($name,$desc,$price,$ido)); <---these are the values inserted
Database::disconnect();
header("Location: index.php");
}
}
else {
echo $ido;
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM Items where I_id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($ido));
$data = $q->fetch(PDO::FETCH_ASSOC);
$name = $data['I_name'];
$desc = $data['I_desc'];
$price = $data['I_price'];
Database::disconnect();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Update Items</h3>
</div>
<form class="form-horizontal" action="update_items.php" method="post">
<div class="control-group <?php echo !empty($nameError)?'error':'';?>">
<label class="control-label">Name</label>
<div class="controls">
<input name="name" type="text" placeholder="Item Name" value="<?php echo !empty($name)?$name:'';?>">
<?php if (!empty($nameError)): ?>
<span class="help-inline"><?php echo $nameError;?></span>
<?php endif; ?>
</div>
</div>
<div class="control-group <?php echo !empty($descError)?'error':'';?>">
<label class="control-label">Description</label>
<div class="controls">
<input name="desc" type="text" placeholder="Item Description" value="<?php echo !empty($desc)?$desc:'';?>">
<?php if (!empty($descError)): ?>
<span class="help-inline"><?php echo $descError;?></span>
<?php endif;?>
</div>
</div>
<div class="control-group <?php echo !empty($priceError)?'error':'';?>">
<label class="control-label">Price</label>
<div class="controls">
<input name="price" type="text" placeholder="Item Price" value="<? php echo !empty($price)?$price:'';?>">
<?php if (!empty($priceError)): ?>
<span class="help-inline"><?php echo $priceError;?></span>
<?php endif;?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Create</button>
<a class="btn" href="index.php">Back</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>
This is your form:
<form class="form-horizontal" action="update_items.php" method="post">
^ nothing here
As you can see you are posting and there is no query variable after the url you are posting to.
Then you check for the ID:
$ido = 0;
if (!empty($_GET['id'])) {
$ido = $_REQUEST['id'];
echo $ido;
}
$ido will remain 0 as there is no $_GET['id'].
You can either modify your form to add the ID or add a hidden variable in the form with the ID and check for $_POST['id'].
I'd go for the second option:
<form class="form-horizontal" action="update_items.php" method="post">
<input type="hidden" name="id" value="<?php echo $ido; ?>">
and in php:
if (!empty($_POST)) {
$ido = $_POST['id'];
In following code, how can I add a button or a link that sorts the data by 'name'?
The following code is just an example, a modified version of code that I found from http://fwebde.com/php/sqlite-php/ . The structure of the code is so enjoyable that I would like to improve it with a sorting-element.
Thanks!
<?php
$db = new PDO('sqlite:db.db');
if (isset($_POST['name']) && isset($_POST['message'])) {
try {
$stmt = $db->prepare("INSERT INTO messages (name, message) VALUES (:name, :message);");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':message', $message);
$title = $_POST['name'];
$content = $_POST['message'];
$stmt->execute();
} catch (Exception $e) {
die ($e);
}
}try {
$posts = $db->prepare('SELECT * FROM messages;');
$posts->execute();
} catch (Exception $e) {
die ($e);
}
?>
<?php while ($post = $messages->fetchObject()): ?>
<?php echo $post->name ?>
<?php echo $post->message ?>
<?php endwhile; ?>
<form action="" method="post">
<label for="name">Name:</label>
<input type="text" name="name" />
<textarea name="message" rows="8" cols="50"></textarea>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
$db = new PDO('sqlite:db.db');
if (isset($_POST['submit']) && isset($_POST['name']) && isset($_POST['message'])) {
try {
//Insert data
} catch (Exception $e) {
die ($e);
}
}
try {
$order = "";
if(isset($_POST['sort'])){
$order = " ORDER BY `name`"; // Order list by name
$orderFlag = 1;
if(isset($_POST['order']) && $_POST['order'] == 1){
$order .= " DESC";
$orderFlag = 0;
}
}
$posts = $db->prepare("SELECT * FROM `messages`" . $order . ";");
$posts->execute();
} catch (Exception $e) {
die ($e);
}
?>
<?php while ($post = $posts ->fetchObject()): ?>
<?php echo $post->name ?><?php echo $post->message ?><br/>
<?php endwhile; ?>
<form action="" method="post">
<!--pushing this button sort by name -->
<input type="submit" name="sort" value="Sort by name" />
<input type="hidden" name="order" value="<?=$orderFlag?>" />
<label for="name">Name:</label>
<input type="text" name="name" />
<textarea name="message" rows="8" cols="50"></textarea>
<!--pushing this button insert new data -->
<input type="submit" name="submit" value="Submit" />
</form>