Binding in php with postgres - php

I have problem with bindings, I want to insert name or surname in label Pisatelj as keyword to search for this author,
I want also do the same way if I insert keyword for Naslov(=Title of book)
please correct my code
I have this code in php with postgres:
function get_knjige_sql ( )
{
global $CRUD;
$dbh = $CRUD['dbh'];
$str_query = '';
if(isset($_POST['Knaslov'])){
$str_query = addslashes($_POST['Knaslov']);
}
if(isset($_POST['Ppriimek'])){
$str_query = addslashes($_POST['Ppriimek']);
}
$query = " SELECT * FROM knjiga, pisatelj, zaloga WHERE (knjiga.naslov ILIKE '?' OR CONCAT(pisatelj.ime, ' ', pisatelj.priimek) ILIKE '?' ) AND knjiga.p_id = pisatelj.p_id AND knjiga.k_id = zaloga.k_id AND zaloga.prodana = false ";
if($sth)
$sth->bindValue(':Knaslov', $Knaslov, PDO::PARAM_STR);
$sth->bindValue(':Ppriimek', $Ppriimek, PDO::PARAM_STR);
if($sth)
$sth->execute();
else error('get_knjige_sql: select prepare returned no statement handle');
$err = $sth->errorInfo();
if($err[0] != 0) error( $err[2] );
return($sth);
}
main.php:
<!-- main html file for CRUD (php version) -->
<?php echo $CRUD["MESSAGES"] ?><?php echo $CRUD["ERRORS"] ?>
<div class="form">
<form action="<?php echo $CRUD["SELF"] ?>" method="post" name="knjiga">
<p class="subheading"><?php echo $CRUD["FORM_HEAD"] ?></p>
<table class="form">
<tr>
<td><p class="Afield"> Naslov:</p></td>
<td><input class="Afield" type="text" name="Knaslov" value="<?php echo $CRUD["Knaslov"] ?>"> </td>
</tr>
<tr>
<td><p class="Afield"> Isbn:</p></td>
<td><input class="Afield" type="text" name="kisbn" value="<?php echo $CRUD["Kisbn"] ?>"> </td>
</tr>
<tr>
<td><p class="Afield"> Cena:</p></td>
<td><input class="Afield" type="text" name="Kcena" value="<?php echo $CRUD["Kcena"] ?>"> </td>
</tr>
<tr>
<td><p class="Afield"> Pisatelj:</p></td>
<td><input class="Afield" type="text" name="Ppriimek" value="<?php echo $CRUD["Pime"] ?><?php echo $CRUD["Ppriimek"] ?>"> </td>
</tr>
<tr class="buttons"><td colspan="2">
<p class="buttons">
<?php echo $CRUD["BUTTONS"] ?><?php echo $CRUD["HIDDENS"] ?>
</p>
</td></tr>
</table>
</form>
</div>
<?php echo $CRUD["PRECONTENT"] ?><?php echo $CRUD["CONTENT"] ?><?php echo $CRUD["POSTCONTENT"] ?>

Related

PHP Array and foreach Combination calculation

