Compare values with respective fields in database - php

I have 3 fields in database:
levelOne , levelTwo, levelThree // Table Name = levels
With values:
levelOne = 300,
levelTwo = , // This field is empty
levelThree = , // This field is empty
Now I have a variable which has to be compared with the respective fields.
$var = L1_200;
Now L1_200 means its a level 1 value so it has to be compared with levelOne field in a query and vice versa. SO how can I write the query?

Try this code:
<?php
$var = 'L1_200';
$sql = 'select * from table_name where 1 ';
$arr = explode('_', $var);
if($arr[0] == 'L1'){
$sql .= 'AND levelOne = \''.$arr[1].'\'';
} else if($arr[0] == 'L2'){
$sql .= 'AND levelTwo = \''.$arr[1].'\'';
} else if($arr[0] == 'L3'){
$sql .= 'AND levelThree = \''.$arr[1].'\'';
}
Now use $sql

Related

Using the && / AND operator for an array

This code checks if $value (array) is set in the database as 1. The foreach loop saves all the founding matches into the array $products. Now I have all the fields in the database which have the value 1 but that's not really what I want, because if the field 'dog' equals 1 and the field 'cat' equals NULL, I still have the value of 'dog' in my array. It only should get to the array when BOTH equal 1.
For simple variables you can use the && or AND operator to check if all keys have the same value but how do I do this with an array?
$products = array();
foreach($_POST['selected_checkboxes'] as $value) {
var_dump($value);
if($result = $db->query("SELECT * FROM produkte WHERE `$value` = 1")){
while($row = $result->fetch_object()) {
if (!in_array($row->name, $products)) {
array_push( $products, array('name'=>$row->name, 'image'=>$row->image, 'link'=>$row->link) );
}
}
}
else {
array_push($products, 'error');
}
}
Change your SQL statement such that all checked values are equal to 1.
You can append a " = 1 AND " to each value then use them in your query.
<?php
$arr = ['field1', 'field2', 'field3'];
$condition = join(' = 1 AND ', $arr) . ' = 1';
The output would be "field1 = 1 AND field2 = 1 AND field3 = 1". You can then use $condition in your query.
$db->query("SELECT * FROM produkte WHERE $condition")
UPDATE:
To cope with fieldname containing spaces you would need to wrap each fieldname with backticks so change this line
$condition = '`' . join('` = 1 AND `', $arr) . '` = 1';

MySQL query filtering with CASE or IF

I am trying to find the most efficient (or proper if you prefer) way to filter a MySQL query.
What I am trying to achieve is from a list of around 20+ checkboxes (which I am using to filter the results) to see which one of them are "checked" and if they are "checked" to add them after the WHERE clause.
When they are "checked" the $var = '1' else it is NULL.
What I did until now was mix them together but with 20+ filters that's like o_O
if ($var1 == '1') {
$query = "SELECT * FROM table WHERE var1 = '1';";
..
} elseif ($var2 == '1') {
$query = "SELECT * FROM table WHERE var2 = '1';";
..
} elseif ($var1 == '1' AND $var2 == '1') {
$query = "SELECT * FROM table WHERE var1 = '1' AND var2 = '1';";
..
}
Combination of 20+ filters seems a bit stupid this way.. Is there a simpler way like put an IF $var1 != NULL THEN WHERE var1 = '1'?
Thank you!
This should do what you need:
$var1 = '1';
$var2 = '0';
$var3 = '1';
$where = array('1 = 1');
foreach (array('var1', 'var2', 'var3') as $var)
{
if ('1' == $$var)
{
$where[] = "$var = '1'";
}
}
// SELECT * FROM table WHERE 1 = 1 AND var1 = '1' AND var3 = '1'
echo $query = 'SELECT * FROM table WHERE ' . implode(' AND ', $where);
Suppose you have named your checkboxes as array of cb, so you can use their value as,
$cb=$_POST['cb'];
$q='';
for($i=0;$i<count($cb);$i++)
{
if(isset($cb[$i])&&$cb[$i]!='')
{
$q.=' AND var'.($i+1).'=1';
}
}
$q=trim(' AND');//removes AND from start of string
$query="SELECT * FROM table where $q";
There are several intersting solutions here; this one will work based on a numbered var scheme and add any variable (if it has length) to the query, not just 1.
You can see it working here: https://eval.in/94701
Here are some setup variables:
$numberOfVars = 3;
$var1=4;
$var2=5;
$var3='';
Note that $thevar actually holds the value of var1, var2, etc for each iteration:
$query = "SELECT * FROM table WHERE 1=1 ";
for($i=1;$i<=$numberOfVars;$i++) {
$thevar = ${'var'.$i};
if ( strLen($thevar) ) {
$query .= " AND var$i = '$thevar' ";
}
}
for($i=1;$i<=20;$i++)
{
if (${'var'.$i} == '1' && ${'var'.$i+1} == '1')
{
$query = "SELECT * FROM table WHERE var$i = '1' AND var.$i+1 = '1';";
}
else if (${'var'.$i} == '1')
{
$query = "SELECT * FROM table WHERE var$i = '1';";
}
}
demo

