insert values from multiple checkbox into database PHP [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
handling checked checkboxes PHP
i have this problem. I have a webpage that show car registration number and it's violation. And we can change the status of the violation from 1=not treated to 2=treated. I want to use multiple check box to choose which car registration status that i want to change
here's the screenshot of my web
)
how i change the status of both car registration number ?
here's my webpage code
<div id="content">
<div class="content_item">
<?php
$con = mysql_connect("localhost","fpjarmul","fpjarmul");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("fpjarmul", $con);
$query = "SELECT * FROM laporan WHERE status = '1'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{?>
<form action="ubahdata.php" method="post">
<input type="checkbox" name="idlaporan" value="<?php echo $row['idlaporan'] ?>" /><?php echo "ID : {$row['idlaporan']}" ?><br />
<?php echo "Nomor Polisi : {$row['platkendaraan']} <br>" .
"Status : {$row['status']} <br>" .
"Tanggal Laporan : {$row['tanggallapor']} <br><br>"; ?>
<?php
}
?>
<input type="submit">
</form>
and here's my script
<?php include 'header.php'; ?>
<?php
$con = mysql_connect("localhost","fpjarmul","fpjarmul");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("fpjarmul", $con);
$sql=("UPDATE laporan set status='2' where idlaporan='$_POST[idlaporan]'");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
?>
<?php include 'footer.php'; ?>

Please try the following approach:
Change the checkbox 'name' as 'idlaporan[]' (<input type="checkbox" name="idlaporan[]" )
After form submit, selected check box values will be present in the Server side array $_POST['idlaporan']
Use a foreach loop to update values in database.
foreach ($_POST['idlaporan'] as $idlaporan) {
$sql=("UPDATE laporan set status='2' where idlaporan='$idlaporan'");
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
echo "1 record added<br/>";
}

Related

PHP checklist get ID and value and store it

So I have a form to add a new item to database with a checkbox as follows
So my difficulty is the checkbox. I can easily enough create the array for all items checked but I need an ID for them along with it. I've tried to think of many ways and searched a lot but I just can't think of a way to get the ID in a way that is then useable to me along with the name of the feature (checklist). Since I have to get each feature item and add it to the table houses_has_features.
<?php
$title = 'Add a new house';
require_once 'header.php';
require_once 'nav.php';
require_once 'mysqli-con.php';
$conn = new MYSQLI($hn, $un, $pw, $db);
// If house name and type is set then add them into the database
if( !empty($_POST['h_name']) && !empty($_POST['h_type']) ) {
$house_name = $conn->real_escape_string($_POST['h_name']);
$house_type = $conn->real_escape_string($_POST['h_type']);
//show names added
echo '<b>House name: </b>'.$house_name . '<br><b> House type:</b> ' . $house_type;
$query = "INSERT INTO `house_names` (`id`, `name`) VALUES (NULL, '$house_name')";
$result = $conn->query($query);
if (!$result) die ("<b class='text-danger'><p>Insert failed ERRROR: " . $conn->error. "</p>");
global $house_name_id;
$house_name_id = $conn->insert_id;
$query = "INSERT INTO `house_types` VALUES ('$house_name_id', '$house_type')";
$result = $conn->query($query);
if (!$result) die ("<b class='text-danger'><p>Insert failed ERRROR: " . $conn->error. "</p>");
} else {
global $house_name_id;
$house_name_id= NULL;
}
//Start container for page content
echo '<div class="container">';
//Display an error message if house name is filled in but not house type
if ( !empty($_POST['h_name']) && empty($_POST['h_type']) || empty($_POST['h_name']) && !empty($_POST['h_type']) ) {
echo "<p class='error-text'>* Please fill in both the house name and house type *</p>";
}
$query_feat = $conn->query('SELECT * FROM features');
$rows = $query_feat->num_rows;
$features_list = $_POST['check_list'];
$feature_id = $_POST['feature_id'];
//display checked boxes.
if(isset($_POST['check_list'])) {
for ($i=0; $i<sizeof($features_list); $i++){
//echo '<br>House name id:' . $house_name_id . '<br> $_POST[] = ' . "$features_list[]";
print_r($features_list); echo '<br>';
print_r($feature_id);
}
}
// Add house form
echo <<<_END
<h1>Add a house</h1>
</div>
<div class="container">
<form action="add.php" method="post">
<p>House Name: <input type="text" name="h_name"></p>
<p>House type: <input type="text" name="h_type"></p>
<b>features:</b>
<ul class="list-group">
_END;
for ($c = 0 ; $c < $rows ; ++$c){
$query_feat->data_seek($c);
$feat = $query_feat->fetch_array(MYSQLI_NUM);
echo '<li><input type="checkbox" name="check_list[]" value="' .$feat[1]. '">'.$feat[1].'</li>';
}
echo <<<_END
<ul>
<input class="btn-primary" type="submit" value="Submit">
</form>
</div>
_END;
require_once 'footer.php';
I'm really lost on this one any help would be greatly appreciated :)
change your value of checkbox to id or anything you want.
<li><input type="checkbox" name="check_list[]" value="' .$feat[0]. '">'.$feat[1].'</li>
$feat[1] => $feat[0] or else

