Insert value from select box into database - php

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

Related

dropdown box value's default value shows what is saved in database.

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.

php mysql select option

I am having problems with my code.
I have a registration form which works fine apart form one area. The select option the user should select 'Yes' or 'No' from the options and then it should insert this 'Yes' or 'No' into the mysql database. Due to my code error it is not inserting anything. can you help me as to where i am going wrong please.
registration page code has this html among the form
<form action="register.php" method="post" autocomplete="off">
<label>Member<span class="req">*</span></label>
<select name="member">
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</form>
this is then posted to my php page which has this code
<?php
$member = $mysqli->escape_string($_POST['member']);
$sql = "INSERT INTO members (member) "
.
"VALUES('$member')";
?>
obviously this is due to my lack of experience and is probably a really stupid mistake i have made but cannot see. I have spent a few days trawling around trying to get the answer but without any success.
Many Thanks
Use prepared statements. You won't need to escape string anymore.
$query = "INSERT INTO members (member) VALUES(?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s",$_POST['member']);//bind parameter to placeholder
return $stmt->execute() === true ? true : false;
You have written the query but have not executed it.
Use $mysqli->query($sql); to run the query.
Check this:
$sql = "INSERT INTO members (member) VALUES ('$member')";
$mysqli->query($sql);

Inserting data in Mysql database

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.

INSERT query returns TRUE but does not work?

I am trying to build an INSERT record query where the user can add new entries to the database using two drop down menus. The way this works is that, depending on who has logged in, $_SESSION variables take over and show the correct information in the drop down menus.
What I want it to do is, once a member of staff from a school has logged on, chosen the Subject Area and chosen the Year Group they want to manage, it shows two dynamic drop down menus with all the possible teachers that can teach that specific subject in the first menu, and a list of all the subject classes in that year in the second menu. The user can then select a teacher and a class and press the submit button to send the query off to the database for entry.
When prompted by the IF-command to test if the query worked, it recognizes the query as if it was TRUE, echos the SUCCESS line and redirects to previous page:
$result = $query_addteacher;
if (!$result) {
die('Invalid query:'. mysql_error());
}
else
{ echo "Success!";
header("location:addteachertest.php"); }
But the data hasn't actually been fed into the database at all. Below is the code for both the drop down menu's and the query:
// Connect Command //
mysql_connect($host, $username, $password) OR die("Can't connect");
mysql_select_db($database_name) OR die("Can't connect to Database");
$teacher = $_POST['teacher'];
$class = $_POST['class'];
// Query to insert data into the staffclass table //
$query_addteacher = "SELECT #staff := idStaff FROM Staff WHERE Staff = '$teacher', #class := idClass
FROM Class WHERE Class = '$class';
INSERT INTO Staffclass (idStaff, idClass)
VALUES ($teacher, $class)";
Teacher:
<select name="teacher" id="teacher" form="addteacher" title="Teacher">
<?php do { ?>
<option value="<?php echo $row_teacherlist['Staff']?>"><?php echo $row_teacherlist['Staff']?>
</option>
<?php
} while ($row_teacherlist = mysql_fetch_array($teacherlist));
$rows = mysql_num_rows($teacherlist);
if($rows > 0)
{
mysql_data_seek($teacherlist, 0);
$row_teacherlist = mysql_fetch_array($teacherlist);
}
?>
</select>
Class:
<select name="class" id="class" form="addteacher" title="Class">
<?php do { ?>
<option value="<?php echo $row_classlist['Class']?>"><?php echo $row_classlist['Class']?></option>
<?php
} while ($row_classlist = mysql_fetch_array($classlist));
$rows = mysql_num_rows($classlist);
if($rows > 0) {
mysql_data_seek($classlist, 0);
$row_classlist = mysql_fetch_array($classlist);
}
?>
</select>
I have a gut feeling that there is something wrong with the way I want the query to operate, by using straightforward MySQL commands. It works in this format (albeit the variables for teacher and class are not variable) when I enter it manually into MySQL so I wonder what I am doing wrong via PHP. Many thanks in advance!
$query_addteacher = "SELECT #staff := idStaff FROM Staff WHERE Staff = '$teacher', #class := idClass
FROM Class WHERE Class = '$class';
INSERT INTO Staffclass (idStaff, idClass)
VALUES ($teacher, $class)";
there are two queries in this fragment.
try query them seprately
$result = $query_addteacher;
You have not run a query, $result will evaluate to true as it is a string that evaluates to true.
$result = mysql_query($query_addteacher); // maybe?
Also, stop with mysql_() funcs and use mysqli or PDO.
You cannot just set the result to the query variable. The query has to be executed on the server.
Consider doing something like this:
$result = mysql_query($query_addteacher);

how to perform sql command on html page with user input field, and show result on the same page

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.

Categories