Removing null columns in SQL query - php

I'm using a select * query from a table.
$query = $this->db->get($table_name);
what I want is to for it to discard all records where the value for a column is empty so for example
Array
{
Topic_1 ->
Topic_2 -> Cats
}
It would discard Topic_1 key and value pair entirely. I'm also using Codeigniter active record so I tried doing
$query = $this->db->get_where($value, array(test_id != 'NULL'));
But i cannot specify each column, I just want test_id to be all columns in the table? Is there someone I can do this or can I just run a loop after the query is returned where it discards unmatched key value pairs?

First, you are doing NULL wrong. You should go like this:
$query = $this->db->where('test_id !=', NULL)->get($value)->result_array();
That query will work when field is NULL, but in your case it is not NULL, it is empty. In order for the field to be NULL you must specify it as default when you are creating table.
Query for your case would be:
$query = $this->db->where('test_id !=', '')->get($value)->result_array();
For all the fields, I guess you will need to go with foreach loop:
$data = array();
$field = array('field1', 'field2', ...);
foreach($field as $f) :
$query = $this->db->where($f, '')->get('table')->result_array();
$data = $data + $query;
endforeach;
This way in the $data you will get all the field that are empty.

Related

SQL query is not returning values even if there are values in mysql Table

I got this function:
private function _loadColumnRights() {
$db = Zend_Registry::get('db');
// Create the select query
$select = $db->select()
->from('account_columns', array(
'accountId'
))
->where('accountId = ?', $this->getId());
// Fetch the data
$row = $db->fetchRow($select);
if($row != null) {
$this->setColumns($row['columns']);
}
else {
$this->setColumns('');
}
}
I search for the accountID = '128'
My table looks like this:
accountId | columns
and at row with accountId = '128' I got a value like this 'orderdate,ref-corlido,item-no,partid,item-description,quantity-value,unit-of-measurement,acquisition-value-order-line,sales-value-order-line,markup,due-date,status,direct-delivery,out-of-scope,non-compliant,memo,request-document,documents'
If I in PHP manually execute this SQL statement:
SELECT * FROM `account_columns` WHERE `accountId` = '128'
Then I get result..
my Code also goes in to this if:
if($row != null) {
$this->setColumns($row['columns']);
}
But the value of $row['columns'] is empty.. If I perform a var_dump on my view on this getter then i get empty values
If I change $row['columns']) to :
$this->setColumns($row['accountId']);
then I get the 128 value..
But I don't get the column values.. How come?
Because you only ask for one column in the result row. :)
You only as k for accountId...
private function _loadColumnRights() {
$db = Zend_Registry::get('db');
// Create the select query
$select = $db->select()
// THERE IS YOU ERROR :)
// THE SECOND PARAMETER IS AN ARRAY OF RESULT COLUMNS
->from('account_columns', array(
//'accountId', <-- Your error :)
'*' // use this if you want all columns back
//'columns' // or add this column name
))
->where('accountId = ?', $this->getId());
// Fetch the data
$row = $db->fetchRow($select);
if($row != null) {
$this->setColumns($row['columns']);
}
else {
$this->setColumns('');
}
}
P.S.: You really should use another name for the "columns" colmn... :)
Look at the list of reserved words and keywords... don't use them for column or table names. :)
https://dev.mysql.com/doc/refman/5.7/en/keywords.html
Have a great day!
Good luck!

Drop row if some columns are empty

I have a dynamic table in my db, that columns are altered and deleted from other scripts. Because there is a chance that all those extra columns might hold null or empty values eventually i want to have a 'cleanup' action somewhere that checks for those cells, and if all are empty, to drop the whole row.
The ones in red are the ones i want to check. If both columns are null or empty WHERE customers_id = 1, then DELETE row.
Like i said this is just an example...There could be 5 or 10 columns after customers_id. I need to check them all if they are empty.
I can get all the names of those extra columns in a string like this:
$temparray = array();
$q = mydb_query("SHOW COLUMNS FROM $table WHERE field NOT REGEXP 'id|customers_id'");
while($row = mydb_fetch_array($q)){
$temparray[] = $row['Field'];
}
$forSQL = " '".implode("', '", $temparray)."' "; // gives 'client_custom_contact_person', 'client_custom_password'
$forPHP = implode(", ", $temparray); //gives client_custom_contact_person, client_custom_password
What is the fastest way to check if all those column values are empty to drop that row ?
Should i go with a php foreach function ? Or is there a faster mysql query i could do ?
-Thanks
Figured it out. Using the $forPHP string:
$q2 = mydb_query("SELECT $forPHP FROM $table WHERE customers_id = 1");
$res = mydb_fetch_assoc($q2);
if(!array_filter($res)) {
//If all are empty then
mydb_query("DELETE FROM $table WHERE customers_id = 1");
}

Compare Column value with more than one in Mysql

