How to use the form value in php function? - php

I am newbie to php.I have coded auto-complete text box using php,and i have a submit button.i have not given form action.
This is the HTML form code that i used for autocomplete textbox.this autocomplete textbox selects the value
<form method="post" autocomplete="off">
<p>
<b>Theater Name</b> <label>:</label>
<input type="text" name="theater" id="theater" />
</p>
<input type="submit" value="Submit" />
</form>
I have another php function that retrieves the values based on where clause.in the where statement i want to use selected value from form.
for ex: select address from theaters where theater_name ="form value"
How to use the form value in php function?can any one help me?
<?php
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("theaterdb", $con);
$result = mysql_query("SELECT * FROM theter
WHERE theater_name="<!-- This could be value that we get after clicking submit button-->);
while($row = mysql_fetch_array($result))
{
echo $row['thearer_name'];
echo "<br />";
}
?>
Thanks in advance......

You could get the value from $_POST by $_POST['theater'].
And note, you should not use this value directly in the sql, you need to escape it to prevent sql injection.
$theater = mysql_escape_string($_POST['theater']);
$result = mysql_query("SELECT * FROM theter WHERE theater_name='$theater'";
Last, you could take a look at PDO, which is suggested over the old mysql_* functions.

First, change your submit button code to the following:
<input name="submit" type="submit" value="Submit" />
Now, this is the code you should use for the query:
<?php
if (isset($_POST['submit'])) {
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("theaterdb", $con);
$result = mysql_query("SELECT * FROM theater
WHERE theater_name='" . mysql_real_escape_string($_POST['theater']) . "'");
while($row = mysql_fetch_array($result))
{
echo $row['theater_name'];
echo "<br />";
}
}
First, I check that the user submitted the form. Then, I escape the data he has submitted and inserting it into your query.
* NOTE: All of what I've wrote is based on the assumption that the code is executed after the form is submitted.
* ANOTHER NOTE: You should read about using PDO rather than MYSQL functions.

First and foremost, try using mysqli instead of mysql (mysqli_query, mysqli_connect). There are numerous security / speed advantages to using it and it has pretty much the exact same functionality.
While the above answers mention using $_POST['theater'] (the name of your input), be SURE to escape your post before putting it into your query.
$con = mysqli_connect("localhost","root", "YOUR PASSWORD HERE", "YOUR DATABASE HERE");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
// No need for this, please see the updated mysqli_connect as the 4th parameter selects your DB
//mysqli_select_db("theaterdb", $con);
// Please notice the last parameter of the mysqli_real_escape_string is your Input's POST
$query = "SELECT * FROM theater WHERE theater_name=".mysqli_real_escape_string($con, $_POST['theater']);
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result))
{
echo $row['thearer_name'];
echo "<br />";
}

$_POST["your_variable_name"] // for POST
$_GET["your_variable_name"] // for GET
For in-depth information please go to: http://www.php.net/manual/en/language.variables.external.php

Related

Opencart Custom mysql search form

I am creating a simple custom search form. This form searches the table 'oc_product' where i created a new column 'gcode'. I have inserted a sample data in this column for one of the products. Is it necessary to make a new db/mysql connect in php within a new tpl file i created just like 'information/contact'. I call this 'gcode/gcode'.
I tried but unable to get result form the search. It redirected to index.php.
My code is:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="searchform">
<input type="text" name="name">
<input type="submit" name="submit" value="Search">
</form>
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("/^[ a-zA-Z]+/", $_POST['name'])){
$name=$_POST['name'];
//connect to the database
$db=mysql_connect ("localhost", "username_demo", "pwddemo123") or die ('I cannot connect to the database because: ' . mysql_error());
//-select the database to use
$mydb=mysql_select_db("db_demo");
//-query the database table
$sql="SELECT * FROM oc_product WHERE gcode LIKE '%" . $name . "%'";
//-run the query against the mysql query function
$result=mysql_query($sql);
//-create while loop and loop through result set
while($row=mysql_fetch_array($result)){
$gcode =$row['gcode'];
//-display the result of the array
echo '<span>'."This product is genuine".$gcode.'</span>';
}
}
else{
echo "<p>Please enter a search query</p>";
}
}
}
Any example to search a column and fetch data from a column.
Don't quite understand your question. Do you want to fetch data from ONE column? Also use mysql_fetch_assoc instead mysql_fetch_array
And replace $_GET with $_POST
Also your select statement is wrong, so do this:
<?
$sql="SELECT * FROM oc_product WHERE gcode LIKE '%$name%'";
$result = mysql_query($sql);
$results = mysql_num_rows($result);
for($i=0; $i<$results; $i++)
{
$row = mysql_fetch_assoc($result);
$gcode = $row['gcode'];
// Here list it the way you want
echo $gcode.'<br>';
}
?>
you would need to create a model or simply add this field in the search model to be searched by it. i am not sure if that is what you want to accomplish, also you would want to make sure to sanitize the request and escape it before you get one of the SQL injection attacks.

