I want to get some variables from a form and i will use those variables to make a search bar for example:
$var=$_POST['var']
I want to put this variable in a request like this:
$SQL = 'SELECT * FROM Table ORDER By $var'
Any suggestions please? How can I transform this request to a dynamic request? thank you :)
The code is:
<form>
<lable for="Variable">
<input type ="text" name="variable" placeholder="Search by : ">
</form>
<?php
$variable = $_POST['variable']
sql = 'SELECT * FROM Total ORDER BY $variable';
?>
Please refer to PDO and for order by review.
your select query would be
SELECT * FROM yourtable ORDER BY DATABASE_FIELD;
At first,
use method="POST" and action="file.php" (but action is not strictly needed, in some cases like processing by AJAX)
<form method="POST" action="file.php">
<lable for="Variable">
<input type ="text" name="variable" placeholder="Search by : ">
</form>
At second you need sanitize input taken from form (it means, you have to eliminate anything that would harm your pages - with this PDO or else layer can help).
At third, you need to rewrite
sql = 'SELECT * FROM Total ORDER BY $variable'
to
sql = "SELECT * FROM Total ORDER BY $variable"
or
sql = 'SELECT * FROM Total ORDER BY '.$variable
because else used variable would be used as is written, instead its content (given by form).
Since you're new it would be wise to embed some good practices from the start. Documentation for reference would be PDO and Prepared Statements.
An example PDO tutorial can be found on W3Schools, along with a tutorial on handling form data with PHP.
This is an example of a simple search
PHP:
<?php
$search = $_POST["search"];
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM `profile` WHERE `email`='$search'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
HTML:
<form action="profile.php" method="post">
<input type="text" name="search"><br>
<input type="submit">
</form>
Hope it helps
Related
I have a column vehicle_name and I would like 2 dropdown lists of my 2 other columns namely, vehicle_type and vehicle_color.
When these 2 dropdown values are selected and submitted, I would like their intersection to print out the values from vehicle_name. So far my code only generates a dropdown list for vehicle_type, I would need another dropdown for vehicle_colour. Which on submissions populates the intersected values for the vehicle_name. How can I achieve this?
<!DOCTYPE html>
<html>
<body>
<?php
echo "<br>";
echo "<br>";
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
$db = new mysqli($servername, $username, $password, $dbname);
if (!$db) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
?>
<br>
<div class="label">Select vehicle type:</div>
<select name="payment_method">
<option value = "">---Select---</option>
<?php
$queryusers = "SELECT DISTINCT vehicle_type FROM orders";
$db = mysqli_query($db, $queryusers);
while ($d=mysqli_fetch_assoc($db)) {
echo "<option value='{".$d['vehicle_type']."}'>".$d['vehicle_type']."</option>";
}
?>
</select>
<br>
<div class="label_for_time">Select color:</div>
<select name="vehicle_color">
<option value = "">---Select---</option>
<?php
$query_for_color = "SELECT DISTINCT vehicle_color FROM orders";
$db = mysqli_query($db, $query_for_date);
while ($a=mysqli_fetch_assoc($db)) {
echo "<option value='{".$a['vehicle_color']."}'>".$a['vehicle_color']."</option>";
}
?>
</select>
<br>
<br>
<button class="go-btn" type="submit">Go</button>
</body>
</html>
As I don't see any AJAX / client-side code in your above example I assume that this is a pure backend-side filtering you are performing. Your code is currently missing parts of the required elements we would need but let's try to figure this out together:
1. Form around your inputs
Add a <form method="POST" target="path-to-your-script.php"> where "path-to-your-script.php" has to be changed to your PHP file name or rewritten URL path. This has to be around the <select> boxes.
You may also use PHP_SELF to set this automatically, this should work in most cases. I used html_entities($var) to avoid any code injections via manipulated URL.
<form name="test" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
2. Check for POST'ed variable 'vehicle_type'
In your form, check if a search for available colors has been performed:
<?php
$query_for_color = "SELECT DISTINCT vehicle_color FROM orders";
// check if the form variable 'vehicle_type' is available; if so, filter entries.
if (isset($_POST['vehicle_type'])) {
$vType= filter_var($_POST['vehicle_type'], FILTER_SANITIZE_STRING);
$query_for_colors .= ' WHERE vehicle_type = \''.$vType.'\'';
}
$db = mysqli_query($db, $query_for_date);
while ($a=mysqli_fetch_assoc($db)) {
echo "<option value='{".$a['vehicle_color']."}'>".$a['vehicle_color']."</option>";
}
?>
Edit:
As pointed out by one user in the comment, filter_var($var, FILTER_SANITIZE_STRING) won't be enough to avoid potential SQL injections. This was just a recommendation and was not part of the question at all. If you have to work with user data, do more than using filter_var(), instead use either prepared statements or properly escape the user data. There are many tutorials like this one out there that will guide you to safe queries.
I'm working on a fantasy football database just for fun and I have made some progress with a PHP page but am stuck with an issue in getting data from my html data to be read by my php update script (update.php)
Here's my code for the form:
$servername = "localhost";
$username = "root";
$password = "nottelling";
$dbname = "Football";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$sqlqb = "SELECT Name_Team_Position FROM Football.2016_Players_QB;";
$resultqb = $conn->query($sqlqb);
echo " <form method=\"post\" action=\"update.php\"> <br> Enter Passcode:";
echo " <input name = \"Passcode\" type = \"text\"> </input> <br><br> ";
echo " Pick your QB: <select name='QB'> </option> "; // list box select command
foreach ($conn->query($sqlqb) as $row){
// Array or records stored in $row
echo " <option value=$row[id]>$row[Name_Team_Position]</option> ";
/* Option values are added by looping through the array */
}
echo " </select> ";// Closing of list box
echo " <br><br> <input type=\"submit\" value=\"Submit\"> </input> ";
echo " </form> ";
$conn->close();
?>
And here's update.php
$servername = "localhost";
$username = "root";
$password = "nottelling";
$dbname = "Football";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$value1 = $_POST['Passcode'];
$value2 = $_POST['QB'];
$sql = "UPDATE Football.PlayerTeams SET QB = '$value2' WHERE Password = '$value1';";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
My problem as concisely as I can put it:
This script is definitely connecting properly to the DB and executing the update query successfully. The problem is that $value1 is not receiving any value from the html form. If I insert the string "test" into the row corresponding with the passcode, and then I use the form this code producing, it runs successfully but then when I check the db "test" is gone and instead its just blank - "". Can someone help me figure out what I'm doing wrong in trying to get the drop-down value to my action script?
This is wrong:
echo " Pick your QB: <select name='QB'> </option> ";
The </option> are wrong placed
Replace: echo " Pick your QB: <select name='QB'>";
Replace: echo " <br><br> <input type=\"submit\" value=\"Submit\">";
The $row['id'] is the value that you become in your QB if your POST.
echo " <option value='TheValueYouNeededHere'>Display Name</option> ";
And for POST use filter_input — Gets a specific external variable by name and optionally filters it:
filter_input(INPUT_POST, QB, filter);
The filters you find here: http://php.net/manual/de/filter.filters.php
Copy from User:
$sql = "UPDATE Football.PlayerTeams SET QB = '".$value2."' WHERE Password = '".$value1."'";
Is more beautiful for the eyes, you must not use ".$Value." In php works without i mean, correct me when i'm wrong
Security:
Your MySQL query can easy injected. And your passwort is Visible.
It gives multiple choices to avoid this.
MySQL injecton:
You can replace some char's. (Char are single character)
The most dangerous things you can replace with other characters. Filter Input have nice filters like htmlspecialchars. I Think you find much things if you search little :)
Password:
First make <input type='password'>.
Then Hash your password or pick MD5 or something to make it "unreadeble". You can set it on MySQL. With PHP u build the "secure" value.
MD5 is not the best option. Its only easy to implement for beginning.
Hope this helps :)
Because you have nothing in you value attribute of option. Try to inspect options tag you will see your value =$row[id] which is senseless try to use this
echo " <option value='".$row['id']."'>$row['Name_Team_Position']</option> ";
or
foreach ($conn->query($sqlqb) as $row)
{ ?>
<option value=<?php echo $row[id];?>><?php echo $row['Name_Team_Position'];?></option>
<?php } ?>
Please try the following and let me know.
echo " Pick your QB: <select name='QB'> </option> "; // list box select command
foreach ($conn->query($sqlqb) as $row){
echo " <option value=$row[id]>$row[Name_Team_Position]</option> ";
into
echo " Pick your QB: "; // list box select command
while($row = $resultqb->fetch_assoc()){
echo " ".$row['Name_Team_Position']." ";
$sql = "UPDATE Football.PlayerTeams SET QB = '$value2' WHERE Password = '$value1';";
Into
$sql = "UPDATE Football.PlayerTeams SET QB = '".$value2."' WHERE Password = '".$value1."'";
Try replacing
foreach ($conn->query($sqlqb) as $row)
{ // Array or records stored in $row
echo " <option value=$row[id]>$row[Name_Team_Position]</option> ";
/* Option values are added by looping through the array */
with
while($row = $resultqb->fetch_assoc())
{ // Array or records stored in $row
echo " <option value=$row['id']>$row['Name_Team_Position']</option> ";
/* Option values are added by looping through the array */
Edit
Array index should be in strings.
So, I'm pretty new to web. I'm always fiddling with HTML and SQL, but recently I started working on a project. This project is basically creating a database with all employees contact data (name, email, phone number, etc) and show it on web. Database is set, web page is connecting normally to DB (I can call PHP and send a query, results are shown perfectly). BUT I don't know how to use a <form> content (text written by user) as a Query Parameter. I want to send the parameter when Enter or the 'busca' button are pressed.
Here is the form
<form id="searchbox" >
<label for="sectname">
</label>
<input id="sectname" name="sectname" type="search" placeholder="Busca" list="setor" class="searchbox"/>
<div style="text-align:center">
<input id="submit" type="button" class="button" value="BUSCA"/>
</div>
</form>
And here is the PHP with query
$host = "host=localhost";
$port = "port=5432";
$dbname = "dbname=Cards";
$creds = "user=postgres password=12345678";
$db = pg_connect( "$host $port $dbname $creds" );
if(!$db){
echo nl2br ("Unable to open database\n");
}
$sql =<<<EOF
SELECT * from Cards where nome='Diego Teste';
EOF;
$ret = pg_query($db, $sql);
if(!$ret){
echo pg_last_error($db);
exit;
}
while($row = pg_fetch_assoc($ret)){
echo "<div>";
echo "<img src='".$row['pic']."'class='cardcontent2'/>";
echo "<div class='carddata'>";
echo nl2br ("\nNome: ".$row['nome'] . "\n");
echo nl2br ("Email: ".$row['email'] . "\n");
echo nl2br ("Ramal: ".$row['ramal'] . "\n");
echo nl2br ("Número: ".$row['numero'] . "\n");
echo nl2br ("Setor: ".$row['setor'] . "\n\n");
echo "</div>";
echo "</div>";
}
pg_close($db);
I want 'nome="Diego Teste"' to be 'nome= %var%' and the %var% value should be text written by user.
The trick is to use prepared statements: (ref)
$basequery =<<<EOF
SELECT * from Cards where nome = $1;
EOF;
pg_prepare($db, "my_query", $basequery);
$results = pg_execute($db, "my_query", array($_GET["nome"]));
...
Prepared statements take care of escaping any values you will pass to SQL, so you do not have to do it yourself. It protects you from SQL injection; some people will fill form fields with malicious content that can trip up your SQL statement if you just put the field's text in-place.
My PHP might be a bit rusty, so please forgive me if I made minor mistakes.
I have a problem, small to others, but huge to me. I have been working on a project since March 15 of this year. I am not a web designer but this is just a hobby of mine.
My problems are:
When I call this program for data, I receive records but it only works if I search for the full postcode
(EX 1: n = no results EX 2: nn12ab = 5 results displayed )
I have to arrange the results in some order
(my results = abcdabcdabcdabcdnn12ababcdabcdabcdabcdnn12ababcdabcdabcdabcdnn12ab,
the way I am trying to get them its
first name / last name / email / postcode.
I had checked in w3schools and all other mode but still I am asking this. :(
I am fully aware its no hack protected , I just want to make it work.
any idea where I need to place whatever works ?
TXT IN ADVANCE!
HTML search
<form method="post" action="search.php">
<center>
<h1>My Search Engine</h1>
<input type="text" value="Search..." name="query" />
<input type="submit" value="Find" name="list" />
</center>
</form>
PHP SEARCH and display CODE
<?php
$servername = "localhost";
$username = "abcd";
$password = "******";
$dbname = "abcd";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM wfuk";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><td><tr><th>ID</th></td></tr>
<th>Name</th></td></tr>
<th>postcode</th</td>></tr>
<th>trade</th></td></tr>
<th>telephone</th></td></tr>
<th>comments</th></td></tr></table>
";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<table><tr><td>"
.$row["id"].
"</td><td>"
.$row["first_name"]
.$row["last_name"].
"</td></tr>".
"<tr><td>"
.$row["post_code"].
"</td></tr>".
"<tr><td>"
.$row["trade"].
"</td></tr>".
"<tr><td>"
.$row["telephone"].
"</td></tr>".
"<tr><td>"
.$row["comments"].
"</td></tr></table>"
;
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
Substitute this line:
$sql = "SELECT * FROM wfuk";
by
$sql = "SELECT * FROM wfuk where name like " . $_POST["query"] . " order by first_name, last_name, email, postcode";
I'm assuming that the columns in table wfuk have the names you said. If not, change them by the column names.
This is not the best way to do a search, because it open the possibility for SQL-injection attacks. But at your current level of knowledge you probably aren't ready for other solution.
Later please educate yourself on better prattices on this kind of operation.
Nothing to worry about, just basic confusions .
Answer of first question:
Dont use = sign in query like this :
Select * from table where postcode='.$variable.'
Use like clause this :
Select * from table where postcode like '%.$variable.%'
Answer for Second question:
Place border for your table :
<table border="1">
a few things here
Use some good tutorials, don't trust on w3school (some people call
it w3fool)
Never User Select * from table, rather specify column names
something like Select firstname, lastname from table
if you want search based on integer, user = sign e.g where rollunme=134
if you want to search some text/ character field , use LIKE operator
eg firstname LIKE %zaffar%
these are basic tips which should help you...
PS
question edited, but these tips should still apply as they are very generic in nature and should help you
yes it work unfortunately not whit this code, but from hear i lear the pice that i was missing THX ALL .
CODE I HAVE USE
<?php
//load database connection
$host = "localhost";
$user = "change my";
$password = "change my";
$database_name = "chage my database name";
$pdo = new PDO("mysql:host=$host;dbname=$database_name", $user, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
// Search from MySQL database table
$search=$_POST['search'];
$query = $pdo->prepare("select * from change_table_name where change_title LIKE '%$search%' OR change_author LIKE '%$search%' LIMIT 0 , 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
// Display search result
if (!$query->rowCount() == 0) {
echo "Search found :<br/>";
echo "<table style=\"font-family:arial;color:#333333;\">";
// if need to multiply check clousley <tr> and </td> make shure they are on the right order
echo "<tr>
<td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Change_Title_Books</td>
<td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Change_Author</td>
<td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">change_Price</td></tr>";
while ($results = $query->fetch()) {
// if need to multiply check clousley <tr> and </td> make shure they are on the right order
echo "<tr><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['Chage_title'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['Change_author'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
// if not needit delete "$". from bellow
echo "$".$results['change_price'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo 'Nothing found';
}
?>
<html>
<head>
<title> How To Create A Database Search With MySQL & PHP Script | Tutorial.World.Edu </title>
</head>
<body>
<form action="search-database.php" method="post">
Search: <input type="text" name="search" placeholder=" Search here ... "/>
<input type="submit" value="Submit" />
</form>
<p>PHP MySQL Database Search by Tutorial.World.Edu</p>
</body>
</html>
i found a different code i will post it for future references but you guys let me understand the thinks i could not understand
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