I have a dropdown box, and this is the format for the create.blade.php
<div class="col-sm-6">
<label for="order_mode">Order Mode</label>
<select class="form-control" id="order_mode" name="order_mode">
<option value="fcfs">First Come, First Serve</option>
<option value="pre-selling">Pre-Selling</option>
<option value="purchase-order">Purchase Order</option>
</select>
</div>
I want to use the same format for the edit.blade.php but I want to show what the selected value is as the default, and when I change it and hit update, then the changes will be saved.
the value for the order_mode is denoted by value="{{ $product->order_mode }}"
You can use AJAX to POST your variable to your edit.blade.php file. Personally, I use jQuery AJAX, simply because it's easy to read and understand. I also encapsulated the AJAX function into another function that you can call in your update button via onclick. However, you could also add this functionality directly to the AJAX function via an onclick event, however, note that in that case, you will need to put that into a document.ready function, so I figured encapsulating the function would make for easier understanding.
Note that you will need to include a jQuery library for this example to work. However, it's no different from including any other JS file or similar.
Example:
<script src="/js/jquery.min.js" type="text/javascript"></script>
/js/ being your JavaScript folder in your directory.
function updateSelection()
{
$.ajax({
type : "POST",
url : "/edit.blade.php",
data : {
selection: $("#order_mode")val()
},
success: function (html) {
/* here you can do something on success if you want.
I.e. redirect to another page etc. */
}
})
}
As for updating the value, I assume that you are storing the data into a database? If not, then you have to, or else there is no way of knowing what was selected in the future. So, going by that you are in fact storing the selected data into a database, your edit.blade.php file will need to fetch the parsed value (I named it selection in this case), and store it in the database.
<?php
/* Note that we used a "POST" method, so in order to
retrieve our parsed variable, we'll have to use $_POST. */
$selected=$_POST['selection'];
/* We then need to store it into the database.
Note that I don't know what mysql extension you use (mysql_*, mysqli_* or PDO).
I will use mysqli_* in my example, and $conn is your
database connection variable. */
/* Note that you will also need the user ID in order to know which user
updated their selected value. You will also need to check if the selection
already exists or not, because if it doesn't, you will have to perform an insert,
and if it does, you will have to perform an update in your query statement. */
//check if user selection already exists, or whether it's the users first selection.
$sql = "SELECT COUNT(column_name_for_user_id) FROM your_table_name
WHERE user_id_column='$your_user_id_variable'";
$result_set = mysqli_query($conn, $sql);
$check = mysqli_fetch_array($conn, $result_set )[0];
if($check > 0)
{
$sql = "UPDATE your_table_name SET column_name_for_selection='$selected'
WHERE column_name_for_user_id='$your_user_id_variable'";
}
else
{
$sql = "INSERT INTO your_table_name SET column_name_for_selection='$selected'
AND column_name_for_user_id='$your_user_id_variable'";
}
mysqli_query($conn, $sql);
/* I would recommend that you look into
prepared statements and/or sanitizing inputs */
?>
Important: In terms of the user ID, I do NOT recommend parsing it through AJAX, as it is something that is handled client side, meaning that it is fully editable by the client through the browser's dev tools. Instead, use a session.
Example of session variable:
<?php
session_start(); //starts the session on the page.
$your_user_id_session_variable = $_SESSION['$your_logged_in_users_user_id'];
?>
You will need to set this session upon user login, where you fetch the users data upon login success, and set the session variable.
Now back to your <select>. We will have to check for what is selected. You will have to retrieve the selected value from the database, using your user's user ID to fetch it.
Remember what I mentioned about sessions.
Example:
<?php
//$conn is your connection variable
$sql = "SELECT column_name_for_selection FROM your_table_name
WHERE user_id_column='$your_user_id_sessin_variable'";
$result_set = mysqli_query($conn, $sql);
$selected = mysqli_fetch_array($conn, $result_set )[0];
?>
You can now use your $selected variable to check for what was selected by the user, and it will always have that as its default selection.
<select class="form-control" id="order_mode" name="order_mode">
<option value="fcfs" <?php if($selected == "fcfs"){ echo 'selected="selected"'; } ?> >First Come, First Serve</option>
<option value="pre-selling" <?php if($selected == "pre-selling"){ echo 'selected="selected"'; } ?> >Pre-Selling</option>
<option value="purchase-order" <?php if($selected == "purchase-order"){ echo 'selected="selected"'; } ?> >Purchase Order</option>
</select>
Please note, that you will need to declare:
<?php
session_start();
?>
at the beginning of every file where you wish to use the session(s).
And now for the last bit, your update button.
<button id="updateButton" name="updateButton" onclick="updateSelection();">Update</button>
Long post... but I hope it helped, or at least gave some insight to how it could be done.
Related
<select id = "test" name = "test">
<option value = "">default option </option>
<?php
$conn = mysqli_connect('localhost', 'root', '');
$result = mysqli_query($conn, 'SELECT id,name FROM center');
while ($row = mysqli_fetch_assoc($result))
{
$selected = (isset($_POST['list']) && $_POST['list'] == $row['id']) ? 'selected' : '';
echo "<option value='$row[id]' $selected >$row[name]</option>";
}
?>
</select>
<?php
if(isset($_POST['test']))
{
// unhide and display a bunch of stuff
}
Hi all, so my issue is that once the user submits the form. Leave the page and come back. The selected option in the while loop is still selected, however isset($_POST['test']) is no longer register so the code below no longer shows. So it just shows that one option, and the default option. (nothing to do or select cause isset(post) no longer set when they come to the page
The issue is that since the isset is no longer set the user can't do anything. even when page refresh. All they have is one select box option. But if the user select the same option before it would've generated the code in the if isset(post['test'])
I want it so that once the form has been submitted to reset the first select option to it's default option or show the second half when the user comes back to the page and the dynamic select option is still save
I apologize because my laptop is still broken and I can't copy and paste my code so I wrote some code and wrote a part of someone else code. I am trying to get my laptop fix as soon as possible but with the current situation I am having trouble getting it repair quickly
I'm making a movie rating website for a project and how to do the rating system has left me at a blank. Please let me know of a proper way to this if you know.
This gets the movie number from the url and displays the relevant information in the page
<body>
<?php
global $conn;
$conn = mysqli_connect('localhost','root','','filmsdb');
function show()
{
global $film;
global $conn;
$film = $_GET['fm'];
$sql = "SELECT * FROM movies WHERE m_No='$film'";
$ok = mysqli_query($conn,$sql);
$data = mysqli_fetch_array($ok);
$c_r= $data[8];
$c_rc= $data[9];
?>
//displays the movie information and uses radio buttons to get user rating
Then this lets the user rate the movie
<?php
}
function act1()
{
if(isset($_POST['rsub']))
{
global $film;
global $conn;
$rate = $_POST['rate'];
$sqlr= "UPDATE movies SET rating=rating+$rate, rate_count=rate_count+1 WHERE m_No='$film'";
$output = mysqli_query($conn,$sqlr);
}
if($output==1)
{
echo 'Data Stored';
}
else
{
echo 'Data Not Stored ';
echo mysqli_error($conn);
}
}
$conn = null;
?>
</body>
</html>
when only the first function is being used, it works, but when I try to use the rating system, this error comes in the browser, mysqli_query() expects parameter 1 to be mysqli, null given... Any idea on a workaround for this?
Your issue is that the two variables you're relying on with the DB connection, $conn and $film, do not exist when the page has posted back the user rating data.
Your application's lifecycle goes like this:
1) User makes initial request. PHP starts and runs the first code block, it echoes some values to the page, page is returned to the user. Once the page is returned, the request is complete and PHP stops executing. All variables declared and in memory are lost because the process has stopped running.
2) The page returned from the PHP script arrives in the user's browser. User enters their rating and posts the data back to the server. This constitutes an entirely new request.
3) The new request arrives at the server. PHP starts up again. The web is inherently stateless, so by default it remembers nothing of the previous request. Certainly not the names or values in any in-memory variables - the process that contained them died long ago and has no association with the new one.
Therefore, if you have any values that you need to use again in PHP for the second request, you can either create them again, or receive them in the request data, or the first PHP script must have stored them somewhere persistent that you can retrieve them from, such as a session variable or cookie, or database.
It's not clear from your posted code, but presumably in the second request the function act1() gets called somehow and tries to insert the data into the database. It fails because neither $film or $conn have any values in them in this new request.
I suggest you solve it like this:
1) Create your connection object again, this is easy, and you need to re-connect to MySQL for this request anyway.
2) the film you're rating should be passed back from the browser in the form data.
This is the first script, to get the initial film data and render the ratings form to the page.
//re-usable function to connect to DB. Maybe move this out to a separate file so all pages can use it.
function getDBConn() {
return mysqli_connect('localhost','root','','filmsdb');
}
function show()
{
$conn = getDBConn();
$film = $_GET['fm'];
$sql = "SELECT * FROM movies WHERE m_No='$film'";
$ok = mysqli_query($conn,$sql);
$data = mysqli_fetch_array($ok);
$c_r= $data[8];
$c_rc= $data[9];
$conn = null;
}
Your latest update doesn't show the form but I'm going to assume it's something like this, with an additional film hidden field. There should be suitable form tags around it as well.
<input type="radio" value="1" name="rate">
<input type="radio" value="2" name="rate">
<input type="radio" value="3" name="rate">
<input type="radio" value="4" name="rate"><input type="radio" value="5" name="rate">
<input type="hidden" name="film" value="<?php echo $film;?>"/>
<input type="submit" value="Rate" name="rsub">
Now is the second script, to be run when the rating data is submitted. You haven't shown how act1() is called but I'll assume you've got that covered.
function act1()
{
if(isset($_POST['rsub']))
{
$film = $_POST['film']; //get the film ID from the submitted form
$conn = getDBConn(); //assuming this script is in the same .php file as the first block, otherwise you'll need to move getDBConn into a separate php file and then include the file in each script.
$rate = $_POST['rate'];
$sqlr = "UPDATE movies SET rating=rating+$rate, rate_count=rate_count+1 WHERE m_No='$film'";
$output = mysqli_query($conn, $sqlr);
}
if ($output==1)
{
echo 'Data Stored';
}
else
{
echo 'Data Not Stored';
echo mysqli_error($conn);
}
$conn = null;
}
P.S. I know it's just an example project, but if you make a real-life site please heed the comments above re SQL injection, and don't let your applications and websites log into your DB as "root" either - give them only the privileges they actually need.
I have a post text website on http://www.youngcreatitivy.se
You see on http://www.youngcreativity.se/post.php that I have a post method. And on the bottom of the page I have like a option to choose which category your text is in. I've founded this code for inserting value from select box into my database. Here it is:
<?php
//insert category to database
if(isset($_POST['qty'])) {
// Fetch and clean the <select> value.
// The (int) makes sure the value is really a integer.
$qty = (int)$_POST['qty'];
// Create the INSERT query.
$sql = "INSERT INTO `table`(`quantity`)
VALUES ({$qty})";
// Connect to a database and execute the query.
$dbLink = mysql_connect('server', 'username', 'password') or die(mysql_error());
mysql_select_db('database_name', $dbLink) or die(mysql_errno());
$result = mysql_query($sql);
// Check the results and print the appropriate message.
if($result) {
echo "Record successfully inserted!";
}
else {
echo "Record not inserted! (". mysql_error() .")";
}
}
?>
Thats the Php code.
Here's the html code:
Qty: <select name="category">
<option value="1">Quote</option>
<option value="1">Poem</option>
<option value="1">Novel</option>
</select>
<br>
<input type="submit">
</select>
I understand the code, but how should I create the database in phpMyAdmin? And how can I get so that If I click submit after choosing the category and typed in my text it post the text and it writes which category I chosen in the database?
Please, help me!
I am guessing your first language is not English - 'Qty' is a common abbreviation for 'Quantity', so the code you are re-using is more about numbers.
You need to change the original <select> to something like -
<select name="category">
<option value="Quote">Quote</option>
<option value="Poem">Poem</option>
<option value="Novel">Novel</option>
</select>
As your code is, the select will only ever return 1.
Also, you need to escape the value returned before you store it in the database. mysql_real_escape_string is your friend in this case - http://php.net/manual/en/function.mysql-real-escape-string.php - otherwise you are open to sql injection.
If you are in localhost. Then you have to go to
http://localhost/phpmyadmin
There you find the way to create database and tables you can get easily. But you r in server if you have cokntrol panel there you see phpmyadmin with logo. There you click on that your phpmyadmin will be opened.Same as localhost. Hope this helps to you.
Ramsai
I am work on HTML and PHP on my project , but I have a problem :
I have a drop down list with countries and I want a nother drop down list to appear with (cities of this country) when user choose a country
I have the countries data base and cities data base ( sql )
I try to use a java script method to do that but it didnt work
this is my code
First : this is the countries drop down list it is work good :
<select name="SelectCountry" id="SelectCountry" onchange="showCity()" >
<?php
$Con= mysql_connect("localhost","root","");
if(!$Con) { die('Could not connect'.mysql_error());}
if(!mysql_selectdb("MyDB",$Con)){die(mysql_error());}
$sql = "SELECT * FROM countries";
$result = mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($result)){
echo ("<option value=\"".$row['CountryID']."\">".$row['Name']."</option>");
}
mysql_close($Con);
Second , this is the java script function showCity() // didnt work any way !!
<script>
function showCity()
{
alert("in the function !!");
Document.write(" <?php echo "<select 'SelectCity' ,'SelectCity'";
echo "</select>";
$theCountry=$_GET['SelectCountry']; // get the country ID
$Con= mysql_connect("localhost","root","");
if(!$Con) { die('Could not connect'.mysql_error());}
if(!mysql_selectdb("MyDB",$Con)){die(mysql_error());}
$sql = "SELECT * FROM cities WHERE cities.Fips=(SELECT Fips FROM countries WHERE CountryID='$theCountry')"; // retrive the cities for the spicific country (work when I enter the ID manully in the sql query e.g CountryID='43')
$result = mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($result)){
echo ("<option value=\"".$row['Fips']."\">".$row['Fullname']."</option>"); // print all the cities in a menu (work when I enter the ID manully in the sql query e.g CountryID='43')
}
mysql_close($Con);
");"; ?> ");
}
</script>
this method is to create a new dropdown list for the spicific country cities when the user change the country by using Onchange Event
I hope you will help me
if there any Questions or misanderstod I am ready to answer or explain
thaaaanks all :)
For your level of experience it would probably be best if all you do by onchange is to submit the form:
<select name="SelectCountry" id="SelectCountry" onchange="this.form.submit();" >
This is equivalent to pressing the submit button after selecting a country. (You are missing </select> in your excerpt by the way, although I expect you just didn't copy that here.)
Then in PHP have something like... (note this code bit needs to be before the dropdown boxes so that the variable is there when you want to echo it)
if ( isset($_GET['SelectCountry']) )
{
$country = $_GET['SelectCountry'];
$citySelect = "<select name='SelectCity'>";
//query DB for cities of that country
...
//now add the options from the query just like you did for the countries, except now use the cities
...
$citySelect .= "</select>";
}
else
{
$citySelect = ""; //to make sure the variable isn't undefined
}
Now you can just add underneath your CountrySelect:
<? echo $citySelect; ?>
If a country was chosen before, the city menu will show.
Note that this does not include even the lowest level of security, fool proofing and it can be very complicated to get a large form to work like this.
$_GET['SelectCountry'] only works when you have the selects in a form tag and you click the submit button to reload the page (which creates the $_GET variable. A simple way to do this would be to add the country to your address URL and that will give you a $_GET too.
So inside the showCity() function, write this:
var i = document.getElementById("SelectCountry").selectedIndex;
var countryValue = document.getElementById("SelectCountry").options[i].text;
window.location.href = '/?SelectCountry='+countryValue;
This will redirect your web page to mysite.com/?SelectCountry=USA or something like that. Then your code will work. This isn't the best way to do it, but it should give you some results.
This doesn't work because $_GET['SelectCountry'] is always going to be null. You're confused about the difference between client side and server side scripting. Once you load the page for the first time, there is no GET variable yet, and so your Javascript is sitting on the browser with no cities. Changing the country doesn't make the getCity() go back to the server. It just looks at what it has already, which is nothing. You need an AJAX function, which has the job of sending GET requests to the server and bringing back the results. Once it gets the list of cities, its going to want to know what you want it to do with that list. You give it a function that makes a dropdown out of them. This is known as a callback. There are a lot of tutorials out there telling you how to make an AJAX function and where to put the callback.
i write a command, or i fill up parameter value from user input field. click the button, send this command to php and send resultant value back to html to display.
for example. on html page :
select ___ from ____,
two available input field i fill up with "tablenameone" and "valueone". then, result will be printed on html text field on the same page.
what i do know is those value can be sent(perhaps) as in such format
$('input[name="talbename"]')
$('input[name="value"]')
example.com?tablename=tablenameone&value=valueone
and from php side i use
$sql="SELECT '$_GET['value']' FROM '$_GET['tablename']';
what i dont know is that....how exactly should i perform this in a click function? its for sure using ajax. but how can i produce example.com?tablename=tablenameone&value=valueone
and where should i put $('input[name="value"]')
thanks in advance :D
You must not use direct input in your queries as you will be open to SQL injection attacks.
$sql="SELECT '$_GET['value']' FROM '$_GET['tablename']';
Instead, use the following:
$column = $_GET['value'];
$table = $_GET['tablename'];
$sql = sprintf("SELECT %s FROM %s;",
mysql_real_escape_string($column),
mysql_real_escape_string($table));
Although you are still exposing too much "inside information" by giving people a page that tells them all of your table and column names!
Anyway, here is a complete example;
<form method="post" action="">
<fieldset>
<legend>Select Data</legend>
<p><label>Table<br>
<select name="table">
<option value="tblStudents">Students</option>
</select></label></p>
<p><label>Table<br>
<select name="column">
<option value="firstname">First Name</option>
<option value="lastname">Last Name</option>
</select></label></p>
<p><input type="submit" name="submit" value="submit">
</fieldset>
</form>
<?php
$connection = mysql_connect("servername:3306", "user", "password") or die ('Error connecting to mysql');
mysql_select_db("databasename");
$column = mysql_real_escape_string($_POST['column']);
$table = mysql_real_escape_string($_POST['table']);
$sql = sprintf("SELECT %s FROM %s;",
$column,
$table);
$result = mysql_query($sql) or die(mysql_error());
echo '<ul>';
while($row = mysql_fetch_array($result)) {
echo '<li>' . $row[$column] . '</li>';
}
echo '</ul>';
mysql_close($connection);
?>
Seeming as though noone has actually answered the question (although they are all good points, I will assume there is a reason for you doing this), I will answer:
$('form[name=formname]').submit(function(e){
e.preventDefault;
var tablename = $('input[name="tablename"]').val();
var value = $('input[name="value"]').val();
$.get("example.php?tablename="+tablename+"&value="+value, function(data){
$('body div').text(data);
})
});
PHP:
$sql=mysql_query("SELECT '$_GET['value']' FROM '$_GET['tablename']'")or die(mysql_error());
$sqlOutput = mysql_fetch_array($sql);
echo "<pre>";
print_r($sqlOutput);
echo "</pre>";
Obviously replace formname with your form name, body div with the name of the element you want the output to go in and all other identifiers replaced where seen fit. Then change the output in the PHP to suit your needs.
Again, do bear in mind the posts regarding SQLi, because you have yourself a very serious problem there.
You really want to make sure you are not open to SQL injection.
You could use mysql prepared statements
or
use the php function mysql_real_escape_string($_GET['value'])
Read this thread:
How can I prevent SQL injection in PHP?
I'm not sure what you mean by the click function.