Form get's resent on refresh

Form get's resent on refresh, I had read about header("Location:my_page.php") unset($_POST), but I'm not sure where to place it.
This is our script, it works as need it, but it keeps re-sending on page refresh (Chrome browser alerts over and over), can some one fix the code and explain to my like 2 years old child.
<form action='thi_very_same_page.php' method='post'>
Search for Christian Movies <input type='text' name='query' id='text' />
<input type='submit' name='submit' id='search' value='Search' />
</form>
<?php
if (isset($_POST['submit']))
{
mysql_connect("localhost", "root", "toor") or die("Error connecting to database: " . mysql_error());
mysql_select_db("db_name") or die(mysql_error());
$query = $_POST['query'];
$min_length = 2;
if (strlen($query) >= $min_length)
{
$query = htmlspecialchars($query);
$query = mysql_real_escape_string($query);
echo "";
$result = mysql_query("SELECT *, DATE_FORMAT(lasteditdate, '%m-%d-%Y') AS lasteditdate FROM movies WHERE (`moviename` LIKE '%" . $query . "%') OR (`year` LIKE '%" . $query . "%')") or die(mysql_error());
if (mysql_num_rows($result) > 0)
{
while ($results = mysql_fetch_array($result))
{
echo "";
}
}
else
{
echo "";
}
}
else
{
echo "";
}
}
If you mean that the form data gets submitted again upon refresh, check this method
http://www.andypemberton.com/engineering/the-post-redirect-get-pattern/
You set your header to header('HTTP/1.1 303 See Other');
Data wont be cached, so when page refreshes the form data wont get submitted again!
The problem is you are using the post method to submit the form values so when ever you tries to refresh the browser asks you whether to send the form information or not it is the default behavior of the browser to tackle the posted information, the alternate solution for your problem is you can use the get method like in form attribute method='get' what it does it will append all the information of form in the URL which we call the query string and in PHP code you are accessing the form values in $_POST but when using get method the form values will now appear in the $_GET method these methods are called request method and are PHP's global variables, Now when you try to refresh it will not ask you to resend information because the information now resides in the URL
<form action='thi_very_same_page.php' method='get'>
Search for Christian Movies <input type='text' name='query' id='text' />
<input type='submit' name='submit' id='search' value='Search' />
</form>
<?php
if (isset($_GET['submit']))
{
mysql_connect("localhost", "root", "toor") or die("Error connecting to database: " . mysql_error());
mysql_select_db("db_name") or die(mysql_error());
$query = $_GET['query'];
$min_length = 2;
if (strlen($query) >= $min_length)
{
$query = htmlspecialchars($query);
$query = mysql_real_escape_string($query);
echo "";
$result = mysql_query("SELECT *, DATE_FORMAT(lasteditdate, '%m-%d-%Y') AS lasteditdate FROM movies WHERE (`moviename` LIKE '%" . $query . "%') OR (`year` LIKE '%" . $query . "%')") or die(mysql_error());
if (mysql_num_rows($result) > 0)
{
while ($results = mysql_fetch_array($result))
{
echo "";
}
}
else
{
echo "";
}
}
else
{
echo "";
}
} ?>
Hope this is enough to explain you about the form submission one thing I will suggest you to deeply look at below
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Setting variable from combo box

How do I get the value in the combo box and store it in a variable? And use the variable in another PHP file? Here is my code.
Note: I am already able to get data from database and store it in the combo box.
$con = mysql_connect("localhost","root","aaaa");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("maptemp", $con);
$sql = "SELECT * FROM users";
$rs = mysql_query($sql) or die(mysql_error());
$selectbox='<select name=\'userst\'>';
while ($row = mysql_fetch_assoc($rs)) {
$selectbox.='<option value=\"' . $row['username'] . '\">' . $row['username'].'</option>';
}
$selectbox.='</select>';
mysql_free_result($rs);
echo $selectbox;
How do I get the value in the combo box and store it in a variable?
Assuming you are talking about a plain select element.
Submit the form it is in
Read $_POST['foo'] or $_GET['foo'] where foo is the name of the select element
And use the variable in another PHP file?
include that file
Store the data in a session
Redirect to that file while passing the data in the query string
various other options depending on precisely what you want to acheive