In a quiz app, I am taking user answer using a form. I am retrieving correct answer from database table. I want to compare the correct answer with the user's answer and count how many answer was right and how many answer was wrong.
Here is my form:
<form id="question" class="" action="quiz_ans.php" method="post">
<table id="quiz-question" align="center" class="row-border compact order-column stripe">
<input class="form-control" type="hidden" name="NumberofQuestions" id="NumberofQuestions" value="<?php echo $NumberofQuestions; ?>">
<thead>
<?php
if($QuizQuestions) {
$i=1;
foreach($QuizQuestions as $row):
?>
<tr>
<th><?php echo $i; ?>. <?php echo $row->Question; ?>
<br>
<?php if(isset($row->Screenshot)) { ?>
<img src="<?php echo htmlspecialchars($row->Screenshot); ?>" alt="test" height="300" width="980">
<?php } ?>
</th>
</tr>
</thead>
<tbody>
<?php if(isset($row->Option1)) { ?>
<tr class="info">
<td><input type="radio" name="AnswerId[<?php echo $row->Id; ?>]" value="0"><?php echo $row->Option1; ?></td>
</tr>
<?php } ?>
<?php if(isset($row->Option2)) { ?>
<tr class="info">
<td><input type="radio" name="AnswerId[<?php echo $row->Id; ?>]" value="1"> <?php echo $row->Option2; ?></td>
</tr>
<?php } ?>
<?php if(isset($row->Option3)) { ?>
<tr>
<td><input type="radio" name="AnswerId[<?php echo $row->Id; ?>]" value="2"> <?php echo $row->Option3; ?></td>
</tr>
<?php } ?>
<?php if(isset($row->Option4)) { ?>
<tr>
<td><input type="radio" name="AnswerId[<?php echo $row->Id; ?>]" value="3"><?php echo $row->Option4; ?></td>
</tr>
<?php } ?>
<tr>
<td><label for="AnswerReason">Why?</label><input class="form-control" type="text" name="AnswerReason[]" id="AnswerReason" value=""></td>
</tr>
<?php if(isset($row->Id)) { ?>
<tr>
<td><input class="form-control" type="hidden" name="QuestionId[]" id="QuestionId" value="<?php echo $row->Id; ?>"></td>
</tr>
<?php } ?>
</tbody>
<?php
$i++;
endforeach;
}
?>
</table>
<br>
<input type="submit" name="submit" value="Submit" class="btn btn-success">
</form>
I am getting the user answer from the form submit:
$NumberofQuestions = $_POST['NumberofQuestions'];
$ans = implode("", $_POST['AnswerId']);
I am retreiving the correct answer from the database table:
try {
$sql = "CALL spQuizAnswers(:quiz_num)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':quiz_num', $quiz_num, PDO::PARAM_STR, 50);
$stmt->execute();
$QuizAns=$stmt->fetchAll();
$stmt->closeCursor();
} catch (PDOException $e) {
die("Error occurred:" . $e->getMessage());
}
I am comparing the user's answer and the correct answer:
for ($i=0; $i<$NumberofQuestions; $i++) {
if($QuizAns) {
foreach($QuizAns as $row):
if($row->CorrectAns == $ans[$i]){
$right++;
} elseif($ans[$i] == 4){
$not_answered++;
} else {
$wrong++;
}
endforeach;
}
}
$CorrectAnswer = $right;
$WrongAnswer = $wrong;
$NotAnswered = $not_answered;
$TotalQuestion = $right+$wrong+$not_answered;
It does not give correct calculation. For 5 questions it gives $TotalQuestion=25.
How can I achieve the correct calculation? Any help would be much appreciated.

Need to Insert Multiple Data by selecting Checkboxes