Php insert/update multple row, using array and not a foreach

I’m wondering if this is possible, I’ve search and haven’t found anything so about to give up.
I’m looking to do the following for example, note i do not want to use a foreach as that converts it into single queries.
$a = (1,2,3);
$b = ('john','Rob','Stuffs');
$c = ('doe','roe','soe');
$sql = "update ppl set firstname = $b, lastname = $c where id = $a";
The same can be said for an insert.
$sql = "insert into ppl (firstname,lastname) value ($b,$c)";
The main reason I'm looking to do this is to optimise the db a bit. There are a lot of single queries that (if this method is possible) could be converted into 1 single query.
Thanks in advance.
if (count($a) <= 0)
return; // nothing to do
$sql = "INSERT INTO table (id, firstname, lastname) VALUES";
while (count($a) > 0)
{
$id = array_shift($a);
$fname = array_shift($b);
$lname = array_shift($c);
$sql .= sprintf("('%s', '%s', '%s'),", mysql_real_escape_string($id), mysql_real_escape_string($fname), mysql_real_escape_string($lname));
}
$sql = substr($sql, 0, -1); //remove last comma
$sql .= " ON DUPLICATE KEY UPDATE firstname=VALUES(fname), lastname=VALUES(lname)";
//run your sql
this will allow you to run all of them at once.
For update you can do as follows
$a = (1,2,3);
$b = ('john','Rob','Stuffs');
$c = ('doe','roe','soe');
$i=0;
foreach($b as $fname){
if( !empty($b[$i]))
{
$sql = "update ppl set firstname = '".$b[$i]."', lastname = '".$c[$i]."' where id = $a[$i]";
}
$i++;
}
and for insert you can try
$i=0;
$var = '';
foreach($b as $fname){
if( !empty($b[$i]))
{
$var .= "(".$a[$i].",'".$c[$i]."','".$b[$i]."') ";
}
$i++;
}
if(!empty($var)){
$sql = "insert into ppl(id,firstname,lastname) values ".$var;
}

if field is empty, return all results

