MySql query on different input fields where some of them are NULL - 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.

Related

How to select all from table based on username

I would like to ask how to select all from table based on username? I mean for example my user 1 insert his/her data and send to localhost and in status page will display their own data only. Below is my status page php.
<?php
require_once('dbConnect.php');
//Creating sql query
$sql = "SELECT * FROM Table";
//getting result
$r = mysqli_query($con,$sql);
//creating a blank array
$result = array();
//looping through all the records fetched
while($row = mysqli_fetch_array($r)){
//Pushing name and id in the blank array created
array_push($result,array(
"id"=>$row['id'],
"username"=>$row['username'],
"name"=>$row['name']
));
}
//Displaying the array in json format
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
"SELECT * FROM Table WHERE username = 'john'"
This is assuming your table is actually named 'Table' as you have it above. Otherwise replace it with the actual table name.
If you have a variable for user name do this:
"SELECT * FROM Table WHERE username = '" . $username . "'";
You can use WHERE clause in the query like.
"SELECT * FROM Table WHERE username = 'lun L'"
But this is not a good way to fetch data by user name. You should select users on ID base and ID should be unique. Because there are so many users who might have the same name.
"SELECT * FROM Table WHERE youUniqueColName = '$uniqueVal'"
If unique column is id then use id='$id'
SELECT * FROM tablename WHERE username = 'username'
Use this if you want a fixed SQL Query in your variable, or use;
SELECT * FROM tablename WHERE username = '$username'
if you have an input that asks a username to display a specific username..

Dynamic sql search in php

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 !

How to make query that ignores undefined variables?

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

dynamically generate mysql query with php

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.

what is wrong with this code?

I need to read a text file, query the database table with that name, and store that table's data in another table. So far I have written this code but I don't know why it's not working.
foreach ($lindb as $namedb) {
$query = "SELECT * FROM ntable WHERE name =" .$namedb. "";
$result = mysql_query($query);
while ($r = mysql_fetch_array($result)) {
$query = "INSERT INTO ndtable (name,details,address,login,country) VALUES (\"".$r["name"]."\", \"".$r["details"]."\", \"".$r["address"]."\", \"".$r["login"]."\", \"".$r["country"]."\")";
mysql_query($query);
}
}
You don't have quotes around $namedb
ie. SELECT * FROM ntable WHERE name =" .$namedb. ""; should be SELECT * FROM ntable WHERE name ='" .$namedb. "'";
I suggest a SELECT INTO would be the better choice... and please post the error so we are able to help...

Categories