I need to Insert data to the DB using the form given below
<form action="OtherEventPayment.php" id="frmSignIn" method="post">
<input type="hidden" name="online_id" value="<?php echo $lid; ?>" >
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Item</th>
<th>No. of Participants</th>
<th>Tick the Items</th>
</tr>
</thead>
<tbody>
<tbody>
<?php
$sn ="1";
$id = $oth_event_id;
$stmt1 = $DB_con->prepare('SELECT * FROM oth_events_details
LEFT JOIN oth_event_category ON (oth_events_details.oth_evcat_id=oth_event_category.oth_evcat_id)
WHERE oth_event_id =:uid ORDER BY oth_event_det_id DESC');
$stmt1->execute(array(':uid'=>$id));
$stmt1->execute();
if($stmt1->rowCount() > 0)
{
while($row1=$stmt1->fetch(PDO::FETCH_ASSOC))
{
extract($row1);
?>
<tr>
<td><?php echo $sn; ?></td>
<td>
<?php echo $row1['oth_category'];?> -
<?php
$group =$row1['oth_catgroup_type'];
if ($group=="S")
{
echo "Single";
}
elseif ($group=="D")
{
echo "Doubles";
}
else{
echo "Group";
}
?>
</td>
<td><?php echo $row1['participntno']; ?></td>
<td>
<b>
</b>
<input type="checkbox" name="chk[<?php echo $row1['oth_event_det_id'];?>]" value="<?php echo $row1['oth_event_det_id'];?>" id="chk[<?php echo $row1['oth_event_det_id'];?>]" />
Fees:- <?php echo $row1['oth_ev_fee'];?>
</td>
</tr>
<?php $sn++; ?>
<?php
}
}
else
{
?>
<div class="col-xs-12">
<div class="alert alert-warning">
<span class="glyphicon glyphicon-info-sign"></span> No Data Found ...
</div>
</div>
<?php
}
?>
</tbody>
</table>
<div class="col-md-6">
<input type="submit" name="selectItems" value="Submit & Proceed" class="btn btn-primary pull-right mb-xl" data-loading-text="Loading...">
</div>
</div>
<?php echo $sn1=$sn-1; ?>
</form>
in the OtherEventPayment.php i have written the code. But not working . How to Insert data correctly to DB
<?php
require_once 'dbconfig.php';
if(isset($_POST['selectItems']))
{
echo array[] = $_POST['chk[]'];
echo $oth_online_id= $_POST['online_id'];
if($oth_event_detid != ""){
for($i=0;$i<sizeof($oth_event_detid);$i++)
{
// oth_event_det_id,oth_online_id
$stmt = $DB_con->prepare('INSERT INTO othevents_itemsonline(oth_event_det_id,oth_online_id) VALUES( :oth_event_det_id, :oth_online_id)');
$stmt->bindParam(':oth_event_det_id',$oth_event_det_id);
$stmt->bindParam(':oth_online_id',$oth_online_id);
if($stmt->execute())
{
$lastonlineid= $DB_con->lastInsertId();
$successMSG = "Thank you For Registering with us . Please select the items to be participating...";
// header("refresh:0;OtherEventsOnlineRegistrationThankyou.php"); /
}
else
{
$errMSG = "error while registering....";
} } }
}
?>
Name should be same for input field. Use following code:
<input type="checkbox" name="chk[]" value="<?php echo $row1['oth_event_det_id'];?>" id="chk[<?php echo $row1['oth_event_det_id'];?>]" />
Fees:- <?php echo $row1['oth_ev_fee'];?>
You can see name. Hopefully it will be clear enough
Just change the value of you checkboxes and the value it represents but keep the name same with the others, yet it should have a name with []
<input type="checkbox" id="chk<?php echo $row1['oth_event_det_id'];?>" name="chk[]" value="<?php echo $row1['oth_event_det_id'];?>">
<label for="chk<?php echo $row1['oth_event_det_id'];?>"><?php echo $row1['oth_event_det_id'];?></label>
having a name chk[] like this will send and serve as an array in your get or post-function so loop it on controller or function that will add it in the DB
upon inserting it,
$data = $_GET['chk']; //this is in array form
foreach($data as $chk){
//insert code here
}

How do I build, save and retrieve wp_options from a single form in a plugin development

I'm working in a simple WP plugin, my first one, and I don't know the right way to handle wp_options table using update_options function. I have this code in my plugin:
<form name="frequent_traveler_form" method="post" action="<?php echo str_replace('%7E', '~', $_SERVER['REQUEST_URI']); ?>">
<input type="hidden" name="frequent_traveler_hidden" value="Y">
<?php echo "<h4>" . __('Common Settings') . "</h4>"; ?>
<p><?php _e("Default Conversion Value: "); ?><input type="text" name="ft_default" value="<?php echo $ft_default; ?>" size="5"></p>
<p><?php _e("From Date: "); ?><input type="text" id="frequent_traveler_from_date" name="frequent_traveler_from_date" value="<?php echo $frequent_traveler_from_date ?>" class="datepicker" /></p>
<p><?php _e("To Date: "); ?><input type="text" id="frequent_traveler_to_date" name="frequent_traveler_to_date" value="<?php echo $frequent_traveler_to_date; ?>" class="datepicker" /></p>
<p class="submit">
<input type="submit" name="Submit" value="<?php _e('Save') ?>" />
</p>
</form>
What I need to do is "always", add new values to some config option at wp_options so any time I load the plugin config I should able to create as many options as I want using the same form. This is what I did and I'm not tested yet:
if ($_POST['ft_default'] && $_POST['frequent_traveler_from_date'] && $_POST['frequent_traveler_to_date'] && $_POST['ft_default'] != "" && $_POST['frequent_traveler_from_date'] != "" && $_POST['frequent_traveler_to_date'] != "") {
$ft_options = array(
'ft_default' => $_POST['ft_default'],
'frequent_traveler_from_date' => $_POST['frequent_traveler_from_date'],
'frequent_traveler_to_date' => $_POST['frequent_traveler_to_date']
);
update_option('ft_options', $ft_options);
}
Is that right? How I do that?
UPDATE
This is what I have in frequent-traveler.php (the main plugin file) among other functions:
function frequent_traveler_admin_actions()
{
add_options_page("Frequent Traveler Configuration", "Frequent Traveler Config", 'manage_options', "ftconfig", "frequent_traveler_admin");
}
add_action('admin_menu', 'frequent_traveler_admin_actions');
function frequent_traveler_admin()
{
include('ft_admin.php');
}
And this is the code at ft_admin.php :
<?php
wp_enqueue_script('jquery-ui-datepicker');
wp_enqueue_style('jquery-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css');
?>
<div class="wrap">
<?php echo "<h2>" . __('Frequent Traveler Configuration') . "</h2>"; ?>
<form name="frequent_traveler_form" method="post" action="<?php echo str_replace('%7E', '~', $_SERVER['REQUEST_URI']); ?>">
<input type="hidden" name="frequent_traveler_hidden" value="Y">
<?php echo "<h4>" . __('Common Settings') . "</h4>"; ?>
<p><?php _e("Default Conversion Value: "); ?><input type="text" name="ft_default" value="<?php echo $ft_default; ?>" size="5">
<?php _e("From Date: "); ?><input type="text" id="frequent_traveler_from_date" name="frequent_traveler_from_date" value="<?php echo $frequent_traveler_from_date ?>" class="datepicker" />
<?php _e("To Date: "); ?><input type="text" id="frequent_traveler_to_date" name="frequent_traveler_to_date" value="<?php echo $frequent_traveler_to_date; ?>" class="datepicker" /></p>
<p class="submit">
<input type="submit" name="Submit" value="<?php _e('Save') ?>" />
</p>
</form>
</div>
<div class="wrap">
<table class="widefat">
<thead>
<tr>
<td>Conversion Value</td>
<td>From Date</td>
<td>To Date</td>
</tr>
</thead>
<tfoot>
<tr>
<td>Conversion Value</td>
<td>From Date</td>
<td>To Date</td>
</tr>
</tfoot>
<tbody>
<?php
global $wpdb;
if ($_POST['ft_default'] && $_POST['frequent_traveler_from_date'] && $_POST['frequent_traveler_to_date'] && $_POST['ft_default'] != "" && $_POST['frequent_traveler_from_date'] != "" && $_POST['frequent_traveler_to_date'] != "") {
$ft_options = array(
'ft_default' => $_POST['ft_default'],
'frequent_traveler_from_date' => $_POST['frequent_traveler_from_date'],
'frequent_traveler_to_date' => $_POST['frequent_traveler_to_date']
);
update_option('ft_options', $ft_options);
}
$config_options = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "options");
foreach ($config_options as $cop) {
?>
<tr>
<td><?php echo $cop->ft_default ?></td>
<td><?php echo $cop->from_date ?></td>
<td><?php echo $cop->to_date ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<script>
jQuery(document).ready(function() {
jQuery('.datepicker').datepicker({
dateFormat: 'dd/mm/yy'
});
});
</script>
I tried this gist code by writing the code at ft_admin.php top just below wp_enqueue_script and wp_enqueue_style calls and this is what doesn't work, what I did wrong?
UPDATE 2
I've added this code to ft_admin.php file:
<?php
wp_enqueue_script('jquery-ui-datepicker');
wp_enqueue_style('jquery-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css');
add_action('admin_init', 'add_meta_boxes', 1);
function add_meta_boxes()
{
add_meta_box('repeatable-fields', 'Promotions', 'repeatable_meta_box_display');
}
function repeatable_meta_box_display()
{
echo "I'm here";
}
And nothing is showed, what is wrong in that code?

SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= '{search_term}''

I can't do the live search table thing. Can someone help me please?
Here is my code. I want to show only the data I've search.........................................................................................................................................................................................................................................................................
<?php
//include the connection file
include "conn.php";
$sql = "SELECT * FROM tblreservation";
if (isset($_POST['search'])) {
$search_term = mysql_real_escape_string($_POST['search_box']);
$sql .= "WHERE Name = '{search_term}'";
}
$query = mysql_query($sql) or die(mysql_error());
?>
<form name="search_form" method="POST" action="trys.php" align="center">
Search: <input type="text" name="search_box" value="" />
<input type="submit" name="search" value="Search the table...">
</form>
<table width="70%" cellpadding="5" cellspace="5">
<tr>
<td>ID</td>
<td>Name</td>
<td>Email</td>
<td>Packages</td>
<td><select name="Packages" class="fieldsize">
<option value="">select package</option>
<option value="budget" <?php if($valid_Packages=='budget') echo "selected='selected'";?>>Budget</option>
<option value="standard" <?php if($valid_Packages=='standard') echo "selected='selected'";?>>Standard</option>
<option value="super" <?php if($valid_Packages=='super') echo "selected='selected'";?>>Super</option>
<option value="mega" <?php if($valid_Packages=='mega') echo "selected='selected'";?>>Mega</option>
</select>
<span class="err"><?php echo $error["Packages"];?></span></td>
</tr>
<td>Contactno</td>
<td>Gender</td>
<td><input type="radio" name="gender" value="male" <?php if($valid_gender=='male') echo "checked='checked'";?> />
Male
<input type="radio" name="gender" value="female" <?php if($valid_gender=='female') echo "checked='checked'";?>/>
Female <span class="err"><?php echo $error["gender"];?></span></td>
<td>file</td>
<td><input type="file" name="file" value="upload" />
<span class="err"><?php echo $error["file"];?></span></td>
<td>Address</td>
</tr>
<?php while ($row = mysql_fetch_array($query)) { ?>
<td><?php echo $row['id']; ?> </td>
<td><?php echo $row['Name']; ?> </td>
<td><?php echo $row['Email']; ?> </td>
<td><?php echo $row['Packages']; ?> </td>
<td><?php echo $row['Contactno']; ?> </td>
<td><?php echo $row['Gender']; ?> </td>
<td><?php echo $row['file']; ?> </td>
<td><?php echo $row['Address']; ?> </td>
</tr>
<?php } ?>
</table>
You are missing a $ and a space in this line:
$sql .= "WHERE Name = '{search_term}'";
The correct line should be as follows:
$sql .= " WHERE Name = '{$search_term}' ";
The SQL statement you are currently generating is exactly this:
SELECT * FROM tblreservationWHERE Name = '{search_term}'
Additionally, I would recommend checking for the existence of $_POST['search_box'] rather than $_POST['search'] in your if-statement and that it actually has a value before appending it as this is what you actually want to use in your query:
if (isset($_POST['search_box']) && $_POST['search_box']) {
$search_term = mysql_real_escape_string($_POST['search_box']);
$sql .= " WHERE Name = '{$search_term}' ";
}

Php search not working 100%

I have the following search script,but its not working 100%. My goal is to have 4 textbox to search for records in a table called users and only after the search button is submitted the table must be display, but at the at the moment when the page loads the table header is being displayed secondly if search for a record it display all my records that is in my table and not the just the record that I'm searching for
Any suggestion will be very helpfull
<form id="form1" name="form1" method="post" action="View.php">
<label for="from">First Name</label>
<input name="first" type="text" id="first" size="10" value="<?php echo $_REQUEST["first"]; ?>" />
<label for="to">Last Name</label>
<input name="last" type="text" id="last" size="10" value="<?php echo $_REQUEST["last"]; ?>"/>
<label>Email:</label>
<input type="text" name="email" id="string" value="<?php echo stripcslashes($_REQUEST["email"]); ?>" />
<label>Company</label>
<select name="company">
<option value="">--</option>
<?php
include("config.php");
$sql = "SELECT * FROM users GROUP BY company ORDER BY company";
$sql_result = mysql_query ($sql, $dbConn ) or die ('request "Could not execute SQL query" '.$sql);
while ($row = mysql_fetch_assoc($sql_result)) {
echo "<option value='".$row["company"]."'".($row["company"]==$_REQUEST["company"] ? " selected" : "").">".$row["company"]."</option>";
}
?>
</select>
<input type="submit" name="button" id="button" value="Filter" />
</label>
<a href="View.php">
reset</a>
</form>
<br /><br />
<table width="700" border="1" cellspacing="0" cellpadding="4">
<tr>
<td width="90" bgcolor="#CCCCCC"><strong>First Name</strong></td>
<td width="95" bgcolor="#CCCCCC"><strong>Last Name</strong></td>
<td width="159" bgcolor="#CCCCCC"><strong>Company</strong></td>
<td width="191" bgcolor="#CCCCCC"><strong>Email</strong></td>
<td width="113" bgcolor="#CCCCCC"><strong>Contact Number</strong></td>
<td width="113" bgcolor="#CCCCCC"><strong>Position</strong></td>
<td width="113" bgcolor="#CCCCCC"><strong>How do you know the person</strong></td>
<td width="113" bgcolor="#CCCCCC"><strong>Comment</strong></td>
</tr>
<?php
if($_POST["button"])
{
if ($_REQUEST["first"]<>'') {
$search_first = " AND fname LIKE '%".mysql_real_escape_string($_REQUEST["fname"])."'";
}
if ($_REQUEST["last"]<>'') {
$search_last = " AND lname='".mysql_real_escape_string($_REQUEST["last"])."'";
}
if ($_REQUEST["email"]<>'') {
$search_email = " AND email='".mysql_real_escape_string($_REQUEST["email"])."'";
}
if ($_REQUEST["company"]<>'') {
$search_company = " AND company='".mysql_real_escape_string($_REQUEST["company"])."'";
}
else {
$sql = "SELECT * FROM users WHERE id>0".$search_first.$search_last.$search_email.$search_company;
}
$sql_result = mysql_query ($sql, $dbConn) or die ('request "Could not execute SQL query" '.$sql);
if (mysql_num_rows($sql_result)>0)
{
while ($row = mysql_fetch_assoc($sql_result))
{
?>
<tr>
<td><?php echo $row["fname"]; ?></td>
<td><?php echo $row["lname"]; ?></td>
<td><?php echo $row["company"]; ?></td>
<td><?php echo $row["email"]; ?></td>
<td><?php echo $row["contactnumber"]; ?></td>
<td><?php echo $row["position"]; ?></td>
<td><?php echo $row["howdoyouknow"]; ?></td>
<td><?php echo $row["comment"]; ?></td>
</tr>
<?php
}
} else {
?>
<tr><td colspan="5">No results found.</td>
<?php
}
}
?>
</table>
Please remove else condition,
else {
$sql = "SELECT * FROM users WHERE id>0".$search_first.$search_last.$search_email.$search_company;
}
use like below i.e without else tag
$sql = "SELECT * FROM users WHERE id>0".$search_first.$search_last.$search_email.$search_company;
How would you expect that this:
else {
$sql = "SELECT * FROM users WHERE id>0".$search_first.$search_last.$search_email.$search_company;
}
would even work when you declare the $search_company in the IF
Also I do think the else wouldn't even be needed in your case since the
$sql = "SELECT * FROM users WHERE id>0".$search_first.$search_last.$search_email.$search_company;
wouldn't work without executing the IF statements

Categories