how to do search in the same page?

1) this my search form
search.html :
<form action="process.php" method="POST">
<input type="text" name="query" />
<input type="hidden" name="searching">
<input type="submit" value="Search" />
</form>
2) All of my search process is handled and will be shown on process.php.
process.php :
<?php
$connection = mysql_connect("*****","*****","*****");
if (!connection) {
die ("Please reload page. Database connection failed: " . mysql_error());
}
// Select a databse to use
$db_select = mysql_select_db("*****",$connection);
if (!$db_select) {
die("Please reload page. Database selection failed: " . mysql_error());
}
if (isset($_POST["searching"])) {
/*call search process*/
dosearch();
}
function doSearch(){
$keyword = $_POST("query");
$search = "SELECT * FROM tbl_name WHERE name LIKE '%$keyword%'";
$result = mysql_query($search) or die('query did not work');
While($result_arr = mysql_fetch_array( $result ))
{
echo $result_arr['name'];
echo " ";
echo "<br>";
echo "<br>";
}
}
?>
3)How to show the search result at page "search.html" and how to combine it into one same page?
You will have to create search.php instead of search.html.
you may try using php sessions. they are very helpful.
you can save whatever variable you want to transfer from "process.php" to "search.php" in the $_SESSION array and then use them in search.php. for example :
in process.php
<?php session_start();
$_SESSION['a']=$result_arr['name'];
?>
then in search.php
<?php session_start();
echo $_SESSION['a'];
?>