Grabbing a value from a SELECT box in PHP

I've got a drop down select box that grabs each relevant value from an SQL database in a loop.
I'm creating a form so that when the "Submit" button is pressed it redirects to a PHP file that carries out the INSERT SQL statement. However because the select options are coming from a loop I'm unsure of how to grab the right value when its selected as it just grabs the last value gained from the loop.
I'm pretty sure that the way I have done it is the wrong way to go
<?php
echo"<select name='ModuleTitle' id='ModuleTitle' style='width:100%;'>";
echo"<option>Select...</option>";
//3. Perform database query
$result = mysql_query("SELECT * FROM Module
ORDER BY `ModTitle` ASC;", $connection);
if(!$result){
die("Database query failed: " . mysql_error());
}
//4. Use Returned Data
while ($row5 = mysql_fetch_array($result)) {
$module = $row5[2];
echo "<option name='{$module}'>".$row5[2]."</option><br />";
}
echo"</select>";
echo "<a href='submitREQ.php?id={$module}'><img src='images/submit.jpg' height='27'></a>";
?>
Instead of using <a href you should use <input type="image" value="submit" src="images/submit.jpg" />
To grab the value after the form is submitted you should use: $ModuleTitle = $_POST['ModuleTitle']; or $_GET if the method is get.

php drop down list

i’m new to codeigniter and i’m working on a project. i have to create a dynamic drop down menu with values from my database, when a selection is made in the drop down as soon as you click on the submit button a new page has to occur where all the cities associated with the province selected in the drop menu appear, the cities are also in my database .My database consists of an id field, province field and a cities field.The drop menu is fine but cant seem to make the cities appear in the next page. your help will be highly appreciated
ok here's my code
this is from my view file which displays my drop menu this side is ok
<?
function writeCities($id)
{
$con = mysql_connect("localhost","root","");
if (!$con) die('Could not connect: ' . mysql_error());
mysql_select_db("msansi", $con);
$query = "SELECT cities FROM provinces WHERE id =";
$query .= $id;
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo $row[0];
}
function populateDropBox()
{
$con = mysql_connect("localhost","root","");
if (!$con) die('Could not connect: ' . mysql_error());
mysql_select_db("msansi", $con);
$result = mysql_query("SELECT id,title,cities FROM provinces");
while($row = mysql_fetch_array($result))
{
echo "<option value=$row[0]>" . $row['title']."</option>";
}
}
?>
<form name="myform" action="http://localhost/CodeIgniter_1.7.3/index.php/ndivhuho/submit" method="post">
<select name = "province" onChange="onChangeDropBox();"/>
<? populateDropBox(); ?>
<input type="submit" value="submit"; />
</form>
and here's my other view file which is supposed to display the cities in a text area
<?
function writeCities($id)
{
$con = mysql_connect("localhost","root","");
if (!$con) die('Could not connect: ' . mysql_error());
mysql_select_db("msansi", $con);
$query = "SELECT cities FROM provinces WHERE id =";
$query .= $id;
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo $row[0];
}
?>
<script type="text/javascript">
function onChangeDropBox()
{
var selected =0;
selected = document.myform.province.value;
var t = "<? writeCities(1);?>";
document.myform.textArea.value = t;
}
</script>
<form name=myform>
<textarea name="citites" readonly="true";></textarea>
</form>
i'm sure theres something i need to do in my controller which i don't know of
thanxx in advance!!!
Take a look at the following two guides on how to do what you're talking about doing:
http://php-ajax-code.blogspot.com/2007/07/ajax-triple-dropdown-with-states-cities.html
http://roshanbh.com.np/2007/12/change-dropdown-list-options-values-from-database-with-ajax-and-php.html
There are a few problems here.
The code you have provided is using native php functions to connect to mysql. You should be using the proper CodeIgniter libraries. Start by reading this.
http://codeigniter.com/user_guide/database/examples.html
Once you've read that..
"this is from my view file which displays my drop menu"
Take the code out of your view file! The database calls should be in a model, and that should be called by a controller, which passes the data through to your view file.
Probably read this too:
http://en.wikipedia.org/wiki/Model%E2%80%93View%E2%80%93Controller

Categories