Filtering MySQL query. "AND" operator - php

I'm getting excessive rows selected from the db. However, when i try to filter the data with AND lt_num it does not select anything at all. What could be the problem?
$w = $_POST['pal_num'];
$w = "'".implode("','",$_POST['pal_num'])."'";
$r = mysql_query("SELECT * FROM pl_tab WHERE pal_num AND lt_num in (".$weights.");");

My guess is you need to do two comparisons like this:
SELECT
*
FROM
pl_tab
WHERE
pal_num in (".$weights.")
AND lt_num in (".$weights.");
You can't say column1 and column2 = 3 for example. If you want rows where both are equal to 3, you would need to use column1=3 and column2=3 in your query.
Also, you might want to have a read of this Q&A that I wrote a while back which covers off a lot of basic SQL queries and expands from there.
Edit:
If you have $weights in the query, you do set it somewhere, or do you want it to be what is in your variables you show here:
$weights = $_POST['pal_num'];
$weights = "'".implode("','",$_POST['pal_num'])."'";
Is this what you meant?

Related

Creating an associative array to query one SQL in PHP to get several results

I am new to PHP and would appreciate any assistance in creating an associative array to query a table using SQL.
I want to use one select statement to get multiple results depending on the 'WHERE' key.
$a = $DB->getOne("SELECT DEF_VAL FROM JDEFAULTS WHERE DEF_KEY = :0", array('ip'));
$stmt1 = $DB->getOne("SELECT DEF_VAL FROM JDEFAULTS WHERE DEF_KEY = :0", array('ftpUserid'));
$c = $DB->getOne("SELECT DEF_VAL FROM JDEFAULTS WHERE DEF_KEY = :0", array('ftpPasswd'));
These codes return different values (as expected). I want to merge all of these into one line of SQL and get the values in a list depending on the DEF_KEY value.
how to create associative array from sql table
I have tried following the solutions from this but haven't been able to execute the code.
#Hashibul Hussain i havent understand your questions completly, but as far as i understood you want one query with three conditions. you can try this. this may work.
$stmt1 = $DB->getOne("SELECT DEF_VAL FROM JDEFAULTS WHERE DEF_KEY = :0 or WHERE DEF_KEY = :0 or WHERE DEF_KEY = :0", array('ip'), array('ftpUserid'), array('ftpPasswd'));
please elabrate your question further so that i can come up with better solution.

How to use "IN" operator in prepared statement in php

i will use "IN" operator with using parameter in prepare statement
but i can't do that
$hotel_list = "SELECT DISTINCT h.hotel_id, h.hotel_name, h.hotel_address, h.hotel_image
FROM type_feture tf
JOIN type t ON t.type_id = tf.type_id
JOIN hotel h ON h.hotel_id=t.hotel_id
WHERE tf.feture_id IN ?
AND h.hotel_city_id=?
GROUP BY tf.type_id, h.hotel_id, h.hotel_name, h.hotel_address HAVING COUNT(tf.type_id)>=?";
$result = $dbca->prepare($hotel_list);
$result->bind_param("sii", $feture,$city_ide,$cnt_type);
$feture=(string)$finish;
$city_ide = (int)$hotel_city_id;
$cnt_type=(int)$cn;
$result->execute();
$res = $result->get_result();
while ($obj = $res->fetch_object()) {
$hotels[] = $obj;
}
Because it is a design requirement that you must use the IN operator and prepared statements, you need a way to convert the PHP array of (value 1, value 2, value 3, ... value n) into an SQL array (value 1, value 2, value 3, ... value n). You'll need an intermediate step, as PHP objects cannot be directly translated into SQL without the aid of functions or loops of some sort.
Your thought process should be: what do the two variables have in common? Answer: they're both lists and they can both be represented by strings. To solve your problem, then, you want to transform the PHP list into a comma-separated string, into an SQL array, and then check in the SQL query if the specified column has a value in that array.
There are only two changes you need to make to your code to accomplish this:
1) Create a variable $feature_ids_str and make it the comma-separated string version of whatever array holds your feature IDs (as per the comments on your question, it really would be helpful if you gave us some more code to explain where some of these variables were coming from). An example of the value of $feature_ids_str would be "1,5,3,7,82,4".
2) Amend your query as follows: ... WHERE tf.feture_id IN STRING_SPLIT(?, ',') ... [feture_id sic] and of course update the $result->bind_param() function accordingly.
Also, I think you're misspelling "feature".

MySQLi BETWEEN query to get data from text fileds in database