I'm working at a search script at the moment, but I have a little problem. I'm using the following query:
mysql_query("SELECT * FROM boeken WHERE
titel LIKE '%".$titel."%' AND
categorie_id = '".$categorie."' AND
auteurs LIKE '%".$auteurs."%' AND
jaar_copyright = '".$jaar_copyright."'
AND ontwerp_groep = '".$ontwerp_groep."'");
For example, when I search for 'categorie_id' = '5', and leave the other fiels empty, I want to get every row that has categorie_id = 5. No matter what the other fields are.
What it does is the following: I get every row that has categorie_id = 5, but where the title is empty, where the 'jaar_copyright' is empty, etc. etc.
How can I fix this the way I want?
<?php
$query = "SELECT * FROM boeken WHERE";
$n = 0;
$makeAnd = "";
foreach($_POST as $key=>$value){
if($value != '' && $value != 'submit'){
if($n != 0){$makeAnd = " AND";}
if(!is_numeric($value)){
$query .= "$makeAnd `$key` LIKE '%$value%'";
} else {
$query .= "$makeAnd `$key` = '$value'";
}
$n++;
}
}
print $query;
?>
In this way you can filter out empty values. If other values are posted to $_POST make sure to filter them out in the "if($value !=" part.
Why not just build a query based on vars? That way they're not included in the query unless the var is populated. I don't know what your variables like $titel actually are, so I just say if they're not blank. This should obviously be set towhatever is applicable. Not null, isset, etc. and always escape with something like mysql_real_escape_string()
$titel_where = "";
if($titel != '')
$title_where = "AND titel LIKE '%".$titel."%'";
$auteurs_where = "";
if($auteurs_where != "")
$auteurs_where = "AND auteurs LIKE '%".$auteurs."%'";
$jaar_copyright_where = "";
if($jaar_copyright != '')
$jaar_copyright_where = "AND jaar_copyright = '".$jaar_copyright."'";
$ontwerp_groep_where = "";
if($ontwerp_groep != '')
$ontwerp_groep_where = "AND ontwerp_groep = '".$ontwerp_groep."'";
mysql_query("SELECT * FROM boeken WHERE
categorie_id = '".$categorie."'
$titel_where
$auteurs_where
$jaar_copyright_where
$ontwerp_groep_where
");
mysql_query("SELECT * FROM boeken WHERE
( '".$categorie."' = 5 AND
categorie_id = 5
) OR
( titel LIKE '%".$titel."%' AND
categorie_id = '".$categorie."' AND
auteurs LIKE '%".$auteurs."%' AND
jaar_copyright = '".$jaar_copyright."' AND
ontwerp_groep = '".$ontwerp_groep."'
)");
For each criteria, you need to add a second evaluation for a blank parameter value:
(categorie_id = '".$categorie."' OR '".$categorie."' = '') AND ...
This way you cover both cases of an empty or a populated parameter.
EDIT:
Sample query as it would appear in SQL.
Assume you pass in a $categorie of 5 and no other parameters:
SELECT * FROM boeken WHERE
(titel LIKE '%%' OR '' = '' )AND
(categorie_id = '5' OR '5' = '') AND
(auteurs LIKE '%%' OR '' = '') AND
...
If they get passed in as NULL then do a NULL comparison instead of an empty string comparison.
You should check what field is set in code, and then only add that part to your query. for instance:
if(isset($_POST['categorie_id'])){
$where = " categorie_id = '".$categorie."' ";
}elseif(...){
....
}
Well, you get the point, you can make it a bit neater probably, depending on the format of your form/POST etc, but that's the idea. Just figure out WHAT you know, and then push it in the SQL.
I'm at work, so no long stories possible, but you should be able to figure it out with this:
foreach($_POST as $key=>$item){
if($value != ''){
$yourField = $key;
$yourValue = $item;
}
}
//PERFORM SANITY CHECKS!
//MAYBE USE PDO etc? (but that's another thing)
//SAVE them in 2 new variables used below:
$query = "SELECT * FROM boeken WHERE `$sanitizedField` = '$sanitizedValue'";

Checking for empty fields in mysql table

I have a table with 12 columns and 200 rows. I want to efficiently check for fields that are empty/null in this table using php/mysql. eg. "(col 3 row 30) is empty". Is there a function that can do that?
In brief: SELECT * FROM TABLE_PRODUCTS WHERE ANY COLUMN HAS EMPTY FIELDS.
empty != null
select * from table_products where column is null or column='';
SELECT * FROM table WHERE COLUMN IS NULL
As far as I know there's no function to check every column in MySQL, I guess you'll have to loop through the columns something like this...
$columns = array('column1','column2','column3');
foreach($columns as $column){
$where .= "$column = '' AND ";
}
$where = substr($where, 0, -4);
$result = mysql_query("SELECT * FROM table WHERE $where",$database_connection);
//do something with $result;
The = '' will get the empty fields for you.
you could always try this approach:
//do connection stuff beforehand
$tableName = "foo";
$q1 = <<<SQL
SELECT
CONCAT(
"SELECT * FROM $tableName WHERE" ,
GROUP_CONCAT(
'(' ,
'`' ,
column_name,
'`' ,
' is NULL OR ',
'`' ,
column_name ,
'`',
' = ""' , ')'
SEPARATOR ' OR ')
) AS foo
FROM
information_schema.columns
WHERE
table_name = "$tableName"
SQL;
$rows = mysql_query($q1);
if ($rows)
{
$row = mysql_fetch_array($rows);
$q2 = $row[0];
}
$null_blank_rows = mysql_query($q2);
// process the null / blank rows..
<?php
set_time_limit(1000);
$schematable = "schema.table";
$desc = mysql_query('describe '.$schematable) or die(mysql_error());
while ($row = mysql_fetch_array($desc)){
$field = $row['Field'];
$result = mysql_query('select * from '.$schematable.' where `'.$field.'` is not null or `'.$field.'` != ""');
if (mysql_num_rows($result) == 0){
echo $field.' has no data <br/>';
}
}
?>
$sql = "SELECT * FROM TABLE_PRODUCTS";
$res = mysql_query($sql);
$emptyFields = array();
while ($row = mysql_fetch_array($res)) {
foreach($row as $key => $field) {
if(empty($field)) || is_null($field) {
$emptyFields[] = sprintf('Field "%s" on entry "%d" is empty/null', $key, $row['table_primary_key']);
}
}
}
print_r($emptyFields);
Not tested so it might have typos but that's the main idea.
That's if you want to know exactly which column is empty or NULL.
Also it's not a very effective way to do it on a very big table, but should be fast with a 200 row long table. Perhaps there are neater solutions for handling your empty/null fields in your application that don't involve having to explicitly detect them like that but that depends on what you want to do :)
Check this code for empty field
$sql = "SELECT * FROM tablename WHERE condition";
$res = mysql_query($sql);
while ($row = mysql_fetch_assoc($res)) {
foreach($row as $key => $field) {
echo "<br>";
if(empty($row[$key])){
echo $key." : empty field :"."<br>";
}else{
echo $key." =" . $field."<br>"; 1
}
}
}
Here i'm using a table with name words
$show_lang = $db_conx -> query("SHOW COLUMNS FROM words");
while ($col = $show_lang -> fetch_assoc()) {
$field = $col['Field'];
$sel_lan = $db_conx -> query("SELECT * FROM words WHERE $field = '' ");
$word_count = mysqli_num_rows($sel_lan);
echo "the field ".$field." is empty at:";
if ($word_count != 0) {
while($fetch = $sel_lan -> fetch_array()){
echo "<br>id = ".$fetch['id']; //hope you have the field id...
}
}
}
There is no function like that but if other languages are allowed, you can extract the structure of a table and use that to generate the query.
If you only need this for a single table with 30 columns, it would be faster to write the query by hand...

Categories