I have test table which is
this is my table i am comparing string and getting the entity_id from this table
my sql query for one value search is like this
Select entity_id From test Where BINARY value = '".$my_search_list."'
this works fine if i search for single value like Shirt
i want to search for multiple values and when i try it with Comma Separated value
like Root,Appare,hand Bags (more than work) it is not giving me output
i Also tried with this
Select entity_id From test Where BINARY value IN ( '".$my_search_list."' )
i don't want multiple query i want to do it in single query is it possible???
what i was thinking as i said is to create an array of keywords and see which one match the criteria then show all result.
$search = array('Root','Appare','hand Bags');
$sql = "SELECT `entity_id` FROM `test` WHERE ";
$count = 0;
$search_size = count($search);
foreach($search as $key)
{
$count++;
if($count < $search_size)
{
$sql .= "(`value` = '".$key."') or ";
}
else if ($count == $search_size)
{
$sql .= "(`value` = '".$key."')";
}
}
is you echo $sql you will see the correct query wich should work:
SELECT `entity_id` FROM `test` WHERE (`value` = 'Root') or (`value` = 'Appare') or (`value` = 'hand Bags')`
you need to use quotes for values
SELECT entity_id FROM test WHERE value IN ('one','two','three')

How to query all fields in a row

I know this is very simple, but I haven't used PHP/MySQL in a while and I have been reading other threads/php website and can't seem to get it.
How can I query a single row from a MySQL Table and print out all of the fields that have data in them? I need to exclude the NULL fields, and only add those that have data to an html list.
To clarify, I would like to display the field data without specifying the field names, just for the reason that I have a lot of fields and will not know which ones will be NULL or not.
What you've outlined requires 4 basic steps:
Connect to the database.
Query for a specific row.
Remove the null values from the result.
Create the html.
Step 1 is quite environment specific, so that we can safely skip here.
Step 2 - SQL
SELECT * from <tablename> WHERE <condition isolating single row>
Step 3 - PHP (assuming that $query represents the executed db query)
//convert the result to an array
$result_array = mysql_fetch_array($query);
//remove null values from the result array
$result_array = array_filter($result_array, 'strlen');
Step 4 - PHP
foreach ($result_array as $key => $value)
{
echo $value \n;
}
Just SELECT * FROM table_name WHERE.... will do the trick.
To grab data from specific fields, it would be SELECT field_1,field_2,field_3....
you have to make a string which represent mysql query. Then there is function in php named mysql_query(). Call this function with above string as parameter. It will return you all results. Here are some examples
You need to do it like this...
First connect to your sql... Reference
Now make a query and assign it to a variable...
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename");
If you want to retrieve a single row use LIMIT 1
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename LIMIT 1");
If you want to fetch all the columns just use * instead of column names and if you want to leave some rows where specific column data is blank you can do it like this
$query = mysqli_query($connect, "SELECT * FROM tablename WHERE column_name4 !=''");
Now fetch the array out of it and loop through the array like this..
while($show_rows = mysqli_fetch_array($query)) {
echo $show_rows['column_name1'];
echo $show_rows['column_name2'];
}
If you don't want to include the column names in the while loop, you could do this:
while($show_rows = mysqli_fetch_array($query)) {
foreach( $show_rows as $key => $val )
{
echo $show_rows[$key];
}
}

Php explode then get the name row from a MySql Table

I know this has been talked about here before. However, my situation is a bit different and I'm so close.
I would like to explode an array of category id's from a news data table then get the category name from the category table.
Right now I am able to get the id's out and explode them just fine inside the while loop for the news data using:
$post_cats_data = $news_data['cat_id']; // 1,6,7,11
$post_cats_id = explode(",", $post_cats_data);
Now where I'm getting stuck is getting the news categories and echoing out the name.
$cat_count = count($post_cats_id);
$i = 0;
foreach($post_cats_id as $cat_id){
$cat_qry = mysql_query("SELECT * FROM news_categories WHERE `cat_id` = '$cat_id'") or die(mysql_error());
$cat_title_row = mysql_fetch_row($cat_qry) or die(mysql_error());
$i++;
$write_cat .= $cat_title_row['cat_name'] ;
if($i<$cat_count){
$write_cat .= ', ';
}
}
The idea is that this will get the category names from the category tables that were exploded and will add a comma back to the end of everyone but the last one. I am unable to get the category name and when I return the ID it loops though the id for all the news.
I know this is a simple problem, I'm just new to using loops.
mysql_fetch_row returns an array indexed at 0, so $cat_title_row['cat_name'] will not give you the desired results. Use mysql_fetch_assoc instead and it should work fine.
From PHP manual:
mysql_fetch_row() returns an numerical array of strings that corresponds to the
fetched row, or FALSE if there are no
more rows.
mysql_fetch_row() fetches one row of
data from the result associated with
the specified result identifier. The
row is returned as an array. Each
result column is stored in an array
offset, starting at offset 0.
you could just use mysql_result like this:
$cat_title = mysql_result(mysql_query("SELECT cat_name FROM news_categories WHERE `cat_id` = '$cat_id'"),0);
if you want them all in a comma delimited list you could use implode like this:
$cat_titles = array();
foreach($post_cats_id as $cat_id){
$cat_title = mysql_result(mysql_query("SELECT cat_name FROM news_categories WHERE `cat_id` = '$cat_id'"),0);
$cat_titles[] = $cat_title;
}
$comma_cat_titles = implode(',',$cat_titles);
To get it all done in a single query you could do something like:
$cat_titles = mysql_result(mysql_query("SELECT GROUP_CONCAT(`cat_name` SEPARATOR ',') FROM `news_categories` WHERE `cat_id` IN (".$post_cats_data.")"),0);

Categories