I have a query :
$sql = "SELECT * FROM table WHERE CONCAT(Prod, Serial) BETWEEN '$start' AND '$end'";
Where Prod and Serial are stored in MySQLi database as a string. I need to update details of items between say AA1000 and AA1005. When I run this query it updates details of units between AA1000 and AA1005 and, "as a bonus", all between AA10000 and AA10050.
Is there a way to get exact match for the text type fields using BETWEEN query?
Thanks!
P.S. I know that I need update query to update details. I'm using SELECT for testing purposes.
You are abusing the BETWEEN syntax in a very bad way. You're comparing strings, so
'AA1000' <= 'AA10000' <= 'AA1005'
is actually TRUE, because you're not comparing numbers, just strings. String comparisons go on a per-character basis, without consideration for length, so
'A' <= 'AZ' <= 'B'
is also true, even though a human would consider "AZ" to come AFTER 'B'.
This query should do it:
SELECT *
FROM TABLE
WHERE Prod = LEFT('$start', 2)
AND CAST(Serial AS DECIMAL) BETWEEN SUBSTRING('$start', 3) AND SUBSTRING('$end', 3);
You could also split the start and end strings apart in PHP:
$prod = substr($start, 0, 2);
$start_code = substr($start, 2);
$end_code = substr($end, 2);
$sql = "SELECT *
FROM TABLE
WHERE Prod = '$prod'
AND CAST(Serial AS DECIMAL) BETWEEN $start_code AND $end_code";
I have never personally encountered a situation where I have needed this, but I believe you can do this with Regular Expressions. This may help you.
Following worked so far:
CONVERT(SUBSTRING('$startunit', 3),UNSIGNED INTEGER)
Thanks everyone!

extracting rows from two tables in php and sql

I have two tables properties and buildings. I want to extract rows from the buildings table according to a criteria.
I have put these buildings ids in a variable, as below:
$buildings = "1,2,3,4,5,6,7,8,9,10"
I am trying to access the properties according to the above list.
SELECT * FROM properties WHERE BUILDING_ID IN ('{$buildings}')
but I am not getting the desired result. How can I get the desired result? Is this the right approach?
Remove the single quotes (and optionally the braces).
$query = "SELECT * FROM properties WHERE BUILDING_ID IN ($buildings)"
Note that IN is not always the most efficient as it can't use indexes - if you can use BETWEEN instead, you may get better performance on a large dataset. But for smaller datasets, IN is fine.
You could do something like:
$buildings = "1,2,3,4,5,6,7,8,9,10";
$buildingIDs = explode(",", $buildings);
$buildingQueries = array();
foreach ($buildingIDs as $buildingID) {
$buildingQueries[] = "BUILDING_ID = " . $buildingID;
}
$query = "SELECT * FROM properties WHERE " . implode(" OR ", $buildingQueries);
That will let you take advantage of indexes, and allow for variable IDs.
Warning: you should look into mysqli or PDO, and move away from the soon to be deprecated mysql library

How to select results from a MySQL DB using Strpos instead of a While statement?

I have been using the PHP function strpos to find results containing the characters of a string from a DB:
User Types: Hel
Results: Hello, Hell, Helli, Hella
I have it basically query the entire table:
$result = mysql_query("SELECT * FROM Events");
And then ran a while statement to see which of the results contain the characters of the input:
while($row = mysql_fetch_array($result))
{
$pos = strpos($row['Title'], $q);
if ($pos === false) {
} else {
echo $row['Title'];
}
}
And to find the number of results, I was using:
$n = $n++
Inside of the while statement.
I know you can use:
$num_rows = mysql_num_rows($result);
To find the number of results if you are only selecting those values from the database, but do I have to use this while statement to find the number of results that match the strpos function? Or can I put the strpos in to the Select From query?
Any help is greatly appreciated,
Taylor
This seems highly inefficient. Why wouldn't you simply let the database do the searching for you?
$result = mysql_query("SELECT * FROM Events WHERE Title LIKE '" . addslashes($q) . "%'");
Then just loop through the results.
You could update your SQL to something like
SELECT *
FROM Events
WHERE Title LIKE '{your_string}%'
Make sure to filter for sql injection though.
You can use the LIKE statement:
SELECT * FROM Events WHERE field1 LIKE '%something%'
Where the special % characters say "Anything of any length"; so we're searching for something (or nothing), then the string, then something (or nothing.) For example, searching for %f% will match foo, off, and affirmative.
Just as general advice, I recommend that you use php's MySQLi class; it's an improved version (hence the i), and provides prepared statements, so you won't have to worry too much about SQL injections.

Categories