Good morning everyone,
I have a page that performs a default connection to database, search and looped output of data to the page by applying a template for each result in the table using this code:
<?php
$result = mysqli_query($con,"SELECT * FROM XXX WHERE Type='ABCD';");
while($row = mysqli_fetch_array($result))
{
include('includes/template-1234.php');
}
mysqli_close($con);
?>
On the same page I have a simple HTML search box:
<div id="srch-form">
<form>
<input name="srch-box" type="text" id="srch-box" size="45" onClick="this.value='';" onFocus="this.select()" onBlur="this.value=!this.value?'Enter Product Name or SKU#':this.value;" value="Enter Product Name or SKU#">
<input type="submit" name="srch-btn" id="srch-btn" value="Search">
</form>
</div>
Because I am just learning PHP - how do I set this up so that the default action still occurs on page entry, but - onsubmit of something in the searchbox the data in the current page is replaced by the results of the submission? I guess I'm getting confused over the fact that since I have already assigned a value(s) to $result to get the default output, If the value of $result is changed by the search form, does PHP automatically refresh the page when the value of $result is changed? - Sorry if this is a simple thing.
First, you'll have to add an action (which file to refer when submitted) and preferably a method-type in your form-tag. You will also have to include value of $productName (given from server-side php) inside of your html (look at value attribute)
Do something like this:
html-form: (Examplefile: yourhtmlform.php)
Then in your php-file get value from a specific element like this:
<?php
//File querydb.php (example filename)
//Form is submitted and srch-box is set (only set when form is submitted)
if(isset($_POST['srch-box'])) {
$type = $_POST['srch-box']; //Get value of input-element
}
else {
$type = 'kingkong'; //Default type to search
}
$prepareQuery = mysqli_prepare($dbConnectionLink,"SELECT * FROM XXX WHERE Type=:type");
//...code to fetch results..
//You get a productName (or SKU) from db
if (isset($result['product_name'])) {
$productName = $result['product_name']; //or whatever your column is called
}
else {
$productName = '';
}
include('yourhtmlform.php'); //Observe that it must be php to echo out value of $productName in this included file
I noticed you didn't use prepared-statement. Look for more information on prepared statements here: http://www.php.net/manual/en/mysqli.prepare.php (use them!)
I hope this will help you somehow :-)
Related
So basically, I've got a function in PHP that deletes an user from the same row when a form is submit, the form does submit, the function does do it's thing, but the user is not deleted.
$html = '';
$html .= '<table><form method="post" action="index.php?controller=user&action=delUser">';
foreach( $auser as $user) {
$html .= '<tr><td><input type="hidden" value="'.$user['id'].'"><input type="submit" name="delUserSubmit" value=""> '.$user["id"].' '.$user["voornaam"].' '.$user["tv"].' '.$user["achternaam"].'</td></tr>';
}
$html .= '</form></table>';
return $html;
}
So in this form, it sends the id through a hidden input field which carries the user id
public function delUser()
{
if(isset($_POST['delUserSubmit'])) {
$sql = "DELETE FROM user WHERE id = ".$_POST['id'];
$this->oDb->insUpdDelQuery($sql);
unset($_POST);
header("Location: index.php?controller=user&action=show");
}
}
When it reaches the above function, it goes through the isset $_POST etc. Since when everytime I do submit the form, I go to the page at which the header is pointing.
But when it reaches the user page, the user is still there.
Now the problem could either be:
I don't actually send the id
I do send the id, but the $sql doesn't get the id somehow? the delUser() function is empty whereas something like show($id=null) shows all the users.
the delUser() needs something like $_POST['id'], but that would give unexpected characters in my editor.
Can't fix this, anybody able to help?
POST values are submitted using the name attribute on the input field.
Change your HTML input to
<input type="hidden" name="id" value="'.$user['id'].'">
You have not set anything in the from to $_POST['id']. The name of the posted element is taken from the name in the html form. The input tag that has the value of id needs to have the the name set to id:
<input type="hidden" value="'.$user['id'].'" name="id">
Hi i have update my question to explain you my problem easily.Okay so,
What i wnant and whats wrong with me?
i code a product form where i require getcatlist.php which help me get value from sql database and show in product page, Snapshot of product form product form image
Product form code
<section class="main-section">
<article class="prod-item">
<h3>Product Form</h3>
<form action="addproducts.php" method="get" name="product_form">
<section class="select-box">
<label for="category">Category</label>
<?php require_once("getcatlist.php"); ?>
<input type="hidden" name="cat_id" value="<?php echo $_GET['cat_id']; ?>" >
</section>
</form>
</article>
</section>
my javascript in product form page used to create query string code
<script type="text/javascript">
function showCategory(str)
{
document.product_form.action="addproducts.php?cat_id="+str;
}
</script>
**getcallist.php page code which fetch data from databse and show in select tag **
<?php
error_reporting(E_ALL ^ E_NOTICE);
require_once("../data_connect.php");
$error_msg = "";
$cat_id = "";
$catsql = "SELECT Cat_id,CategoryName FROM category order by Cat_id asc; ";
$cat_query = mysqli_query($connect,$catsql);
$numrows = mysqli_num_rows($cat_query);
$cat_id = $_GET['cat_id'];
if($numrows == 0)
{
$error_msg= "No Categories Found";
}
else{
echo "<select name=\"category\" id=\"category\" onchange=\"showCategory(this.value)\" >";
echo "<option value=\"null\">Select your category</option>";
while($catrow = mysqli_fetch_assoc($cat_query))
{
if ($catrow['Cat_id'] == $cat_id){
echo "<option value=\"".$catrow['Cat_id']."\" selected=\"selected\">".$catrow['CategoryName']."</option>";
}
else{
echo "<option value=\"".$catrow['Cat_id']."\">".$catrow['CategoryName']."</option>";
}
}
echo "</select>";
}
?>
here is my ajax code which move to another page when i click on dropdown list
<script type="text/javascript">
/**/$(document).ready(function(){
$("#category").change(function(){
var code = $(this).val();
if(code == 1)
{
$('.main-section').load('addconsoles.php');
}
else if(code == 2)
{
$('.main-section').load('addaccessories.php');
}
else if(code == 3)
{
$('.main-section').load('addgames.php');
}
});
});
</script>
okay i wants to create a query string of category list, when i click on any category option in dropdown list it wont show me any thing in url. This is the big problem i face and also when i try to set and get value in php oop class(require in product form page) it won't set and get when echo it.
Please help me out from this problem, Thanks
I think you have somewhat mis-understood how HTML forms work.
The code you've got will not work as you expect because you have got the cat_id field defined twice within your form - once in the hidden field you created, and again when you alter the action method of the form via the JavaScript. However when your JavaScript runs, it modifies the "action" string, but the hidden field will not change, and when you submit the form, the browser will submit the value from the hidden field, and ignores the value you manually added to the "action" method. This is just the default behaviour in such a situation, in order to resolve the ambiguity you created.
Therefore if at the time the page was first loaded, there was no value in cat_id (which seems likely, looking at your code), then no value for cat_id will be sent to the server when the form is submitted.
However, all of the code I described above is actually unnecessary. You can directly use the value of the dropdownlist as the cat_id. Simply changing the "name" parameter of your <select>, as follows:
echo '<select name="cat_id" id="category">';
will make the cat_id parameter change to whatever is in the selected value of the dropdown when the form is submitted.
You do not need the "showCategory" function, or the hidden field.
So the form can be
<form action="addproducts.php" method="get" name="product_form">
<section class="select-box">
<label for="category">Category</label>
<?php require_once("getcatlist.php"); ?>
</section>
</form>
without the hidden field, and the "showCategory" JavaScript function can be deleted entirely.
N.B. From this code it seems you have no way to submit this "addproducts" form to the server. It's not clear whether you have some other JavaScript elsewhere which controls this and is triggered based on some other event, and/or whether you need to add a "submit" button to the form. Either way, nothing will be sent to the server until you cause the form to be submitted, or provide a way for the user to cause it.
I hope this is useful, please comment if you still find anything unclear.
I am currently working on a form that requires few fields to be filled by the user and few based on the selection made by the user on the previous page. The URL looks like below:
http://localhost:8080/series/dynamics/admin/cleanURL/post.php?subgroup=redapple&adverid=254427035
where redapple is the $_GET variable. However what I wd like the url to look like is ;
http://localhost:8080/series/dynamics/admin/cleanURL/post.php?adverid=254427035
i.e. no info about subgroup selection in the url. But still would like to have the subgroup field to be filled with the choice made by user.
My php looks like this:
<?php require('../config/connection.php');
if(isset($_POST['variable'])){
$values = mysqli_real_escape_string($dbc, $_POST['variable']);
$query = "SELECT * FROM prdct_categories WHERE product = '$values'";
$result = mysqli_query($dbc, $query);
$rand = rand(0, 1000000);
$html = '<ul>';
while($row = mysqli_fetch_assoc($result)){
$clickable_url = 'post.php?subgroup='.$row['subgroup'].'&advertid='.$rand;
$html .= '<li class="nav">';
$html .= ''.$row['subgroup'].'';
$html .= '</li>';
}
$html .='<ul/>';
echo $html;
mysqli_close($dbc);
}
If you don't want to pass information in the URLs then you'll need to use a Cookie or Session. Post the form to a page that gathers the posted data and then set a session or cookie before redirecting the user to the correct page.
http://php.net/manual/en/features.cookies.php
Or
http://php.net/manual/en/features.sessions.php
You can also use a POST request, for example, if I made a form like:
<form action="form_url.php" method="get">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
In form_url.php, I could access the variables like so:
<?php
var_dump($_POST);
The benefit of using POST over GET is that in can be encrypted over SSL whereas all parameters inside a GET request are encoded and visible in the URL. Also, since the URL can only be 265 characters max, that's also the limit of the data size.
If you want to upload something such as an image, you'll want to use a file input in a form field (like the one above) so that data can be sent over a file-stream instead of a url.
EDIT:
If you want another way to just get the url data, you don't have to use get. The full URL can be given by:
<?php
var_dump($_SERVER['HTTP_HOST']);
var_dump($_SERVER['REQUEST_URI']);
Although the REQUEST_URI is probably what you want. Note that any data passed through here can also be obtained from GET, but you don't have to use GET to get the data. You would then want to parse the URL with something like:
<?php
var_dump(explode('\', $_SERVER['REQUEST_URI']));
I'm trying to "pre-fill" (not sure if there's a technical term for this) form fields with values that the user has previously entered in the database. For this example it's a City and State. When the user loads the page to edit options, these values (which they have previously entered) will automatically be in the text boxes.
<tr><td>City</td><td><input type="text" name="city" value="<? $city = "usercity"; echo $formValue->location('$city'); ?>"></td>
<td>State</td><td><input type="text" name="state" value="<? $state = "userstate"; echo $formValue->location('$state'); ?>"></td>
Is there any way to set a value based on the input (from the boxes above)? If it was something like function location($input) I would know how to, but when there's nothing in the parenthesis, is there any way to set a value?
function location(){
$userid = $_SESSION['userid'];
$server = 'localhost';
$user = 'root';
$password = '';
$connection = mysql_connect($server, $user, $password) or die(mysql_error());
mysql_select_db(testdb, $connection) or die(mysql_error());
$result = mysql_query("SELECT '$location' FROM userinfo WHERE userid = '$userid'");
$user_data = mysql_fetch_array($result);
if($location =='usercity'){
$userlocation = $user_data['usercity'];
return $userlocation;
}
else
$userlocation = $user_data['userstate'];
return $userlocation;
}
Instead of thinking about this from a global perspective think about the problem in it's context.
Your starting point (from the server perspective) is that an HTTP GET request has come in from a client for this page, or a client is returning to this page from after a POST request. In either case, the server has located the "resource" (the PHP script) that should handle this request and dispatched it by loading the PHP interpreter with the script file.
The context at this point is at the first line of the script; at the point where the interpreter has just finished parsing and started executing. Ask yourself: does the current request include an active session identifier? If it does have an active session, then check to see if the client has filled in this form before and if they have, substitute the default form values they've previously submitted for the normal form default values. If the client does not have an active session or has not used the form before then show a blank form with default values as needed.
Tip: Consider using this technique to debug your code. Pick a line in your code and place a mental "break point" at that place. Ask yourself: what is the context of this script at this point? What variables are defined? What is the server state? What is the client expecting? Once you have an answer to those questions, writing the code is simple.
From what I see in your code you have the variable in single quotes:
$city = "usercity"; echo $formValue->location('$city');
remove the single quotes, as it will pass '$city' as is, not the value of $city. Try
$city = "usercity"; echo $formValue->location($city);
to make it clearer:
$city = "usercity";
print ('$city'); // will print $city
print ($city); // will print usercity
My last few projects had forms all over the place and telling php to fill out the forms each time was a pain in the arse.
For my current project, I kept the input names the same as the mysql field names. Makes submitting and populating way easier.
When it comes to populating the forms, I use some ajax (jQuery used all over the project so using jquery's ajax() function;
FORM
<form>
<input name="field_one" type = "text" >
<input name="field_two" type = "text" >
<input type="button" value="Send">
</form>
I put a conditional statement at the top of the doc along the lines of:
<?php if($_POST['update']){
$query=mysql_query("SELECT * FROM table WHERE unique_id='$id' LIMIT 1");
echo json_encode(mysql_fetch_assoc($query));
exit;
} ?>
Lets say you have a list of items you want to be able to click on and edit (populate the form with it's corresponding data). I assign it a data- attribute and fill it with it's unique id, normally an AI PRIMARYKEY eg:
while($r=mysql_fetch_assoc($data)){
echo "<li data-unique_id=\"\">$r[name]<span class="edit">edit</span></li>";
?>
$('.edit').click(function(){
var toget = $(this).parent().data('unique_id');
$.ajax({
url:'here so it sends to itself',
data:'update='+toget,
success:function(data){
for (var key in data) {
if (data.hasOwnProperty(key)) {
$('input[name="'+key+'"]').each(function(){
$(this).val(data[key]);
});
}
}
}
});
There's a little more work required for <select>, <textarea>, checkboxes, but same general idea applies, (I threw in a couple of if statements, but it could probably be handled way better)
I could probably explain this better, but I hope you get the idea and i've been of some help.
FYI
my inserts are like...
foreach($_POST as $k=>$v){
$v=mysql_real_escape_string($v);
$fields.=" `$k`,";
$vals.=" '$v',";
}
$fields=substr($fields,0,strlen($fields)-1);//to get rid of the comma :)
$vals=substr($vals,0,strlen($vals)-1);//and again
mysql_query("INSERT INTO ($fields) VALUES ($vals)");
I am going back though a web-based document numbering system from few weeks ago. To sum it up, the user types in the project,class,base, and dash number (PPP-CCC-BBBB-DDD) then it is added to a mysql database. Now most doc numbers go in order according to revisions. IE: A document 1465-630-0001-000 becomes, after revision, 1465-630-0002-000.
The boss wants the system to automatically fill the input text box for the base number if it detects that the user is entering a revised doc. So if a user types in 1465 into the project field and 630 into the class field the system should autofill the base field with the next available number. In the previous example this would be 0002.
It needs to be able to search the database for the first two fields so that it can find the next available one. Is there anyway to do this using javascript or something? SO was really helpful with my last javascript question pertaining to this system.
heres an bit of my code if it helps:
` ?>
<div id='preview'></div>
<form id='item' action="submit.php?item=1" method="post">
Enter Title:<input type="text" name="title" size="20"><BR>
Choose Project Code:
<SELECT NAME="project">
<OPTION VALUE="">Project...
<?
$query = "SELECT * FROM project ORDER BY project asc";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$num = ($row['project']);
$name = ($row['description']);
?>
<OPTION VALUE="<?=$num?>" ><? echo"{$num}" . " | " . "{$name}";?>
<?
}
?>
</SELECT><BR>
Choose Class Code:
<SELECT NAME="class">
<OPTION VALUE="">Class...
<?
$query = "SELECT * FROM class ORDER BY class asc";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$num = ($row['class']);
$name = ($row['description']);
?>
<OPTION VALUE="<?=$num?>" ><? echo"{$num}" . " | " . "{$name}";?>
<?
}
?>
</SELECT><BR>
Assigned Base Number:<input type="text" name="base" size="20"><BR>
Enter Dash Number:<input type="text" name="dash" size="20"><BR>
Enter Comments:<input type="text" name="comment" size="40"><BR>
<input type="hidden" name="item" value="1"/> `
Just a simple html/php input form with the project and class code list generated from a database pertaining to each.
Thanks for any help-Thomas
Update:
So, you're going to need to make an AJAX call (see example in my comment below) to some PHP script that will retrieve the base value you want and then returns that to the AJAX request. Once the request gets a response, you can use that data to fill in the value the way I originally said...
On a side note, since the example I gave you is a jQuery AJAX function, you should probably check out how to use jQuery to select elements on the page, instead of using straight JS.
E.g. for getting by ID and replacing value:
$("#base").attr('value', valueFromAjaxCall);
How to change value with JS:
If you use PHP to get the base value you want to fill into the field, then you can fill the value in with:
var baseField = document.getElementsByName("base")[0];
baseField.value = <?=$baseValue?>;
The getElementsByName() call returns an array, which is why you have to index into the field you want. I would suggest giving your <input> an id so that you can use document.getElementById() instead. You would do something like:
<input type="text" id="base" size="20">
and the JS to get the input element would be:
var baseField = document.getElementById("base");
...therefore, no need to index, in case you named any fields with the same name.
**Not sure about the PHP syntax.
An ajax call on focus of the 3rd field firing back to the server the values of the first two fields?
first, you'll probably want to use jQuery since it has great support is easy to use and will feel familiar to someone used to PHP.
so include your jQuery javascript code that you can get from :
http://jquery.com/
then, assume a form that looks like:
{form}
<input type=text id='major' name='major' value=''>
{Or a select, your choice}
<input type=text id='minor' name='minor'>
{or a select again}
<input type=text id='sequence' name='sequence' onFocus='getNextSequence()'>
...
{/form}
in your head, have your javascript:
function getNextSequence(){
var major=$('#major').val();
var minor=$('#minor').val();
if(!major){
alert('Select a major version#');
$('#major').focus();
return(false);
}
if(!minor){
alert('Select a minor version#');
$('#minor').focus();
return(false);
}
$.getJSON('http://url.to.getnextNumber.php',
{major:major,minor:minor},
function(data){
if(!data.error){
$('sequence').val(data.nextSequence);
}else{
alert(data.error);
}
}
});
}
the jQuery getJSON call will make a call back to your URL with two $_POST variables, major and minor. do your query, save the result as $result=array('nextSequence'=>$x,'error'=>'false');
and convert it to JSON with echo json_encode($result);
don't include ANY headers or any other content in the output of that file, and jQuery will pull the correct value and insert it where it's supposed to bed