Ajax Pagination not working properly - php

<?php include("config.php");
error_reporting(E_ALL); ini_set('display_errors', 1);
$results = mysqli_query($con,"SELECT COUNT(name) FROM user_tbl ");
$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
?>
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("fetch_pages.php"); //initial page number to load
$(".pagination").bootpag({
total: <?php echo $pages; ?>,
page: 1,
maxVisible: 5
}).on("page", function(e, num){
e.preventDefault();
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
$("#results").load("fetch_pages.php", {'page':num});
});
});
</script>
<body>
<div id="serch">
<form method="post" enctype="multipart/form-data">
<label>SEARCH BY NAME:</label>
<input type="text" name="name" class="name" >
<input type="submit" name="submit" class="sbmtt" value="SEARCH" />
</form>
</div>
</table>
<div class="res">
<div class="navi">
<div id="results"></div>
<div class="pagination"></div>
</div>
</div>
</body>
fetch_pages.php:
<?php
include("config.php"); //include config file
if(isset($_POST["page"])) {
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
if(!is_numeric($page_number)) {
//incase of invalid page number
die('Invalid page number!');
}
} else {
$page_number = 1;
}
//get current starting point of records
$position = (($page_number-1) * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($con, "SELECT * FROM user_tbl WHERE name = 'aruna' ORDER BY id ASC LIMIT $position, $item_per_page");
//output results from database
echo '<ul class="page_result">';
while($row = mysqli_fetch_array($results)) {
echo 'Name: ' .$row['name'];
echo '<br /><br />Contact Number: ' .$row['cont'];
echo '<br /><br />Email ID: ' .$row['email'];
echo '<br /><br />View details';
echo "<br /><hr />";
}
echo '</ul>';
?>
Config.php:
<?php
$con = mysqli_connect("localhost","root","","mydb");
$item_per_page = 3;
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Here the result just shows in the div.. i want to fetch the result after the form get submitted .. i tried if(isset($_POST['submit'])) but not working.. and the search should be done by fetching the name from the html form not the way i ve given in fetch_pages.php like 'aruna' .. it should get fetched by the form data like $_POST['name'] .. i m really stuck here.. any help plzzz .. thanks in advance

You need to pass search form value. Below is the full updated code.
<?php include("config.php");
error_reporting(E_ALL); ini_set('display_errors', 1);
$name = "";
$where = "";
if(isset($_POST["name"])){
$name = $_POST["name"];
$where = " WHERE name = '".$name."' ";
}
$results = mysqli_query($con,"SELECT COUNT(name) FROM user_tbl $where");
$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
?>
<script type="text/javascript">
$(document).ready(function() {
var name = '<?php echo $name; ?>';
$("#results").load("fetch_pages.php", {'name':name}); //initial page number to load
$(".pagination").bootpag({
total: <?php echo $pages; ?>,
page: 1,
maxVisible: 5
}).on("page", function(e, num){
e.preventDefault();
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
$("#results").load("fetch_pages.php", {'page':num, 'name':name});
});
});
</script>
<body>
<div id="serch">
<form method="post" enctype="multipart/form-data">
<label>SEARCH BY NAME:</label>
<input type="text" name="name" class="name" value="<?php echo $name; ?>">
<input type="submit" name="submit" class="sbmtt" value="SEARCH" />
</form>
</div>
</table><div class="res">
<div class="navi">
<div id="results"></div>
<div class="pagination"></div>
</div> </div>
</body>
fetch_pages.php:
<?php
include("config.php"); //include config file
if(isset($_POST["page"])){
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
if(!is_numeric($page_number)){die('Invalid page number!');} //incase of invalid page number
}else{
$page_number = 1;
}
//get current starting point of records
$position = (($page_number-1) * $item_per_page);
$name = "";
$where = "";
if(isset($_POST["name"])){
$name = $_POST["name"];
$where = " WHERE name = '".$name."' ";
}
//Limit our results within a specified range.
$results = mysqli_query($con, "SELECT * FROM user_tbl $where ORDER BY id ASC LIMIT $position, $item_per_page");
//output results from database
echo '<ul class="page_result">';
while($row = mysqli_fetch_array($results))
{
echo 'Name: ' .$row['name'];
echo '<br /><br />Contact Number: ' .$row['cont'];
echo '<br /><br />Email ID: ' .$row['email'];
echo '<br /><br />View details';
echo "<br /><hr />";
}
echo '</ul>';
?>
Hope it will help.

Related

PHP SQL Change style of filtered data while still display all data

I hava a page with a list of data displayed from database table and a search bar.
When I filter the data by id, the searched data will be highlighted (background color change) but I need it to remain displaying the rest of data.
I managed to change the background color of searched data however if I search the data that is not in table, the Record not found not displayed.
<?php
$search_keyword = '';
if (isset($_POST['search'])) {
$search_keyword = $_POST['search'];
}
?>
<head></head>
<body>
<form name="searchForm" action="" method="POST">
<input type="text" id="search" name="search" placeholder="Enter Employee ID Search">
</form>
<?php
$sql_search = "";
if (!empty($search_keyword)) {
$sql_search = " WHERE id = '" . $search_keyword . "' ";
}
$sql1 = "SELECT id, name, address FROM employee";
$result = $conn->query($sql1);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
?>
<div class="row">
<div class="employee">
<?php
if ($row["id"] == $search_keyword) {
?>
<div class="red-bg">
<?php
} else {
?>
<div class="white-bg">
<?php
}
?>
<div class="col-md-2"><?php echo $row["id"] ?></div>
<div class="col-md-3"><?php echo $row["name"] ?></div>
<div class="col-md-5"><?php echo $row["address"] ?></div>
</div>
</div>
</div>
</div>
<?php
}
} else {
?>
<div class="row">
<div class="employee">
<div class="white-bg">
<?php echo "Record not found." ?>
</div>
</div>
</div>
<?php
}
?>
</body>
<script>
document.onkeydown = function(evt) {
var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
if (keyCode == 13) {
//your function call here
document.searchForm.submit();
}
}
</script>
If I include the search keyword in query, I can display the Record not found when searching for data not in table however if I search data that is in table will only display and highlight 1 data.
$sql1 = "SELECT id, name, address FROM employee ". $sql_search ."";
So how do I display all data and highlight searched data that is in table and only display Record not found when search for data that is not in table?
I have managed to highlight/bold the search data while still display all the other data and will display a message Record not found if the data is not in table.
<?php
include("database.php");
$search_keyword = '';
if (isset($_POST['search'])) {
$search_keyword = $_POST['search'];
}
?>
<head>
</head>
<body>
<form name="searchForm" action="" method="POST">
<input type="text" id="search" name="search" placeholder="Enter Employee ID Search">
</form>
<?php
//query for searching
$sql_search_keyword = "";
if (!empty($search_keyword)) {
$sql_search_keyword = " WHERE id = '" . $search_keyword . "' ";
$sql_want_search = "SELECT id, name, address FROM employee" . $sql_search_keyword;
$result_want_search = $conn->query($sql_want_search);
if ($result_want_search->num_rows > 0) {
while ($row_want_search = $result_want_search->fetch_assoc()) {
$searched_data = $row_want_search["id"];
//query for displaying all data - if match with search will bold
$sql_display_searched = "SELECT id, name, address FROM employee";
$result_display_searched = $conn->query($sql_display_searched);
if ($result_display_searched->num_rows > 0) {
while ($row_display_searched = $result_display_searched->fetch_assoc()) {
if ($searched_data == $row_display_searched["id"]) {
//bold match
echo "<b>" . $row_display_searched["id"] . " " . $row_display_searched["name"] . " " . $row_display_searched["address"] . " </b><br>";
} else {
echo $row_display_searched["id"] . " " . $row_display_searched["name"] . " " . $row_display_searched["address"] . " <br>";
}
}
}
}
} else {
echo "Record not found.";
}
} else {
//Initial display all data before search
$sql_initial = "SELECT id, name, address FROM employee";
$result_initial = $conn->query($sql_initial);
if ($result_initial->num_rows > 0) {
while ($row_initial = $result_initial->fetch_assoc()) {
echo $row_initial["id"] . " " . $row_initial["name"] . " " . $row_initial["address"] . " <br>";
}
}
}
?>
</body>
<script>
document.onkeydown = function(evt) {
var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
if (keyCode == 13) {
//your function call here
document.searchForm.submit();
}
}
</script>

