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!
Related
I'm doing a simple chat and everything is working well, but everybody can flood the chat sending how many messages they want to...
PHP:
<div id="chat_panel"></div>
<br />
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td><input type="text" autocomplete="off" maxlength="50" placeholder="Type your message..." id="message" size="87%" checked="yes"></td>
<td><input type="button" id="message" onClick="sendMessage()" value="Send"></td>
</tr>
</table>
JAVASCRIPT:
function sendMessage() {
var message = $('#message').val();
$.post('postMessage.php', { message: message } , function() { } );
}
postMessage.PHP:
session_start();
include ("chats/connect.php");
$timname = $_SESSION['username'];
if (isset($_POST['message'])) {
mysql_query("INSERT INTO chat VALUES ('', '".$timname."', '".$_POST['message']."', '".time()."', NOW(), '');");
}
I need to set a interval to send each message like 3 seconds...
Any information will be helpful!
Try Jquery to refresh specific page. Try something like below code
setup.js
var autorefresh=setInterval(
function()
{
$("query.php").load('query.php');
e.preventDefault();
},3000);
query.php
session_start();
include ("chats/connect.php");
$timname = $_SESSION['username'];
if (isset($_POST['message'])) {
mysql_query("INSERT INTO chat VALUES ('', '".$timname."', '".$_POST['message']."', '".time()."', NOW(), '');");
}
Here 3000 in setup.js is time in miliseconds you want to refresh.
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.
I'm creating a simple contact form within my ZF application. It doesn't feel like it's worth the trouble to manipulate decorators for only a few form elements.
My Question is: am I able to still use Zend Form Filters on elements that are not created with Zend Form:
For Example:
The Form:
<!-- Standard HTML - not generated with ZF -->
<form id="contact-form" method="post" action="/contact/submit">
<input type="text" name="name" />
<input type="email" name="email" />
<input type="submit" name="submit" />
</form>
The Controller:
public function submitAction()
{
$params = $this->_request->getParams();
//Am I able to apply filters/validators to the data I get from the request?
//What is the best way to handle this?
}
I took a look at this (the answer from Darcy Hastings) - and it seems like it would work, it just feels a bit hacky.
Any and all advice appreciated.
Thanks,
Ken
yes, you can use Zend_Filter_Input, here is an example of how to set it up.
//set filters and validators for Zend_Filter_Input
$filters = array(
'trackid' => array('HtmlEntities', 'StripTags')
);
$validators = array(
'trackid' => array('NotEmpty', 'Int')
);
//assign Input
$input = new Zend_Filter_Input($filters, $validators);
$input->setData($this->getRequest()->getParams());
//check input is valid and is specifically posted as 'Delete Selected'
if ($input->isValid()) {
also you may consider using the viewscript decorator to render a Zend Form, The control is absolute (or almost).:
//in your controller action
public function indexAction() {
//a normally constructed Zend_Form
$form = new Member_Form_Bid();
$form->setAction('/member/bid/preference');
//attach a partial to display the form, this is the decrator
$form->setDecorators(array(
array('ViewScript', array('viewScript' => '_bidForm.phtml'))
));
$this->view->form = $form;
//the view
<?php echo $this->form?>
//the partial
//use a normal Zend_Form and display only the parts you want
//processing in an action is done like any other Zend_Form
form action="<?php echo $this->element->getAction() ?>"
method="<?php echo $this->element->getMethod() ?>">
<table id="sort">
<tr>
<th colspan="2">Sort By Shift</th>
<th colspan="2">Sort By Days Off</th>
<th colspan="2">Sort By Bid Location</th>
</tr>
<tr></tr>
<tr>
<td class="label"><?php echo $this->element->shift->renderLabel() ?></td>
<td class="element"><?php echo $this->element->shift->renderViewHelper() ?></td>
<td class="label"><?php echo $this->element->weekend->renderLabel() ?></td>
<td class="element"><?php echo $this->element->weekend->renderViewHelper() ?></td>
<td class="label"><?php echo $this->element->bidlocation->renderLabel() ?></td>
<td class="element"><?php echo $this->element->bidlocation->renderViewHelper() ?></td>
</tr>
<tr></tr>
<tr>
<td colspan="6" style="text-align: center"><?php echo $this->element->submit ?></td>
</tr>
</table>
</form>
Yes, you definitely can use Zend_Form on self-rendered forms.
You can do this in two ways:
Use a Zend_Form object, but don't render it. You create a Zend_Form instance as usual, with all the elements named correctly and attach validators and filters as per normal. In your action, you can then check the form's isValid() and use getValues() to ensure that you collect the filtered data.
The second option is to use Zend_Filter_Input which is a chain of validators and filters. You set up your validators and filters at construction and then call setData to populate the filter with the information from the request. Again, you have isValid() to test and then you use getUnescaped() to retrieve the data. The manual page has more details.
I am trying to create a page in my WordPress Admin Area that displays excerpts of posts and various custom field meta in a table-style layout.
If this were a front-end WordPress Template, I could do this very easily using a WordPress Loop and Query, however, I am not so sure how I would go about doing this on a page in the admin area.
Would it be the same, or would I need to use a completely new method? If so, could someone please provide a working example of how I would do this?
The admin page will be created using an included file within my functions.php - or at least that is the plan at the moment, so I just need help in figuring out how to pull the WordPress Excerpts and Post Meta.
you can use the WP_Query object everytime after WordPress is initialized, so if you like you can even make thousands of nested queries in den WordPress backend if you want to do this.
This is the way to go:
Create an action to add your backend page - write a Plugin or put it into your functions.php
Setup the Menu Page - the code is an example for a full backend administration Page of your Theme
Include your queries using the WP_Query object - optionally make database queries directly (http://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query). Possibly use the "widefat" class of WordPress, for pretty formatting.
Make sure that your changes are saved correctly
add_action('admin_menu', 'cis_create_menu');
function cis_create_menu() {
//create new top-level menu
add_menu_page(__('Theme Settings Page',TEXTDOMAIN),__('Configure Theme',TEXTDOMAIN), 'administrator', __FILE__, 'cis_settings_page', '');
//call register settings function
add_action('admin_init','cis_register_settings');
}
function cis_register_settings() {
register_setting('cis-settings-group','cis_options_1','cis_validate_settings');
}
function cis_settings_page() {
// All Text field settings
$op_fields = array(
array(__('Label 1','textdomain'),"Description 1")
);
?>
<div class="wrap">
<h2><?php echo THEME_NAME; _e(": Settings",TEXTDOMAIN); ?></h2>
<?php
settings_errors();
?>
<form method="post" action="options.php">
<?php
settings_fields( 'cis-settings-group' );
$options = get_option('cis_options_1');
?>
<h3><?php _e('General','textdomain'); ?></h3>
<table class="widefat">
<thead>
<tr valign="top">
<th scope="row"><?php _e('Setting','ultrasimpleshop'); ?></th>
<th scope="row"><?php _e('Value','ultrasimpleshop'); ?></th>
<th scope="row"><?php _e('Description','ultrasimpleshop'); ?></th>
<th scope="row"><?php _e('ID','ultrasimpleshop'); ?></th>
</tr>
</thead>
<tbody>
<?php
// the text-settings we define fast display
$i=1;
foreach($op_fields as $op) {?>
<tr valign="top">
<td><label for="cis_oset_<?php echo $i; ?>"><?php echo $op[0]; ?></label></td>
<td><input size="100" id="cis_oset_<?php echo $i; ?>" name="cis_options_1[cis_oset_<?php echo $i; ?>]" type="text" value="<?php echo esc_attr($options['cis_oset_'.$i]);?>" /></td>
<td class="description"><?php echo $op[1]; ?></td>
<td class="description"><?php echo $i; ?></td>
</tr>
<?php
$i++;
} ?>
</tbody>
</table>
<p class="submit">
<input type="submit" class="button-primary" value="<?php _e('Save Changes',TEXTDOMAIN) ?>" />
</p>
</form>
</div>
<?php }
// Validate the user input - if nothing to validate, just return
function cis_validate_settings( $input ) {
$valid = array();
$i= 1;
while(isset($input['cis_oset_'.$i])) {
$valid['cis_oset_'.$i] = $input['cis_oset_'.$i];
$i++;
}
$cis_additional_settings = get_option('cis_options_1');
foreach($input as $ikey => $ivalue) {
if($ivalue != $valid[$ikey]) {
add_settings_error(
$ikey, // setting title
"cis_oset_".$ikey, // error ID
str_replace("%s",$ikey,__('Invalid Setting in Settings Area ("%s"). The value was not changed.',TEXTDOMAIN)), // error message
'error' // type of message
);
$valid[$ikey] = $cis_additional_settings[$ikey];
}
}
return $valid;
}
outside the loop you would need to use
$post->post_excerpt
or try this
function get_the_excerpt_here($post_id)
{
global $wpdb;
$query = "SELECT post_excerpt FROM $wpdb->posts WHERE ID = $post_id LIMIT 1";
$result = $wpdb->get_results($query, ARRAY_A);
return $result[0]['post_excerpt'];
}
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.