I have to make an online shop.
I generate my products from a database like this:
$sql = "SELECT * FROM wblouses";
$result = mysql_query($sql);
if (! $result)
{
echo "eroare db database-item";
}
else
while($db_field = mysql_fetch_assoc($result)) {
echo "<div class=\"col-md-4\"><div class=\"thumbnail\"><form method=\"POST\" action=\"addToChart.php\" ><img style=\"display: block;\" src=";
echo $db_field["poza"]." height=\"250\" width=\" 400 \"> <p class=\"prices\">
<span class=\"price\" data-color=\"401\" >
<span class=\"currentPrice\"> ".$db_field["pret"]." LEI </span>
</span>
<input type=\"username\" name=\"username\">
<select id=\"myselect\" name=\"myselect\">
<option value=".$db_field["ID"].">SIZE</option>
<option value=\"XS\">XS</option>
<option value=\"S\">S</option>
<option value=\"M\">M</option>
<option value=\"L\">L</option>
</select>
<input type=\"submit\" value=\"add to chart\">
</p></form><button id=\"ilas\" onClick=\"fct(this.id)\">B3</button></div></div> ";
}
In another .php file I manage a database which represents a list of items selected from the one posted. How do I pass the id of a particular item to another file, I only seem to get the last generated id.
How can I pass some arguments to another php file?
The problem is that every product has it`s own generated div,dropdown and button with the same name and ID , how I find out in .php which product I refer to(it always refer to the last added product)?
#Skrrp
#TEster
Simple answer, you can't pass both bits of data from the same select.
You could do some funky concatenation, such as;
<option value=\"" . $db_field["ID"] . ";XS\">XS</option>
and then do a string spilt on the other side. This is silly. Don't do this.
If you have multiple products that you want the user to select from, what you want is 2 select drop-downs, one for product and one for size. If certain products are available only in certain sizes you will need some JavaScript to sort out the second.
What you are probably looking for is a hidden data field. It looks like you have already selected the product (and its ID) by the stage you generate this form. Rather than putting the $db_field["ID"] in the select, put it in its own control.
<input type=\"hidden\" name=\"id\" value=\"" . $db_field["ID"] . "\">
Then when you get to your next page, $_POST["id"] will contain the product ID you need.
As the above guys said,
I recommend using a hidden field to store the value.
$id = $db_field["ID"];
<input type='hidden' name='id' value='$id'>
Then just collect it using $_POST['id'] on the other php script.
Related
I have a list of products that I wish to be editable. When a user hits the edit button, then the content of only the selected product needs to be changed (for example to a textbox so the user can edit the title on the fly). But how do I prevent php to echo for example a textbox to all the products- I guess it would do that automatically?
I also guess that i should use some Jquery stuff to make the content editable :P ?
The list is being looped like this:
$items = $mysqli->query("SELECT product_name, product_id FROM products");
while($products = $items->fetch_assoc(){
echo $products['product_name'];
echo 'Edit me';
}
As your first commenter pointed out, PHP alone is not enough here. You'll need on-page JS code that can communicate the changes in the browser, and a PHP script that can take those changes and work them back into the database. You can either write that yourself, or use proven libraries that exist specifically for this purpose, like http://backbonejs.org/ or http://angularjs.org/
These are model/view frameworks that let you show a view of your database data on a page, while keeping them editable, updating the database records when you update the entry online. But be warned: if you've never worked with MVC frameworks, you get to look forward to probably being very confused at first. The approach is completely different from the much simpler "get data from db with PHP, generate page content, send off to client, the end" approach.
Not necessarily the most efficient, but if there aren't a huge number of products how about including a simple form for each product but just hiding it until the 'Edit' link is clicked?
The list/forms:
$items = $mysqli->query("SELECT product_name, product_id FROM products");
while($products = $items->fetch_assoc(){
echo "<span>" . $products['product_name'] . "</span>";
echo "<a class='editButton'>Edit</a>";
echo "<form action='products.php' method='post' style='display: none;'>
<input type='hidden' name='product' value='" . $products['prodcut_id'] . "' >
<input type='text' name='title' value='" . $products['product_name'] . "' >
<input type='submit' value='Update' >
</form>";
echo "<br/>";
}
The jQuery:
$(".editButton").click(function(){
//Hide the text entry and the edit link
$(this).prev().hide();
$(this).hide();
//Show the form
$(this).next().show();
});
If you'd rather not reload the page to submit changes you could submit them via ajax too for a more dynamic user experience.
Thanking you for taking the time to look at this question.
The premise of the situation is that I have a "website" written in PHP and HTML that displays items from my database named "Spreadsheet." There are six columns, and over 4000+ rows of data. The columns are "accountID", "accountName", "website", "rating", "imageURL", "comments." The column "rating" in the website is a drop down list.
Currently, everything works well, but I have do questions:
How do I, with PHP, have data submitted to the database upon clicking on an option (such as "Very Bad") in the drop down list? At the moment, it requires the user to click a "submit" button, which refreshes the page entirely, losing their position. Is it possible to have it submit silently (without refreshing)
Second question has to do with the drop-down list again. How do you have the drop-down list display what's in the database? For example, if rating is "Very Bad" in the database, the drop-down list reflects that, and not what the first element is.
Below is my code.
". $row['website']."<br />
<Form Name =\"rating\" Method =\"POST\" ACTION =\"\" />
<input type = \"hidden\" name=accountID value=" . $row['accountID'] . ">
<select name=\"rating\">
<option value=\"\"></option>
<option value=\"Very Bad\">Very Bad</option>
<option value=\"Bad\">Bad</option>
<option value=\"Average\">Average</option>
<option value=\"Above Average\">Above Average</option>
</select>
<INPUT TYPE =\"Submit\" Name =\"formSubmit\" VALUE =\"Submit\">
if (isset($_POST['formSubmit'])){
$rating = $_POST['rating'];
$accountID = $_POST['accountID'];
var_dump($rating);
var_dump($accountID);
if(!mysql_query("UPDATE Spreadsheet SET rating='$rating' WHERE accountID='$accountID'")) {echo 1;}
}
mysql_close();
?>
Thanks so much! This question has been bothering me for a bit. I have tried many Google attempts, but I could not find an answer as specific as I am asking. Thank you so much.
Answer to #1:
You can use Javascript/AJAX to accomplish submitting the form without actually pressing submit. There are various javascript libraries that can help you accomplish this a lot easier than bare bones Javascript, namely jQuery ( http://jquery.com/ ). It's not a very complicated task but you will need to learn some basic Javascript and how to use jQuery. The essential flow of things would be when the form changes, submit an AJAX request to submit the form. You will need a second script to take the incoming AJAX request and do the save. Try search engines for some basic jQuery tutorials, and once you have a basic grip, something like "ajax submit on form change jquery" will get you started.
Answer to #2:
Something like this (please see my notes...)
echo '<select name="rating" id="rating">';
$q = mysql_query("SELECT `option_name` FROM `options`");
while($row = mysql_fetch_assoc($q)) {
echo '<option value="' . $row['option_name'] . '">' . $row['option_name'] . '</option>';
}
echo '</select>';
If you would like the select preselected, that's pretty easy too! Taking from the last example:
$pre_selected = "Very Bad";
echo '<select name="rating" id="rating">';
$q = mysql_query("SELECT `option_name` FROM `options`");
while($row = mysql_fetch_assoc($q)) {
echo '<option value="' . $row['option_name'] . '"';
if($row['option_name'] == $pre_selected) {
echo ' selected="selected"';
}
echo '>' . $row['option_name'] . '</option>';
}
echo '</select>';
But this is the part I'd like to point a few things out:
Don't use the old mySQL library like you are using and my examples are using. Please, use PDO, or at least mySQLi. The functions you are using are deprecated, and may not be available in PHP for much longer.
Please, escape your data properly. Search for "SQL Injection" and you will find a massive amount of information about how your code is very insecure (your UPDATE, specifically) because you did not escape the values.
Just a heads up, when/if you use jQuery, you're going to need to use id="foo" in addition to name="foo".
For the first question you can look at ajax onchange event. Basically when you change select value you fill call function that can call php file to insert data in db.
For the second question you check the DB for selected value and if it matches option value or text you set it to selected
<select name=\"rating\">
<option value=\"\"></option>
<option value=\"Very Bad\">Very Bad</option>
<option value=\"Bad\">Bad</option>
<option value=\"Average\">Average</option>
<option value=\"Above Average\"
<?php if($someValueFromDb=='Above Average'){
echo 'selected=selected';}?>
>Above Average</option>
</select>
Here is a quickie obviously unworking code of an example of what I am looking to do.
Lets say this is a dinner menu, and the echo's are currently all the foods that are stored in the database. The user selects only the foods they want, and those selections are inserted into another table.
EXAMPLE:
<form method="post" action="entryform3.php">
<?php
SELECT * FROM foods ...etc...etc...
//Say for example whats echoed below at the moment is value: pizza, apple, steak...etc. So this will echo atleast 3 entries.
echo "For dinner, I'd like ". $result['food'] ."?";
echo "<input type=\"checkbox\" name=\"check\" />Click Me<hr></input>";
echo "<input type=\"hidden\" name=\"item_name\" value=\"$result['food']\"/>";
?>
<input type="submit" value="Add Selected Foods" name="submit"></form>
------------entryform3.php-----------
<?php
$food = $_POST['food'];
if (isset($_POST['check'])) {
INSERT INTO selectedfoods "(foods) VALUES '$food'";
}
//made up example... but if user check marks only apple, and steak from the echo, I want only apple and steak to be inserted into database.
?>
I realize there is missing mysql and such, but my problem lies in tying together the checkbox button with an individual value. My partially working code that I took this example from, only takes the very last echoed selection, if any one of the foods is checked.
So, it doesn't send the correct food choice into the database, only the last echoed --the if statement only notices if any one of the check boxes are selected or not.
Thanks!
It seems like you miss the name of the checkbox as array. For example, you may write your checkbox like this:
<input type="checkbox" name="box[]" value="name_of_food" />Name_of_Food<br />
.......
.......
then when you get the result, just do like this:
<?php
if(isset($_POST['check'])){
$foods = $_POST['box'];
foreach($foods as $food){
echo $food." <br />";
}
}
?>
Hi i want to get changed text value from JQuery but i can't select edit text with JQUERY because edit texts generated from php while loop that this php code query on database and get value of edit texts and in my program i have edit button for every edit texts and when the user changed value of edit text i select new value and when user click edit button send this value from get method to another php page with jquery $.ajax function and send new value to that php code with ajax.But i don't know how can i select edit text that it's value changed because i don't know id of that edit text!.And when i set one id for every edit text i only get first edit text value from $("#id").change().val();.I use below code but it doesn't work.I am beginner in java script and don't know how fix this problem!.
var testAnswer;
function setNewTestAnswer(id){
testAnswer = $("#id").val();
}
function sendToEdit(pID,phID,thDate,type){
var info = 'pId='+pID+'&phId='+phID+'&testAnswer='+testAnswer+'&thDate='+thDate+'&type='+type;
}
2nd function use testAnswer that user changed in edit text.
php code
<?php
include 'Connect.php';
if(match($_POST['pId'], "/^[\d]+$/") ){
$pId = $_POST['pId'];
$result = mysql_query("select pName, pID, phName, phID, testHistoryDate, type, testAnswer from patient join reception using(pID) join physician using(phID) join testHistory using(rID) join test using(tID) where pID = $pId",$connection);
}
else
die("Insert true value");
while($row=mysql_fetch_array($result)){
echo "<tr><td>";
echo $row["pName"].'</td>';
echo '<td>'.$row["phName"].'</td>';
echo '<td>'.$row["testHistoryDate"].'</td>';
echo '<td>'.$row["type"].'</td>';
$type = $row['type'];
$testHistoryDate = $row['testHistoryDate'];
?>
<td>
<span id='spryTanswer'>
<input type='text' name='tAnswer' id='tAnswer' value='<?php echo $row['testAnswer']; ?>' />
</span>
</td>
<td>
<input type='submit' value='Edit' name='edit' id='edit' onclick="sendToEdit('<?php echo $row['pID'] ?>','<?php echo $row['phID'] ?>', '<?php echo $row['testHistoryDate'] ?>', '<?php echo $row['type'] ?>')" />
</td>
</tr>
<?php } ?>
tl;dr
So it isn't completely clear what you are trying to do here but I can explain a couple things that might help.
in html ids should be unique. You dont have to obey this rule for your page to work but you have found one of the consequences if breaking it: jQuery will only find the first one.
it is a good idea to base html ids on some unique attribute of your data eg the table row id.
You can get more creative with your jQuery selectors for example
$('input[type="text"]') // gets all the text inputs
Use classes. When you want to be able to easily select all of a group of html elements you should give them all the same class name. one element can have multiple class names and many elements can share a class name. you can then select them by class name using jquery like this:
$('.myclassname')
I think you need to change your php to look more like this:
<span class='spryTanswer'>
<input type='text' name='tAnswer' id='tAnswer-<?php echo $row['id'] ?>' value='<?php echo $row['testAnswer']; ?>' />
</span>
Since you're creating elements inside a php loop, you must be sure that every element has a unique id (or no id at all). You can use either an incrementing index, or some unique value in your array. At first glance, seems that $row['pID'] is a good candidate:
<input id='edit_<?php $row['pID'] ?>' type='submit' value='Edit' ... />
After that you should be able to target individual elements.
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