Actually I have a CGI form which consists of textfields and I need a combobox in which I can enter my own data dynamically. May be it seems very silly question but I am new to cgi-perl as well as HTML so no idea what to do. Here is my form:
#!C:\perl\bin\perl.exe
use CGI;
use CGI qw/:standard/;
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
my $q = new CGI;
use DBI;
use CGI qw(:all);
use strict;
use warnings;
print "Content-Type: text/html\n\n";
print $q->header ( );
if ( $q->param("submit") )
{
process_form ( );
}
else
{
display_form ( );
}
sub process_form
{
if ( validate_form ( ) )
{
display_form ( );
}
}
sub validate_form
{
my $User_Name = $q->param("User_Name");
my $User_Password= $q->param("User_Password");
my $User_Permission = $q->param("User_Permission");
my $User_Department= join(", ",$q->param("User_Department"));
my $error_message = "";
$error_message .= "Please enter your name<br/>" if( !$User_Name );
$error_message .= "Please enter your Password<br/>" if( ! $User_Password );
$error_message .= "Please Select a permission<br/>" if( !$User_Permission );
$error_message .= "Please select atleast 1 department<br/>" if(!$User_Department);
if ( $error_message )
{
display_form (
$error_message,$User_Name,$User_Password,$User_Permission,$User_Department);
return 0;
}
else
{
my $dbh = DBI->connect("dbi:SQLite:DEVICE.db","", "",{RaiseError => 1, AutoCommit =>
1 } );
my $sql = "SELECT COUNT(UserName) FROM UsersList WHERE UserName='$User_Name'";
my $sth = $dbh->prepare($sql) or die("\n\nPREPARE ERROR:\n\n$DBI::errstr");
$sth->execute or die("\n\nQUERY ERROR:\n\n$DBI::errstr");
my ($n) = $dbh->selectrow_array($sth);
$sth->finish();
if ($n > 0) {
print "Record Already Exists";
}
else {
my $sql = "INSERT INTO UsersList (UserName,Password,Permission,Department) VALUES
('$User_Name ',' $User_Password','$User_Permission','$User_Department')";
my $sth = $dbh->prepare($sql);
$sth->execute;
print "Record Added Successfully";
$sth->finish();
$dbh->commit or die $dbh->errstr;
}
$dbh->disconnect;
}
}
sub display_form
{
my $error_message = shift;
my $User_Name = shift;
my $User_Password = shift;
my $User_Permission= shift;
my $User_Department= shift;
my $User_Permission_Add_sel = $User_Permission eq "Add" ? " checked" : "";
my $User_Permission_Edit_sel =$User_Permission eq "Edit" ? " checked" : "";
my $User_Permission_Delete_sel =$User_Permission eq "Delete" ? " checked" : "";
my $User_Permission_View_sel =$User_Permission eq "View" ? " checked" : "";
my $User_Department_html = "";
my $dbh = DBI->connect("dbi:SQLite:DEVICE.db","", "",{RaiseError => 1, AutoCommit =>
1 } );
my $sql = "select DepartmentName from Departments order by DepartmentName";
my $sth = $dbh->prepare($sql);
$sth->execute() ;
while (my $User_Department_option= $sth->fetchrow_array)
{
$User_Department_html.= "<option value=\"$User_Department_option\"";
$User_Department_html.= " selected" if ( $User_Department_option eq
$User_Department );
$User_Department_html.= ">$User_Department_option</option>";
}
$sth->finish();
$dbh->commit or die $dbh->errstr;
print <<END_HTML;
<html>
<head><title>Form Validation</title></head>
<body>
<form action="AddUser.cgi" method="post">
<input type="hidden" name="submit" value="Submit">
<p>$error_message</p>
<TABLE BORDER="1" align="center">
<TR>
<TD>Name</TD>
<TD> <input type="text" name="User_Name" value="$User_Name"></TD>
</TR>
<TR>
<TD>Password</TD>
<TD colspan="2"><input type="password" name="User_Password" value="$User_Password"
size="20" maxlength="15" /></TD>
</TR>
<TR>
<TD>Role</TD>
<TD>"HERE I NEED A COMBOBOX"</TD>
</TR>
<TR>
<TD>Permission</TD>
<TD><input type="radio" name="User_Permission"
value="Add"$User_Permission_Add_sel>Add<input type="radio" name="User_Permission"
value="Edit"$User_Permission_Edit_sel>Edit<input type="radio"
name="User_Permission" value="Delete"$User_Permission_Delete_sel>Delete<input
type="radio" name="User_Permission" value="View"$User_Permission_View_sel>View</TD>
</TR>
<TR>
<TD>Department</TD>
<TD colspan="2"> <select name="User_Department" MULTIPLE
SIZE=4>$User_Department_html</select></TD>
</TR>
</TR>
<TR>
<TD align="center" colspan="2">
<input type="submit" name="submit" value="ADD">
</TD>
</TR>
</TABLE
</form>
</body></html>
END_HTML
}
What you're looking for here isn't done on the Perl side, but on the HTML+Javascript side. As noted by others, HTML does not have a built-in combo box form element. So, you're stuck with Javascript.
Personally, I like using JQuery whenever working with Javascript. It's a Javascript library which makes manipulating web pages elements much easier.
Specific to your question, you'll want to look at http://jqueryui.com/demos/autocomplete/ (there is an actual combobox demo linked on the right, if you really, really need a combobox instead of a Google-style autocomplete text field.
Not related to the combobox, but you might also want to look at Template::Toolkit - a templating system for Perl (and others) that will allow you to take the HTML out of your perl scripts. Believe me, having the HTML embedded in CGI scripts for anything beyond the most basic usages will turn into a nightmare soon enough.
In place of "HERE I NEED A COMBOBOX" you have to write :
<select name='User_Department' id='User_Department'>
$User_Department_html
</select>
However, you retrieve parameters within your sub display_form but you've never passed any.
Related
Although I am not sure. update_batch is it possible to without replacing the previous data next updated value will puts by comma separated as an array-form on the SAME FILED . I shown 2 Demo image for better understand. My Code is already running for only batch update But not for update_batch increment value without replacing previous data!
For example -
For 1st time update , column field will shown like this at "t_franchise_price" column ---
For 2nd time When next update will perform , then column field "t_franchise_price" will look like this ---
My Controller is
public function batch_update() {
$sID = $this - > input - > post('test_id[]');
$sAmt = $this - > input - > post('test_priceUpdt[]');
$sOfficeId = $this - > input - > post('fran_office_id');
date_default_timezone_set('Asia/Kolkata');
$edited_test = array();
if (!empty($sID)) {
foreach($sID as $k => $v) {
$edited_test = array(
'test_id' => $sID[$k],
'test_priceUpdt' => $sAmt[$k],
'fran_office_id' => $sOfficeId,
'last_edit_date' => date('Y-m-d H:i:s', time())
);
$edited_test = json_encode($edited_test);
$postData[] = array('test_id' => $v, 't_franchise_price' => $edited_test);
}
$data['franchise_tst_pkg'] = (object) $postData;
}
#-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - #
if ($this - > form_validation - > run() === true) {
$this - > franchise_price_model - > batchTestupdate($postData);
$this - > session - > set_flashdata('message', display('save_successfully'));
redirect('branch/franchise_price/create');
}
**My Model is **
public function batchTestupdate($data = [])
{
$this->db
->update_batch($this->table_test, $data , 'test_id');
}
View
<tr>
<td>
<input type="text" name="test_name[]" class="form-control" placeholder="" value="<?php echo $subject->test_name; ?>" disabled>
<input type="hidden" name="test_id[]" class="form-control" placeholder="" value="<?php echo $subject->test_id; ?>">
</td>
<td>
<input type="text" name="test_price[]" class="form-control" placeholder="" value="<?php echo $subject->test_price; ?>" disabled>
</td>
<td>
<input type="text" name="test_priceUpdt[]" class="form-control" placeholder="" value="<?php echo $subject->test_price; ?>" id="test_priceEdt">
</td>
</tr>
Appends on table field t_franchise_price rather than overwrite.
Change:
$this - > franchise_price_model - > batchTestupdate($postData);
To:
$this->franchise_price_model->batchTestupdate($postData, 2);
Change your model method to this:
public function batchTestupdate($data = [], $method=1){
$db_table = $this->db->dbprefix($this->table_test);
$sql = "";
if($method == 1){
$this->db->update_batch($this->table_test, $data , 'test_id');
}
else if($method == 2){
foreach($data as $k=>$v){
$sql = "UPDATE $db_table SET t_franchise_price = TRIM(BOTH ',' FROM CONCAT(COALESCE(t_franchise_price,''), ',', ?)) WHERE test_id = ?;";
$result = $this->db->query($sql, array($v['t_franchise_price'], $v['test_id']));
if($result === false) {
echo "ERROR at index $k - query: ((".$this->db->last_query()."))<br/><br/>\n\n";
print_r($this->db->error()); echo "<br/><br/>\n\n";
}
}
}
}
I am just trying to figure out the logic behind inserting form data into the database. Below code (load.php) works fine. Howewer I receive somehow a syntax error in process.php, besides I'm not sure if my insert code is correct. I also doubt this code is secure, what is the key security factor that I should consider while working with databases? I know I ask many questions but I just try to get the whole picture. I would appreciate any advice and thoughts.
thanks!
**//process.php**
<?php
require ("load.php");
$fname= $_POST['fname'];
$lname= $_POST['lname'];
$sql = "INSERT INTO registration (firstname, lastname) VALUES ('$_POST[fname]','$_POST[lname]')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
**//load.php**
<?php
$servername = "localhost";
$database = "registration";
$username = "root";
$password = "";
$conn = mysqli_connect($servername, $username, $password, $database);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
**//index.php**
<?php require ("load.php"); ?>
<html>
<head>
<title>Registration Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h3>Registration Form</h3>
<form name="registration" method="post" action="process.php">
<table border="0" cellspacing="2" cellpadding="2">
<tr><td>First Name:</td><td><input type="text" name="fname"></td></tr>
<tr><td>Last Name:</td><td><input type="text" name="lname"></td></tr>
<tr><td> </td><td><input type="submit" name="submit" value="Register"></td></tr>
</table>
</form>
</body>
</html>
Try following code for process.php
This will works
require ("load.php");
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname) VALUES (?, ?)");
$stmt->bind_param("ss", $firstname, $lastname);
$fname= $_POST['fname'];
$lname= $_POST['lname'];
if ($stmt->execute()) {
echo "New record created successfully";
}
$stmt->close();
im Ivica and im new here.
i need form with 5 places for product codes. Every product have 4 rows (name, perex, amount, library_id) in database and i want place solution every products to different places.
Can help?
Sorry for my english.
DB CODE:
<?php
$mysqli = new mysqli('localhost', 'user', 'pass', 'db');
if ($mysqli->connect_error) {
die('Nepodařilo se připojit k MySQL serveru (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$sql = $mysqli->query("SELECT library_id, amount, name, perex, extId
FROM product_item, main_library, product_item_price, product_text
WHERE product_item.product_id = main_library.main_id
AND product_item.id = product_item_price.item_id
AND product_item.product_id = product_text.product_id
AND product_item_price.level_id = 1 AND product_item.extId = '$test'");
echo 'Z databaze jsme ziskali ' . $sql->num_rows . ' radku.';
echo "</br>";
while ($produkt = $sql->fetch_assoc())
{
printf($produkt['name']);
echo "</br>";
printf($produkt['perex']);
echo "</br>";
printf($produkt['amount']);
echo "</br>";
}
$sql->free_result();
$mysqli->close();
?>
Example: I use form and try find 3 different products and these "name", "perex" and "amount" by ID and need to put those results in some tables with any places on page.
FORM:
<form action="search.php" method="REQUEST">
<b>Find product:</b>
<input type="text" name="productID" size="50">
<input type="text" name="productID2" size="50">
<input type="text" name="productID3" size="50">
<br>
<input type="submit" value="Search"> </form>
TABLE:
<table>
<tr>
<td>productID name</td>
<td>productID name</td>
<td>productID name</td>
<tr>
<tr>
<td>productID2 perex</td>
<td>productID2 perex</td>
<td>productID2 perex</td>
<tr>
<tr>
<td>productID3 amount</td>
<td>productID3 amount</td>
<td>productID3 amount</td>
<tr>
</table>
MYSQL look this:
$sql = $mysqli->query("SELECT library_id, amount, name, perex, extId
FROM product_item, main_library, product_item_price, product_text
WHERE product_item.product_id = main_library.main_id
AND product_item.id = product_item_price.item_id
AND product_item.product_id = product_text.product_id
AND product_item_price.level_id = 1
AND (product_item.extId = '$_REQUEST[productID]'
OR product_item.extId = '$_REQUEST[productID2]'
OR product_item.extId = '$_REQUEST[productID3]')");
Can help?
Ivica
I built a simple input drop-down list, using <select> which populates from a mysql database.
It works fine, but if the result from the query is not found then the drop-down list just shrinks and doesn't say anything.
I want it to say something like: "Name not found". I've searched everywhere but I can't seem to find the way.
This is my code:
<?php
if ( $myquery = $mysqli->prepare("SELECT name, idname FROM db WHERE
name LIKE '%".$name."%'") ) {
$myquery->execute();
$myquery->store_result();
$myquery->bind_result( $nompac, $idpac ) ;
}
<form name="form1" method="post" action="example.php">
<table >
<tr>
<td>Name: </td>
<td>
<select name="chosen_name">
<?php
while ( $myquery->fetch() ) {
echo "<strong><option value=".$idpac.">".$nompac."</option></strong>";
}
?>
</select>
</td>
<td><input type="submit" name="Submit" value="Go" class="button"/></td>
</tr>
</table>
</form>
I would like to add an IF statement, saying something like "if $myquery didn't find any results, then $nompac ="name not found". So I wrote this right after the WHILE statement:
if ( $nompac = "" ) {
$nompac = "Name not found";
$idpac = "0";
}
But it just ignores the code as if I didn't write anything :(
Ok I added the code as suggested by Mister Melancholy. Now looks like this:
<form name="form1" method="post" action="example.php">
<table >
<tr>
<td>Name: </td>
<td>
<select name="chosen_name">
<?php
if ( empty( $myquery ) ) {
echo "<strong><option value=''>Name not found</option></strong>";
} else {
while ( $myquery->fetch() ) {
echo "<strong><option value=".$idpac.">".$nompac."</option></strong>";
}
}
?>
</select>
</td>
<td><input type="submit" name="Submit" value="Go" class="button"/></td>
</tr>
</table>
</form>
But still doesn't work if the query doesn't find the name. What am I doing wrong? :-s
I added !empty instead of empty, and I was very happy it seemed to work but it turned out to be that even though the query founded the right name, it echoed "Name not found" every time, so back to square one :(
You need a way to tell if $myquery is empty before you begin your while loop. Something like this should do the trick:
if ( empty( $myquery ) ) {
echo "<strong><option value=''>Name not found</option></strong>";
} else {
while ( $myquery->fetch() ) {
echo "<strong><option value='".$idpac."'>".$nompac."</option></strong>";
}
}
Since I had no further answers in here, I had to ask on another forum and they came up with the solution!
Just to let you know, I used:
if ( $myquery->num_rows==0 ) {
and this works like a charm!
Hi im running into this error and i just cant seem to see the problem so any ideas, a fresh set of eyes might help.
Full 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 'desc='ittititi', price='22', img='img.png'' at line 1
<?php
// Include MySQL class
require_once('../inc/mysql.php');
// Include database connection
require_once('../inc/global.inc.php');
// Include functions
require_once('../inc/functions.inc.php');
// Start the session
session_start();
?>
<?php
// try to create a new record from the submission
$genre = mysql_real_escape_string($_REQUEST['genre']);
$title = mysql_real_escape_string($_REQUEST['title']);
$desc = mysql_real_escape_string($_REQUEST['desc']);
$price = mysql_real_escape_string($_REQUEST['price']);
$img= mysql_real_escape_string($_REQUEST['img']);
if (!empty($genre) && !empty($title) && !empty($desc) && !empty($price) && !empty($img)) {
// here we define the SQL command
$query = "SELECT * FROM books WHERE title='$title'";
// submit the query to the database
$res=mysql_query($query);
// make sure it worked!
if (!$res) {
mysql_error();
exit;
}
// find out how many records we got
$num = mysql_numrows($res);
if ($num>0) {
echo "<h3>That book title is already taken</h3>\n";
exit;
}
// Create the record
$query = "INSERT INTO books SET genre='$genre', title='$title', desc='$desc', price='$price', img='$img'";
$res = mysql_query($query)or die(mysql_error());
if (! $res) {
echo mysql_error();
exit;
} else {
echo "<h3>Book Created</h3>\n";
echo $_SESSION['title']=$title;
}
}
?>
<form name="newbook" method="post">
<table border=0>
<tr>
<td>Genre:</td>
<td><input type=text name='genre'></td>
</tr>
<tr>
<td>Title:</td>
<td><input type=text name='title'></td>
</tr>
<tr>
<td>Description:</td>
<td><input type=text name='desc'></td>
</tr>
<tr>
<td>Price:</td>
<td><input type=number name='price'></td>
</tr>
<tr>
<td>Image:</td>
<td><input type=text name='img'></td>
</tr>
<tr>
<td colspan=2>
<input type=submit value="Create my account">
</td>
</tr>
</table>
</form>
You need to escape reserved words in MySQL like desc with backticks
INSERT INTO books
SET genre = '$genre', title = '$title', `desc` = '$desc'
^----^-----------------here
desc is reserved keyword for mysql
use it like that
`desc`
this must ne your query
$query = "INSERT INTO books SET genre='$genre', title='$title', `desc`='$desc', price='$price', img='$img'";
Don't use desc as a column name; it is a keyword. If you use it as a column name, you have to quote it.