I'm trying to learn how to dynamically generate a mysql query based on the form fields that a user chooses to fill with data. In-order to make the learning process as easy as possible I'm using a simple form with a field for the users first name and last name. The basic (non-dynamic) version of the code is as follows:
<html>
<head>
<title>Untitled</title>
</head>
<body>
<form method="post" name="test" action="dynamic_search.php">
<input type="text" name="first_name">
<input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
<?php
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
include "link.php";
$query = "SELECT * FROM members " .
"WHERE first_name = '$first_name' " .
"AND last_name = '$last_name' ";
$result = mysql_query($query)
or die(mysql_error());
$row = mysql_fetch_array($result);
$member_id = $row['member_id'];
$member_first_name = $row['first_name'];
$member_last_name = $row['last_name'];
echo $member_id;
echo $member_first_name;
echo $member_last_name;
?>
</body>
</html>
What I need to be able to do is generate a query based on the data submitted. So if the user only enters their first name the query would read as :
$query = "SELECT * FROM members " .
"WHERE first_name = '$first_name' ";
But if the user enters both their first and last name the query would read as :
$query = "SELECT * FROM members " .
"WHERE first_name = '$first_name' " .
"AND last_name = '$last_name' ";
Any help (or if someone can point me towards a good tutorial) would be greatly appreciated!
Thanks!
You can use PHP to check the input and append to the query when necessary.
$query = "SELECT * FROM members ";
$query .= "WHERE first_name = '$first_name' ";
if($last_name!="")
$query .="AND last_name = '$last_name' ";
Remember to escape the strings my using real_escape_string
$first_name = mysql_real_escape_string($_POST['first_name']);
In case you want to check for the first name:
$query = "SELECT * FROM members ";
if($first_name!=""){
$query .= "WHERE first_name = '$first_name' ";
if($last_name!="")
$query .="AND last_name = '$last_name' ";
}
else{
if($last_name!="")
$query .="WHERE last_name = '$last_name' ";
}
First, 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. (Credit)
Second, a caution to always escape user input being included in an SQL statement. Prepared statements handles this for you automatically.
Having said that, the PHP logic that you're after is something like this:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$first_name = $mysqli->real_escape_string($_POST['first_name']);
$last_name = $mysqli->real_escape_string($_POST['last_name']);
$sql = "SELECT * FROM members WHERE 1";
if (! empty($first_name)) {
$sql .= " AND first_name = '$first_name'";
}
if (! empty($last_name)) {
$sql .= " AND last_name = '$last_name'";
}
So if you want to generate MySQL queries based on form entries you might look into this functional generator below:
Php Sql Query Builder
https://github.com/nilportugues/php-sql-query-builder
This allows you to take your form results and its field names(or ids) and code it into the query builder to generate your requested query!
One bit of advice is to make sure that your field names match your table column names. This will make your process more seamless.
For example. In your case (assuming that your columns names match your form names and your table is named "members"):
<?php
use NilPortugues\Sql\QueryBuilder\Builder\GenericBuilder;
$builder = new MySqlBuilder(); // <-- use MySqlBuilder
$query = $builder->select()
->setTable('members')
->setColumns(['first_name','last_name','email']); // <-- Form names
echo $builder->write($query);
?>
This will output:
SELECT members.first_name, members.last_name, members.email FROM members
Wha la!
Did are many complex queries that you can generate on the developer's GitHub page.
Related
In my project, I have two tables. They are login and employee table.
Employee table contains name, NIC etc. and login table has NIC, password.
NIC is username of the system. I wanted to know how to retrieve logger name from the session. This is the code I have added to the system, but it shows error as systax error. Could anyone help me to solve this?
<?php
$sql = 'SELECT tbl_employee.Fname
FROM tbl_login , tbl_employee
WHERE tbl_employee.NIC = tbl_login .$_SESSION['username'] ';
?>
You don't need to refer to tbl_login (you already have the NIC in your $_SESSION['username'] var ) and if NIC is a string you should enclose it in quotes
<?php
$sql = 'SELECT tbl_employee.Fname
FROM tbl_employee
WHERE tbl_employee.NIC = "' . $_SESSION['username'] . '"';
?>
Try this. This should work.
You can capture the session in toa variable
$sess = $_SESSION['username'];
$sql = "SELECT tbl_employee.Fname
FROM tbl_login , tbl_employee
WHERE tbl_employee.NIC = { 'tbl_login' .$sess } ";
Or, If you dont want to use one more variable,
$sql = "SELECT tbl_employee.Fname
FROM tbl_login , tbl_employee
WHERE tbl_employee.NIC = tbl_login" .$_SESSION['username'];
Trying to create a dynamic search functionality.
Goal : allowing user to search by email (if not empty), if empty (by last name), if both are not empty, than by both, etc.
I know I can write if statement depicting every scenario and than insert SQL command based on that, question is can this be handled in a more simplified manner. Thanks for your help.
Current function set up does OR across all fields, values are coming from $_POST:
find_transaction($email,$last_name,$first_name, $transaction_id)
{
GLOBAL $connection;
$query = "SELECT * ";
$query .= "FROM transactions WHERE ";
$query .= "email='{$email}' ";
$query .= "OR last_name='{$last_name}' ";
$query .= "OR first_name='{$first_name}' ";
$query .= "OR transaction_id='{$transaction_id}' ";
$query .= "ORDER BY date DESC";
$email = mysqli_query($connection,$query);
confirm_query($email);
return $email;
}
I do this all the time, it's not too much work. Basically build your WHERE statement dynamically based off your POST variables, using a series of if statements.
For example:
$where_statement = "";
// First variable so is simpler check.
if($email != ""){
$where_statement = "WHERE email = '{$email}'";
}
// Remaining variables also check if '$where_statement' has anything in it yet.
if($last_name != ""){
if($where_statement == ""){
$where_statement = "WHERE last_name = '{$last_name}'";
}else{
$where_statement .= " OR last_name = '{$last_name}'";
}
}
// Repeat previous 'last_name' check for each remain variable.
SQL statement would change to:
$query = "SELECT * FROM transactions
$where_statement
ORDER BY date DESC";
Now, the SQL will only contain filters depending on what values are present, so someone puts in just email, it would generate:
$query = "SELECT * FROM transactions
WHERE email = 'smith#email.com'
ORDER BY date DESC";
If they put in just last name, it would generate:
$query = "SELECT * FROM transactions
WHERE last_name = 'Smith'
ORDER BY date DESC";
If they put both, would generate:
$query = "SELECT * FROM transactions
WHERE email = 'email#email.com' OR last_name = 'Smith'
ORDER BY date DESC";
Etc., etc.
You could add as many variables you wish here, and basically if the specific variable is not blank, it will add it to the "$where_statement", and depending on if there is anything in the "$where_statement" yet or not, it will decide to start with = "WHERE ", or append .= " OR" (notice the '.=' and the space before 'OR'.
Better use Data Interactive table : http://datatables.net/
It's useful and no SQL-injection :) Good luck !
I am having problems trying to get these queries with a WHERE clause to work. I have two tables which look like this :
What I am trying to do is return the genre that each film has. At the moment no data is returning at all from what I can see. Here are the two queries:
$film_id = $row_movie_list['film_id'];
mysql_select_db($database_fot , $fot);
$query_get_genre = "SELECT * FROM film_genre WHERE `id_film` ='". $film_id. "'";
$get_genre = mysql_query($query_get_genre, $fot) or die(mysql_error());
$row_get_genre = mysql_fetch_assoc($get_genre);
$totalRows_get_genre = mysql_num_rows($get_genre);
$genre_id = $row_get_genre['id_genre'];
mysql_select_db($database_fot , $fot);
$query_genre = "SELECT * FROM genre WHERE `id_genre` ='". $genre_id. "'";
$genre= mysql_query($query_genre, $fot) or die(mysql_error());
$row__genre = mysql_fetch_assoc($genre);
$totalRows_genre = mysql_num_rows($genre);
PHP with content area. I fairly new to PHP so any help would be appreciated.
<?php do { echo $genre['genre']; } while($row_get_genre = mysql_fetch_assoc($get_genre)); ?>
Update: I am now able to get first genre but not second it just echos the first one twice and I have tried but still no luck:
do {do { echo $row_genre['genre']; } while($row_genre = mysql_fetch_assoc($genre));} while($row_get_genre = mysql_fetch_assoc($get_genre)); ?>
Avoiding the fact that you're using a deprecated way to establish connection and interact with MySQL, what you're doing is getting a single relation genre-film and then getting the row of the genre that matches. You should surround part of your code with a while that executes while it's still genres of the film with id. Something like:
$film_id = $row_movie_list['film_id'];
mysql_select_db($database_fot , $fot);
$query_get_genre = "SELECT * FROM film_genre WHERE `id_film` ='". $film_id. "'";
$get_genre = mysql_query($query_get_genre, $fot) or die(mysql_error());
while($row_get_genre = mysql_fetch_assoc($get_genre)){
$genre_id = $row_get_genre['id_genre'];
$query_genre = "SELECT * FROM genre WHERE `id_genre` ='". $genre_id. "'";
$genre= mysql_query($query_genre, $fot) or die(mysql_error());
$row__genre = mysql_fetch_assoc($genre);
// You should do whatever you want to do with $row__genre here. Otherwise it will be cleared.
}
I must insist this is a deprecated and insecure way of communication with a MySQL Database. I recommend you read about MySQLi or PDO extensions.
MySQLi: http://www.php.net/manual/en/book.mysqli.php
PDO: http://www.php.net/manual/en/book.pdo.php
Hello I have 3 fields on input form which are set via POST method to external php
$id=$_POST['id'];
$nombre=$_POST['nombre'];
$cedula=$_POST['cedula'];
where I would like to make a search option depending on which field have data inside it or if a user put data in all 3 or in only 2 fields to search from the input fields which are not NULL fields in the same table where there is a result.
my sql query is something like that $sql = "SELECT * FROM users WHERE userID = $id AND nombre = $nombre AND cedula = $cedula) ";
obviosly which is not working, what should I do to make it work. Do I need to change only the query or I need to put something before it to check first what is not NULL. Thanks
Firstly, your SQL statement should be updated to have enclosed ' (commas) around string values.
So, modify it to:
$sql = "SELECT * FROM users WHERE userID = '$id' AND nombre = '$nombre' AND pass = '$pass'";
// ----------------------------------------^---^--------------^-------^------------^-----^
Second thing is that you should search a field only when it has a value otherwise, it of no use.
So, your modified PHP code should be:
$sql = "SELECT * FROM users WHERE 1 ";
if (!empty($id)) {
$sql .= " AND userID = '$id' ";
}
if (!empty($nombre)) {
$sql .= " AND nombre= '$nombre' ";
}
if (!empty($pass)) {
$sql .= " AND pass= '$pass' ";
}
And your Database will be searched for the fields only if they have data filled in the form.
Try to add quote:
$sql = "SELECT * FROM users WHERE userID = ".$id." AND nombre = ".$nombre." AND pass = '".$pass."' ";
Yes, you will need to put a check before which will ignore the fields which are null.
Also, you would need to put the $variable inside single quotes ' if they are VARCHAR or CHAR types.
How make mysql search defined just by what is written in html form, by user, and if some form box is stayed empty, mysql should ignore it. For example:
$sql = "SELECT * FROM catalog WHERE name= '".$name."' AND publisher = '".$publisher."' ";
mysql_query($sql);
This query will display all rows where name and publisher are together. Now, what if user insert just name, and left publisher box empty. The idea is that php/mysql ignore empty form box, and display every row with inserted name. But it will not do that because $publisher will be undefined, and error emerges. How to tell musql to ignore $publisher? More generally, the question is: how to generate query that make searching defined by certain criteria if they exists, and if they don't how to just ignore it?
You can build up the sql programmatically. I am assuming you have escaped the values properly.
$sql = "SELECT * FROM catalog";
$wheres = array();
if (!empty($name)) {
$wheres[] = " name = '$name'";
}
if (!empty($publisher)) {
$wheres[] = " publisher = '$publisher'";
}
if (count($wheres)) {
$sql .= " WHERE " . implode (' AND ', $wheres);
}
//RUN SQL
Also have a read through this, you are using a deprecated mysql library.
This will allow either the name or the publisher to be NULL.
<?php
$sql = "SELECT * FROM catalog WHERE (name= '".$name."' OR name IS NULL) AND (publisher = '".$publisher."' OR publisher IS NULL)";
mysql_query($sql);
Try like
$my_var = " ";
if($publisher) //if(!empty($publisher))
$my_var = " AND publisher = '".$publisher."' ";
$sql = "SELECT * FROM catalog WHERE name= '".$name."' ".$my_var;
if the publisher is empty then you need to pass the NULL value and PLZ note that it is a bad practise.It will causes many sql injection issues.Try to put validations for the things