I have created a drop down list as well a input type for for category and name but in both the case as i click next it directs me to another page but nothing saves in my database.
company_account is the table name in which data has to be inserted it has four rows id, category, cname, about
<?php include( "./inc/header.inc.php");
require( "./inc/connect.inc.php"); ?>
<div>
<form action = "payment.php" method= "POST">
<select id="category" name="category" class="old_ui_selector">
<option value="0" selected="1">Choose your category</option>
<option value="">Accounting Firm</option>
<option value="">Agriculture</option>
<option value="">Automotive</option>
<option value="">Aerospace/Defence</option>
<option value="">Building Material</option>
</select>
</div>
<br>
<input type = "text" name="cname" placeholder= "Name"/>
<br><br>
By clicking Next you agree to the Terms and Conditions.
<br>
<input type = "submit" name="comp" value="Next"/>
</form>
<?php
if(isset($_POST['comp']))
{
$category=$_GET['category'];
$cname = $_POST['cname'];
$ins=mysql_query("insert into company_account (category) values ('$category')");
$insert = mysql_query("INSERT INTO company_account VALUES ('','$category','$cname','$about')");
if($ins)
if($insert)
{
echo "<br>".$category."inserted";
}
else
{
echo mysql_error();
}
}
?>
You have a few issues there, the first is you are using mysql, either update it to mysqli or better still PDO.
Second your form is submitting using POST and yet you try to collect the category using GET.
You also need to supply the contents of your connect.inc.php WITHOUT THE IP AND PASSWORD so people can have a look at the config.
I would suggest before going any further you have read here and get a better understanding before you proceed.
https://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
Best of luck.
Note: mysql: This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.
You have provided with the form action and that will redirect after clicking the submit button.
You have written the INSERT STATEMENT in the same page itself and that will not even work for you.
First Remove up the action="" and then you redirect it based on the data saved.
HTML:
<form action = "" method= "POST">
</form>
And you Option value is missing out values and after the form is submitted the values will not be entered into the DB. Hence you need to do the following.
Replace:
<option value="">Accounting Firm</option>
With:
<option value="Accounting Firm">Accounting Firm</option>
PHP Code for Insert:
You Insert Code will not work since you have not provided with the table values for insert operations.
Syntax:
INSERT INTO TABLENAME(`columnname1`,`columnname2`,.....) VALUES(VALUE1,VALUE1,....)
Hence you are advised to use the correct table structure for the Operations and then insert the data.
INSERT QUERY:
$insert = mysql_query("INSERT INTO company_account(`category`,`name`,`about`) VALUES ('$category','$cname','$about')");
You can insert all in the single query itself and then redirect using the header location.
Use header Location for redirection to particular page after the data has been saved.
header('location : http://www.google.co.in');
PHP PART:
<?php
if(isset($_POST['comp']))
{
$category=$_POST['category'];
$cname = $_POST['cname'];
$insert = mysql_query("INSERT INTO company_account(`category`,`name`,`about`) VALUES ('$category','$cname','$about')");
$rows = mysql_affected_rows();
if($rows=0)
{
echo mysql_error();
}
else
{
ob_start(); // Refresh the Output Buffer
header('location: http://www.google.co.in');
exit;
}
}
?>
Note: $about you are using in the Insert Statement but no values are provided over to the Insert Statement. Please check to that.
Related
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.
so I've finally figured out how I can get values from my mySQL-db into a dropdown form in PHP. My problem is, how can I use/work with the option that was selected by the user?
My goal is a functioning email-signature generator. I want the user to be able to insert unique data like their name, and select the office where they work from the dropdown form. After they hit the submit button, they should then be lead to the next site that displays their name with the signature for the selected office.
The name is no problem, that is only a simple html-form with a post method, I know how I can retrieve and access that.
But how can I work with the option that was selected by the user in the dropdown?
After selecting an option and hitting submit, the whole "row" in the mySQL-db should be displayed, in formated form.
My current situation is that the dropdown shows the correct values from the mySQL-db, and the two name fields, that are also working as they should.
The name of the mySQL database is "firmen", the name of the column I use is "niederlassung".
I'm happy to provide more information if needed.
My code:
[...]
<form action="php-verarbeitung.php" method="post">
<div>
<label for="1">Vorname: </label>
<input type="text" name="vorname" id="1" value=""><br><br>
</div>
<div>
<label for="2">Nachname: </label>
<input type="text" name="name" id="2" value=""><br><br>
</div>
<input type = "submit" name = "button" value = "Senden"><br><br>
<?php
// Establish mySQL PDO Connection
$server='mysql:host=*****.com.mysql;dbname=*****'; // Host and DB-Name
$user="******"; // Username
$password="*****"; // Password
$pdo=new PDO($server, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Write out the query
$query = "SELECT niederlassung FROM firmen";
// Execute it, or let it throw an error message if there's a problem
$stmt = $pdo->query($query);
$dropdown = "<SELECT name='firmen'>";
foreach ($stmt as $row) {
$dropdown .= "\r\n<option value='{$row['niederlassung']}'>{$row['niederlassung']}</option>";
}
$dropdown .= "\r\n</select>";
echo $dropdown;
?>
</form>
</body>
</html>
Thanks for any help in advance!
you are passing the variables through the form to php-verarbeitung.php. On that page you can load the content based on the $_POST variables that are sent through the form. so you can query the DB again on the second page to get the info you need, and present formated html using the values from the form passed through the post array, in your case
$_POST['vorname'], $_POST['name'] and $_POST['firmen'] should all be accessible when the php-verarbeitung.php page is called using your script above.
I've searched on the Internet to get my answer, but I couldn't find a helpful one. I've got a page called 'post.php' with a form where I can add an image and submit it to the database.
The big problem is when I go to mysite.com/post.php a new empty row is created automatically in the database, which I clearly don't want. I want only to update the database after clicking on the submit button my code:
the part of INSERT:
<?php
// POST.PHP POSTING NEW CONTENT
include 'config.php';
// values from form
$id=$_POST['id'];
$title=$_POST['title'];
$pic=$_POST['pic'];
$youtube=$_POST['youtube'];
$cat=$_POST['cat'];
// insert data to mysql
$sql = "INSERT INTO post(id, title, pic, youtube, cat)VALUES('$id', '$title', '$pic', '$youtube', '$cat')";
$result=mysql_query($sql);
// succes added
if(!$result){
echo "Something went wrong!";
}
else {
echo "Yeah, buddy! Your content is added.";
}
// end of post script ^^
?>
// end of insert
//POST IMAGE PAGE
if(isset($_GET['pic'])) {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
title: <input name="title" type="text" id="title"><br />
Add url of image;<br />
<input type="text" name="pic" id="pic"/><br />
<?php
echo '
Category game:
<select name="cat"> ';
$query2 = mysql_query("SELECT * FROM `category`");
while($row=mysql_fetch_array($query2)){
echo '
<option value="'.$row["nameID"].'">'.$row["name"].'</option> ';
}
?>
</select>
<input type="submit" onclick="this.disabled = true" name="submit" value="submit">
</form>
<?php
// end script of posting picture
}
?>
You need to add some conditional code around the part that inserts into the database, checking for if any values has been received (if($myvar){ // do stuff }).
Add the rest of your code, specifically the part that adds stuff to the database as that is what's causing you problems, not the code you posted.
You need to wrap the whole block of database insertion code in an if statement. That way, it will not execute until the form has been submitted and $_POST['submit'] has a value:
include 'config.php';
if (isset($_POST['submit'])){
// values from form
$id=$_POST['id'];
// etc... code stays the same down to:
echo "Yeah, buddy! Your content is added.";
}
}//end if (don't forget to add this last bracket)
Also, you should switch to mysqli or PDO, and use parameterized queries. Otherwise, your site is open to a variety of gnarly attacks via SQL injection. It's not that hard to switch, and very, very important.
Check if the post have been set on the file that handles the database input.
if(isset($_POST['pic'])){
//do something
}
else{ // handle the exeption}
Also, you should not use mysql_* functions anymore. they are unsafe and deprecated as-of php 5.5
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 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.