Display search results on new page

I have a Wordpress page I'm working on with a search function that pulls from a database hosted on Amazon AWS.
When searching, I can pull the data just fine, but the results display below the search bar.
I'd like the results to display on its own separate page.
I've tried several suggestions using previously asked questions, though nothing worked.
Here is my code:
<?php
/* Template Name: Database */
?>
<?php
global $query_string;
$query_args = explode("&", $query_string);
$search_query = array();
if( strlen($query_string) > 0 ) {
foreach($query_args as $key => $string) {
$query_split = explode("=", $string);
$search_query[$query_split[0]] = urldecode($query_split[1]);
} // foreach
} //if
$search = new WP_Query($search_query);
?>
<?php get_header(); ?>
<?php get_footer(); ?>
<?php
$db_hostname = 'xxxxxxxxxxxxxxx';
$db_username = 'xxxxxxxxxxxxxxx';
$db_password = 'xxxxxxxxxxxxxxx';
$db_database = 'xxxxxxxxxxxxxxx';
$con = mysql_connect($db_hostname,$db_username,$db_password);
if (!$con){
die('404 Could not connect to server: ' . mysql_error());
}
mysql_select_db($db_database, $con);
global $sf_options;
$sidebar_config = $sf_options['archive_sidebar_config'];
$left_sidebar = $sf_options['archive_sidebar_left'];
$right_sidebar = $sf_options['archive_sidebar_right'];
$blog_type = $sf_options['archive_display_type'];
if ( $blog_type == "masonry" || $blog_type == "masonry-fw" ) {
global $sf_include_imagesLoaded;
$sf_include_imagesLoaded = true;
}
?>
<div class="container-fluid">
<center>
<form role="" method="get" >
<p style="color: #fff;">Search products and services for your business. We make it easier<br />to manage your business operations and make informed purchasing decisions.</p>
<input type="text" name="term" placeholder="Start typing to find a product or business"/>
<span><input type="submit" value="" class="btn btn-default" /></span>
</form>
</center>
</div>
<?php
if (!empty($_REQUEST['term'])) {
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = "SELECT * FROM wpfr_listing WHERE Description LIKE '%".$term."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo '<br /> Company: ' .$row['title'];
echo '<br /> Certs: '.$row['certs'];
echo '<br /> Certifier: '.$row['certifier'];
echo '<br /> Address: '.$row['address'];
echo '<br /> Country: '.$row['country'];
echo '<br /> State: '.$row['state'];
echo '<br /> City: '.$row['city'];
}
}
?>
Any help provided is much appreciated.
Write on this page
<?php if (!empty($_REQUEST['term'])) {
header("location: page_url?term=".$_REQUEST['term']);
}
?>
And on serach result page
<?php
$term = mysql_real_escape_string($_GET['term']);
$sql = "SELECT * FROM wpfr_listing WHERE Description LIKE '%".$term."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo '<br /> Company: ' .$row['title'];
echo '<br /> Certs: '.$row['certs'];
echo '<br /> Certifier: '.$row['certifier'];
echo '<br /> Address: '.$row['address'];
echo '<br /> Country: '.$row['country']; echo '<br /> State: '.$row['state'];
echo '<br /> City: '.$row['city'];
}
?>
Since, you want this done, via PHP, here you go.
1)create a new page.
2)Have it handle a GET data of the query you have used here.
3) Print your search results as you have done in this page.
Now, in this page, you need to do a header redirect to that page The syntax for a header redirect is like this.
header('Location: http://www.example.com/?sql = <Your Query above>');
This should do it for you. Hope this helps. Feel free to comment, if you need any further info.