Undefined index [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP: “Notice: Undefined variable” and “Notice: Undefined index”
hello everyone i am getting a problem while updating my record..when i click the edit button it doesnot update the record but give following errors to all post variables.. i would really appreciate any kind of comments or help...
this is courses-edit.php
<?php include("../includes/config.php"); ?>
<?php
if ($_SESSION["isteacher"])
{
$con=mysql_connect($dbserver,$dbusername,$dbpassword);
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db($dbname, $con);
$courseid=$_GET["id"];
$result = mysql_query("SELECT * FROM courses WHERE (id='".$courseid."')");
while($row = mysql_fetch_array($result))
{
$id=$row['id'];
$title = $row['title'];
$des = $row['description'];
$subjectid = $row['subjects-id'];
}
mysql_close($con);
?>
<script type="text/javascript">
$(function() {
$("form").validity(function() {
$("#title")
.require("This Field Must Be Filled!!")
});
});
</script>
<?php include("../includes/header.php"); ?>
<?php include("includes/nav.php"); ?>
<div id="maincontent">
<div class="span-24 last">
<div id="breadcrumbs">
Home >
Manage Courses >
List Courses >
Edit Course
</div>
</div>
<?php include("../teacher/includes/manage-courses-aside.php"); ?>
<div class="span-18 last">
<h2 class="alt">Edit Course</h2>
<form id="form" method="post" action="courses-edit-action.php">
<input type="hidden" value="<?php echo $courseid; ?>" name="id" />
<label>Course Name:</label><input type="text" name="title" id="title" class="text" value="<?php echo $title; ?>" /><br /><br />
<label>Choose Subject:</label>
<?php
$con=mysql_connect($dbserver,$dbusername,$dbpassword);
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db($dbname, $con);
$result = mysql_query("SELECT * FROM subjects");
echo "<select name='subjects-id'>\n";
while($row = mysql_fetch_array($result))
{
echo "<option value='".$row['id'] . "'";
if ($subjectid==$row['id'])
echo 'selected="selected"';
echo " >" . $row['subjectname'] . "</option>\n";
}
echo "</select>\n";
mysql_close($con);
?>
<label>Description:</label><textarea name="description" id="description"><?php echo $des; ?></textarea><br /> <br />
<input type="submit" value="Edit Course" class="button" />
</form>
<?php include("../includes/footer.php"); ?>
<?php
}
else
{
header("Location: ".$fullpath."login/unauthorized.php");
}
?>
and this is courses-edit-action.php
<?php include("../includes/config.php");?>
<?php
$id=$_POST["id"];
$title=$_POST["title"];
$des=$_POST["description"];
$subjectid=$_POST["subjects-id"];
$con=mysql_connect($dbserver,$dbusername,$dbpassword);
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("ombts", $con);
$query=("UPDATE courses SET title='".$title."', description='".$des."', 'subjects- id'='".$subjectid."' WHERE (id='".$id."')");
$query=mysql_query($query);
if($result){
echo header("Location:manage-courses.php?status=2");
}
mysql_close($con);
?>
and the warnings are
Notice: Undefined index: id in C:\xampp\htdocs\project\teacher\courses-edit-action.php on line 4
Notice: Undefined index: title in C:\xampp\htdocs\project\teacher\courses-edit-action.php on line 5
Notice: Undefined index: description in C:\xampp\htdocs\project\teacher\courses-edit-action.php on line 6
Notice: Undefined index: subjects-id in C:\xampp\htdocs\project\teacher\courses-edit-action.php on line 7
You try to access
$id=$_POST["id"];
$title=$_POST["title"];
$des=$_POST["description"];
$subjectid=$_POST["subjects-id"];
this POST variables. But when you access the script for the first time this values are not set in the POST variable.
Chck the values with isset.
if(!isset($_POST["id"]) {
$_POST["id"] = '';
}
or safe the checked value in a new variable
$id = isset($_POST["id"]) ? $_POST["id"] : 0;
for example.
Modify your script like this....
$id= isset($_POST["id"]) ?$_POST["id"] : 0 ;
$title= isset($_POST["title"]) ? $_POST["title"] : '' ;
$des=isset($_POST["description"]) ? $_POST["description"] : '';
$subjectid= isset($_POST["subjects-id"]) ? $_POST["subjects-id"] : '';
Edited
Also, i see an error here...
$query=mysql_query($query);
if($result){
should be
$result=mysql_query($query);
if($result){
If you still can't update the table, print the $query variable before you do mysql_query. Tell me what you see and i will help you.....
#Stony's answer is good solution to check if you are sending any POST data - and if not, do not try to fetch non-existing data.
Now, if you think $_POST["id"]; should be there, then there is something missing. Are you using GET instead of POST?
To see what data is submitted do a print_r($_POST). If this is blank, do a print_r($_REQUEST). If this is still blank, then no data is being submitted from the previous page.
You can also check by adding this in your URL &id=75 (or ?id=75 if you have no other parameters in the url). This will submit data and you will see one less error.

Only one select list works on PHP form

Disclaimer: It's been a while since I last wrote any code. The quality of my code is likely to be sub-par. You've been warned.
I have a basic form that's meant to search flat files on our server. The "search engine" I created as two select lists: one for the file names and one for the customer site files come from.
For a reason I can't figure out, whatever option I select from the second select list is never captured when I hit Submit.
However, whatever option I select from the first select list is always captured.
What am I missing? I am sure it's starting right at me.... Any hints welcome. Thank you.
Here's my code:
<HTML>
<head><title>SEARCH TOOL - PROTOTYPE</title></head>
<body><h1>SEARCH TOOL - PROTOTYPE</h1>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<legend>Filename (one item)</legend><select name="DBFilename" id="DBFilename">
<?php $con = mysql_connect("localhost", "user", "pass"); if (!$con) { die('Could not connect: ' . mysql_error());}
mysql_select_db("dev", $con) or die(mysql_error());
$result = mysql_query("select distinct filename from search_test");
while ($row = mysql_fetch_array($result))
{ ?> <option value="<?php echo $row['filename']; ?>"><?php echo $row['filename']; ?></option> <?php } mysql_close($con); ?>
</select></fieldset>
<fieldset>
<legend>Site (one item)</legend><select name="DBSite" id="DBSite">
<?php $con = mysql_connect("localhost", "user", "pass"); if (!$con) { die('Could not connect: ' . mysql_error());}
mysql_select_db("dev", $con) or die(mysql_error());
$result = mysql_query("select distinct site from search_test");
while ($row = mysql_fetch_array($result))
{ ?> <option value="<?php echo $row['site']; ?>"><?php echo $row['site']; ?></option> <?php } mysql_close($con);
?>
</select></fieldset>
<input type="submit" name="submit" value="submit" >
<input type="button" value="Reset Form" onClick="this.form.reset();return false;" />
</form>
</body>
</HTML>
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['DBFilename'])) {doFileSearch();}
elseif (!empty($_POST['DBSite'])) {doSite();}
}
function doFileSearch() {
$mydir = $_SERVER['DOCUMENT_ROOT'] . "/filedepot";
$dir = opendir($mydir);
$DBFilename = $_POST['DBFilename'];
$con = mysql_connect("localhost", "user", "pass");
if (!$con) {die('Could not connect: ' . mysql_error());}
mysql_select_db("dev", $con) or die("Couldn't select the database.");
$getfilename = mysql_query("select filename from search_test where filename='" . $DBFilename . "'") or die(mysql_error());
echo "<table><tbody><tr><td>Results.</td></tr>";
while ($row = mysql_fetch_array($getfilename)) {
$filename = $row['filename'];
echo '<tr><td>' . $filename . '</td></tr>';
}
echo "</table></body>";
}
function doSite() {
$mydir = $_SERVER['DOCUMENT_ROOT'] . "/filedepot";
$dir = opendir($mydir);
$DBSite = $_POST['DBSite'];
$con = mysql_connect("localhost", "user", "pass");
if (!$con) {die('Could not connect: ' . mysql_error());}
mysql_select_db("dev", $con) or die("Couldn't select the database.");
$getfilename = mysql_query("select distinct filename from search_test where site='" . $DBSite . "'") or die(mysql_error());
echo "<table><tbody><tr><td>Results.</td></tr>";
while ($row = mysql_fetch_array($getfilename)) {
$filename = $row['filename'];
echo '<tr><td>' . $filename . '</td></tr>';
}
echo "</table></body>";
}
?>
You have no part of your form with name='submit'
There for you will never get into the if statement that says: if (isset($_POST['submit'])) { because it will always be false
Complete re-re-write here => http://pastebin.com/raw.php?i=qi5F7X2e
There are several problems with my form.
a) Neither one of my SELECT lists are ever empty.
b) I never check for return the values from my functions.
This one is working.
Thanks to all for taking the time.

problem with form php and sql

Ok, so im new in php and sql, and I have this form that submits some names and cities into a database.
I managed to do it, but once a hit the submit button, i get an error:
"Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1"
but, when i check in phpmyadmin, the new record is there!!, so im not sure what's wrong, thats the problem.
this is the code:
<?php
mysql_connect("localhost", "name", "pass") or die(mysql_error());
echo "Connection to the server was successful!<br/>";
mysql_select_db("db_name") or die(mysql_error());
echo "Database was selected!<br/>";
$resultComuna = mysql_query("SELECT idComuna, nombre FROM comuna ORDER BY nombre ASC");
$resultGiro = mysql_query("SELECT idGiro, nombre FROM giro ORDER BY nombre ASC");
?>
<html>
<head>
<title>TEST</title>
</head>
<body>
<br/><br/>
<form name="form" method="POST" action="test_action.php">
<div align="center">
<!--///////////////// input nombre //////////////////////// -->
NOMBRE CLIENTE:
<input name="nombreCliente" type="text" maxlength="30" size="40"></>
<!-- ///////////////////////////////////////////////////////////// -->
<!-- ////////////////////drop box para giro ///////////////////// -->
GIRO:
<select name="giro">
<?php
while($row = mysql_fetch_assoc($resultGiro)){
echo "<option value=\"".$row['idGiro']."\">".$row['nombre']."</option><br/>";
}
?>
</select>
<!-- ///////////////////////////////////////////////////////////// -->
<!-- ////////////// dropbox para comunas //////////////////////// -->
COMUNA:
<select name="comunas">
<?php
while($row = mysql_fetch_assoc($resultComuna)){
echo "<option value=\"".$row['idComuna']."\">".$row['nombre']."</option><br/>";
}
?>
</select>
<!-- ////////////////////////////////////////////////////////////// -->
<input type="submit" value="Ingresar"> </>
</div>
</form>
</body>
</html>
and the test_action.php is:
<?php
$con = mysql_connect("localhost", "name", "pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("data_base", $con);
$query = mysql_query("SELECT max(idNombre)+1 as id FROM nombre");
$row = mysql_fetch_array($query);
$idMax = $row['id'];
$sql = mysql_query("INSERT INTO nombre VALUES ('".$idMax."','".$_POST['comunas']."',".$_POST['giro'].",'".$_POST['nombreCliente']."')");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "record added";
mysql_close($con)
?>
You're inserting the ID in single quotes:
$sql = mysql_query("INSERT INTO nombre VALUES ('".$idMax."','".$_POST['comunas']."',".$_POST['giro'].",'".$_POST['nombreCliente']."')");
Can you provide the table structure? ID is an integer or a varchar there?
Try changing test_action.php to:
<?php
$con = mysql_connect("localhost", "name", "pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("data_base", $con);
$query = mysql_query("SELECT max(idNombre)+1 as id FROM nombre");
$row = mysql_fetch_array($query);
$idMax = $row['id'];
$query = "INSERT INTO nombre VALUES ('".$idMax."','".$_POST['comunas']."',".$_POST['giro'].",'".$_POST['nombreCliente']."')";
$sql = mysql_query($query);
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error().'<br>query: '.$query);
}
echo "record added";
mysql_close($con);
?>
It helps for debugging

Categories