PHP SQL Insert text value into database

I am working on an online shopping cart project, which requires me to be able to add a custom text input field to each item that is added to the shopping cart. However, when I attempt to insert the information for each item in the card into a database, I cannot figure out how to pass the itemtext value into my INSERT statement. How would I go about being able to pass the itemtext value from the initial item list into my database for Orderitems? The itemtext input is on line 170, and I want to pass it into the INSERT statement seen on line 83.
<?php
session_start();
$user = $_SESSION['user'];
if(!isset($user)) {
header("Location:userlogin.php");
}
$cart = $_COOKIE['WSC'];
if(isset($_POST['clear'])) {
$expire = time() -60*60*24*7*365;
setcookie("WSC", $cart, $expire);
header("Location:order.php");
}
if($cart && $_GET['id']) {
$cart .= ',' . $_GET['id'];
$expire = time() +60*60*24*7*365;
setcookie("WSC", $cart, $expire);
header("Location:order.php");
}
if(!$cart && $_GET['id']) {
$cart = $_GET['id'];
$expire = time() +60*60*24*7*365;
setcookie("WSC", $cart, $expire);
header("Location:order.php");
}
if($cart && $_GET['remove_id']) {
$removed_item = $_GET['remove_id'];
$arr = explode(",", $cart);
unset($arr[$removed_item-1]);
$new_cart = implode(",", $arr);
$new_cart = rtrim($new_cart, ",");
$expire = time() +60*60*24*7*365;
setcookie("WSC", $new_cart, $expire);
header("Location:order.php");
}
if(isset($_POST['PlaceOrder'])) {
$email = $user;
$orderdate = date('m/d/Y');
$ordercost = $_POST['ordercost'];
$ordertype = $_POST['ordertype'];
$downcost = $_POST['downcost'];
$cardtype = $_POST['cardtype'];
$cardnumber = $_POST['cardnumber'];
$cardsec = $_POST['cardsec'];
$cardexpdate = $_POST['cardexpdate'];
$orderstatus = "Pending";
if($ordertype=="") {
$ordertypeMsg = "<br><span style='color:red;'>You must enter an order type.</span>";
}
if($cardtype=="") {
$cardtypeMsg = "<br><span style='color:red;'>You must enter a card type.</span>";
}
if($cardnumber=="") {
$cardnumberMsg = "<br><span style='color:red;'>You must enter a card number.</span>";
}
if($cardsec=="") {
$cardsecMsg = "<br><span style='color:red;'>You must enter a security code.</span>";
}
if($cardexpdate=="") {
$cardexpdateMsg = "<br><span style='color:red;'>You must enter an expiration date.</span>";
}
else {
include ('includes/dbc_admin.php');
$sql = "INSERT INTO Orders (email, orderdate, ordercost, ordertype, downcost, cardtype, cardnumber, cardsec, cardexpdate, orderstatus)
VALUES ('$email', '$orderdate', '$ordercost', '$ordertype', '$downcost', '$cardtype', '$cardnumber', '$cardsec', '$cardexpdate', '$orderstatus')";
mysql_query($sql) or trigger_error("WHOA! ".mysql_error());
$sql = "SELECT orderid FROM Orders";
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
while($row=mysql_fetch_assoc($result)) {
$myid = $row[orderid];
}
$itemnumber = 1;
$items = explode(',', $cart);
foreach($items AS $item) {
$sql = "SELECT * FROM Catalog where id = '$item'";
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
while($row=mysql_fetch_assoc($result)) {
$itemtext = $_POST['itemtext'];
$sql= "INSERT INTO OrderItems (orderid, itemnumber, itemid, itemtype, media, itemtext, price)
VALUE ('$myid', '$itemnumber', '$row[itemid]', '$row[itemtype]', '$row[media]', '$itemtext[itemnumber]', '$row[price]')";
mysql_query($sql) or trigger_error("WHOA! ".mysql_error());
}
$itemnumber++;
}
$inserted = "<h2>Thank You!</h2> <h3>Your order has been placed.</h3>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Williams Specialty Company</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function validateForm() {
var ordercost = document.form1.ordercost.value;
var downcost = document.form1.downcost.value;
var ordertype = document.form1.ordertype.value;
var cardtype = document.form1.cardtype.value;
var cardnumber = document.form1.cardnumber.value;
var cardsec = document.form1.cardsec.value;
var cardexpdate = document.form1.cardexpdate.value;
var ordertypeMsg = document.getElementById('ordertypeMsg');
var cardtypeMsg = document.getElementById('cardtypeMsg');
var cardnumberMsg = document.getElementById('cardnumberMsg');
var cardsecMsg = document.getElementById('cardsecMsg');
var cardexpdateMsg = document.getElementById('cardexpdateMsg');
if(ordertype == ""){ordertypeMsg.innerHTML = "You must enter an order type."; return false;}
if(cardtype == ""){cardtypeMsg.innerHTML = "You must enter a card type."; return false;}
if(cardnumber == ""){cardnumberMsg.innerHTML = "You must enter a card number."; return false;}
if(cardsec == ""){cardsecMsg.innerHTML = "You must enter a security code."; return false;}
if(cardexpdate == ""){cardexpdateMsg.innerHTML = "You must enter an expiration date."; return false;}
}
</script>
</head>
<body>
<?php include('includes/header.inc'); ?>
<?php include('includes/nav.inc'); ?>
<div id="wrapper">
<?php include('includes/aside.inc'); ?>
<section>
<h2>My Cart</h2>
<table width="100%">
<tr>
<th>Catalog ID</th>
<th>Item Name</th>
<th>Price</th>
<th>Item Text</th>
<th>Actions</th>
</tr>
<?php
$cart = $_COOKIE['WSC'];
if ($cart) {
$i = 1;
$ordercost;
include('includes/dbc.php');
$items = explode(',', $cart);
foreach($items AS $item) {
$sql = "SELECT * FROM Catalog where id = '$item'";
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
while($row=mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td align="left">';
echo $row['itemid'];
echo '</td>';
echo '<td align="left">';
echo $row['itemname'];
echo '</td>';
echo '<td align="left">';
echo $row['price'];
$ordercost+=$row['price'];
$downcost = $ordercost / 10;
echo '</td>';
echo '<td align="left">';
echo '<p><input type="text" id= "itemtext" name="itemtext"></p>';
echo '</td>';
echo '<td align="left">';
echo 'Remove From Cart';
echo '</td>';
echo '</tr>';
}
$i++;
}
}
?>
</table><br />
<form method="POST" action="<?php $_SERVER['PHP_SELF'];?>">
<input type="submit" name="clear" value="Empty Shopping Cart">
</form>
<?php if(isset($inserted)) {echo $inserted;} else{ ?>
<form method="post" action="<?php echo $SERVER['PHP_SELF'] ?>" name="form1" onSubmit="return validateForm()">
<p>Total Price: <?php echo $ordercost;?> <input type="hidden" id="ordercost" name="ordercost" value="<?php echo $ordercost;?>"> </p>
<p>Down Cost: <?php echo number_format((float)$downcost, 2, '.', '');?> <input type="hidden" id="downcost" name="downcost" value="<?php echo number_format((float)$downcost, 2, '.', '');?>"> </p>
<p><label>Order Type:</label><br> <input type="text" id="ordertype" name="ordertype">
<?php if(isset($ordertypeMsg)) {echo $ordertypeMsg;} ?>
<br /><span id="ordertypeMsg" style="color:red"></span>
</p>
<p><label>Card Type:</label><br> <input type="text" id="cardtype" name="cardtype">
<?php if(isset($cardtypeMsg)) {echo $cardtypeMsg;} ?>
<br /><span id="cardtypeMsg" style="color:red"></span>
</p>
<p><label>Card Number:</label><br> <input type="text" id="cardnumber" name="cardnumber">
<?php if(isset($cardnumberMsg)) {echo $cardnumberMsg;} ?>
<br /><span id="cardnumberMsg" style="color:red"></span>
</p>
<p><label>Card Security Code:</label><br> <input type="text" id="cardsec" name="cardsec">
<?php if(isset($cardsecMsg)) {echo $cardsecMsg;} ?>
<br /><span id="cardsecMsg" style="color:red"></span>
</p>
<p><label>Card Expiration Date:</label><br> <input type="text" id="cardexpdate" name="cardexpdate">
<?php if(isset($cardexpdateMsg)) {echo $cardexpdateMsg;} ?>
<br /><span id="cardexpdateMsg" style="color:red"></span>
</p>
<p><input type="submit" name="PlaceOrder" value="Place Order"></p>
</form><?php }?>
</section>
</div>
<?php include('includes/footer.inc'); ?>
</body>
</html>
Update: This is your answer: change '$itemtext[itemnumber]' into '$itemtext'
This is going wrong because of the way you use quotes. (not the answer but you might want to think about it ;-) )
$sql = "INSERT INTO Orders (email, orderdate, ordercost, ordertype, downcost, cardtype, cardnumber, cardsec, cardexpdate, orderstatus)
VALUES ('$email', '$orderdate', '$ordercost', '$ordertype', '$downcost', '$cardtype', '$cardnumber', '$cardsec', '$cardexpdate', '$orderstatus')";
You should not use '$email' but -for example- ...VALUES ('".$email."',...
Learn more about this here: What is the difference between single-quoted and double-quoted strings in PHP?
On another note, your code is not safe. Please use: http://php.net/manual/en/function.mysql-real-escape-string.php
Example:
...VALUES ('".mysql_real_escape_string($email)."',...

PHP if option is selected, selected option can't selected again in other chooses

Hello my name is Patrick and this is my first question, i'm sorry but i'm not very good in PHP. probably there are more improvements but this post is for the questions. (but improvements are also welcome)
Question:
You can choose a team of 2 monsters // The monster are selected form database
The question is: if you choose 1 monster how can i fix that you can't choose the same monster on option 2?
PHP CODE:
Action of the 2 sumbit buttons
<?php
session_start();
include("header.php");
if(!isset($_SESSION['uid'])){
echo "You must be logged in to view this page!";
}else{
if (isset($_POST['save'])) {
if ($_POST['save'] == 'keuze4') {
$fuelQuery4 = sprintf("UPDATE user_team SET `m_keuze4` = '%s' WHERE `id`='".$_SESSION['uid']."' ",
mysql_real_escape_string($_POST['option4']));
$Result = mysql_query($fuelQuery4);
if($Result){
echo 'Team is aangepast!';
}
} elseif ($_POST['save'] == 'keuze5'){
$fuelQuery5 = sprintf("UPDATE user_team SET `m_keuze5` = '%s' WHERE `id`='".$_SESSION['uid']."' ",
mysql_real_escape_string($_POST['option5']));
$Result = mysql_query($fuelQuery5);
if($Result){
echo 'Team is aangepast!';
}
}
echo '';}
?>
Get the monsters form database and put it in a select list
<?php
$get=mysql_query("SELECT * FROM user_monsters WHERE `id`='".$_SESSION['uid']."' ORDER BY usid ASC");
$option4 = '';
while($row = mysql_fetch_assoc($get))
{
$option4 .= '<option value = "'.$row['usid'].'">'.$row['usid'].' - '.$row['monster'].' - '.$row['type'].'</option>';
}
?>
Show the selected item
<?php
$k4 = mysql_query("
SELECT user_team.m_keuze4, user_monsters.usid, user_monsters.monster, user_monsters.type, user_monsters.attack, user_monsters.defense
FROM user_team
INNER JOIN user_monsters
ON user_team.m_keuze4=user_monsters.usid
ORDER BY user_monsters.type;
");
while($row4 = mysql_fetch_assoc($k4))
{
$k4_1 = ''.$row4['m_keuze4'].' - '.$row4['monster'].' - '.$row4['type'].' - '.$row4['attack'].' - '.$row4['defense'].'';
}
?>
Option 5 is the same code as 4:
<?php
$get=mysql_query("SELECT * FROM user_monsters WHERE `id`='".$_SESSION['uid']."' ORDER BY usid ASC");
$option5 = '';
while($row = mysql_fetch_assoc($get))
{
$option5 .= '<option value = "'.$row['usid'].'">'.$row['usid'].' - '.$row['monster'].' - '.$row['type'].'</option>';
}
?>
<?php
$k5 = mysql_query("
SELECT user_team.m_keuze5, user_monsters.usid, user_monsters.monster, user_monsters.type, user_monsters.attack, user_monsters.defense
FROM user_team
INNER JOIN user_monsters
ON user_team.m_keuze5=user_monsters.usid
ORDER BY user_monsters.type;
");
while($row5 = mysql_fetch_assoc($k5))
{
$k5_1 = ''.$row5['m_keuze5'].' - '.$row5['monster'].' - '.$row5['type'].' - '.$row5['attack'].' - '.$row5['defense'].'';
}
?>
The Form
<form action="team.php" method="post">
<select name="option4">
<?php echo $option4; ?>
</select><br><br>Keuze 4
<?php
echo $k4_1;
?><br><br>
<input type="submit" name="save" value="keuze4"/>
</form>
<form action="team.php" method="post">
<select name="option5">
<?php echo $option5; ?>
</select><br><br>Keuze 5
<?php
echo $k5_1;
?><br><br>
<input type="submit" name="save" value="keuze5"/>
</form>
In php the best you can do check the option once its posted:
if (isset($_POST['save'])) {
if (filter_input(INPUT_POST,'option4') == filter_input(INPUT_POST,'option5')){
echo "Sorry. You can't select the same monster twice";
}else{
//your db insert logic goes here
}
}
It would be a good idea to also include some javascript to alert the user before they submit the form. This example uses jQuery
$('[name="option4"],[name="option5"]').change(function(){
if ($('[name="option4"]').val() == $('[name="option5"]').val()){
alert('you already chose that monster, please choose another');
}
});
The Form
<form action="team.php" method="post">
<select name="option4">
<?php echo $option4; ?>
</select><br><br>Keuze 4
<?php
echo $k4_1;
?><br><br>
<input type="submit" name="save" value="keuze4"/>
</form> <!-- remove this line-->
<form action="team.php" method="post"> <!-- and this line-->
<select name="option5">
<?php echo $option5; ?>
</select><br><br>Keuze 5
<?php
echo $k5_1;
?><br><br>
<input type="submit" name="save" value="keuze5"/>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function () {
$('[name="option4"],[name="option5"]').change(function () {
if ($('[name="option4"]').val() == $('[name="option5"]').val()) {
alert('you already chose that monster, please choose another');
}
});
});
</script>
Action of the 2 sumbit buttons
if (isset($_POST['save'])) {
if (filter_input(INPUT_POST, 'option4') == filter_input(INPUT_POST, 'option5')) {
echo "Sorry. You can't select the same monster twice";
} else {
if ($_POST['save'] == 'keuze4') {
$fuelQuery4 = sprintf("UPDATE user_team SET `m_keuze4` = '%s' WHERE `id`='" . $_SESSION['uid'] . "' ", mysql_real_escape_string($_POST['option4']));
$Result = mysql_query($fuelQuery4);
if ($Result) {
echo 'Team is aangepast!';
}
} elseif ($_POST['save'] == 'keuze5') {
$fuelQuery5 = sprintf("UPDATE user_team SET `m_keuze5` = '%s' WHERE `id`='" . $_SESSION['uid'] . "' ", mysql_real_escape_string($_POST['option5']));
$Result = mysql_query($fuelQuery5);
if ($Result) {
echo 'Team is aangepast!';
}
}
}
}
Edit again,
Demo Fiddle of js

View customer info on select change

I'm creating a page which will allow an admin to select a user from a drop down list, which populates from a database. When the person is selected, the info associated with that person will then be viewed on the page. I already have a select statement which selects all the info and the drop down menu is populating correctly. However, I'm unsure on how to get that selected user's info to display on the page once selected. Would I need to do an entirely different select statement and query which checks which customer was selected? Or is there another way?
customer.php
<div id="view_form" class="view">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select name='selectCust' id='selectCust'>";
echo "<option></option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
echo "<option>$name</option>";
}
echo "</select>";
?>
</fieldset>
</form>
</div>
viewUser.php
if(isset($search)){
$select = "SELECT * FROM $cust WHERE acctNum='{$search}'";
$result = mysqli_query($db, $select);
if(mysqli_num_rows($result) > 0){
if($row = mysqli_fetch_assoc($result)){
$acct = "{$row['acctNum']}";
echo $acct;
}
}
}
script.js
$(document).ready(function(){
function searchAjax(){
var search = $('#selectCust').val();
$.post('includes/viewUser.php', {searchUsers: search}, function(data){
$('#view_form').append(data);
})
}
$('#selectCust').on('change', function(ev){
ev.preventDefault();
searchAjax();
})
})
Search.php
<script type="text/javascript "src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
$(".dropdown-users").on("change",function(event){
event.preventDefault();
search_ajax_way();
});
});
function search_ajax_way(){
var search_this=$("dropdown-users").val();
$.post("Ajaxsearch.php", {searchusers : search_this}, function(data){
$(".results").html(data);
})
}
</script>
<div id="view_form" class="view">
<form method="post">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select class="dropdown-users">";
echo "<option></option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
$acct = $row['acctNum'];
echo "<option value="$acct">$name ($acct)</option>";
}
echo "</select>";
?>
</fieldset>
</form>
</div>
<label>Enter</label>
<input type="text" name="search_query" id="search_query" placeholder="What You Are Looking For?" size="50"/>
<input type="<span id="IL_AD1" class="IL_AD">submit</span>" <span id="IL_AD6" class="IL_AD">value</span>="Search" id="button_find" />
<div class="results"></div>
//********************************************************************************************
********************************************************************************************//
Ajaxsearch.php
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db"); // Enter your information here
$term = $_POST['searchusers']
$term = mysqli_real_escape_string($con, $term);
if($term == "")
echo "Enter Something to search";
else {
$query = mysqli_query($con, "select * from USERDATEBASEHERE where ID = '{$term}' ");
$string = '';
if (mysqli_num_rows($query) > 0) {
if (($row = mysqli_fetch_assoc($query)) !== false) {
$string = "{$row['ID']}";
}
} else {
$string = "This Person does not exist";
}
echo $string;
}
?>
<div id="view_form" class="view">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select name=\"somename\" onchange=\"this.form.submit();\">";
echo "<option value=\"\">Select User</option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
$acct = $row['acctNum'];
echo '<option value="'.$acct.'">$name ($acct)</option>';
}
echo "</select>";
?>
</fieldset>
</form>
</div>
The options must have some refering value, through which you can retrieve the details of selected user, whenever the value of option is not initiated then the default value of the option will be option's label.

Categories