php search/replace empty records in mysql - php

Trying to do a search and replace using php/mysql. I do this in specified table headers/columns. it works fine when my search term has a value. However i want to search for an empty field in a specified column and replace with a value. it fails to do a search and replace when my search term is an empty string. Any help?
$SearchAndReplace_header = isset($_POST['SearchAndReplace_header']) ? $_POST['SearchAndReplace_header'] : "";
$SearchAndReplace_search_term = isset($_POST['SearchAndReplace_search_term']) ? $_POST['SearchAndReplace_search_term'] : "";
$SearchAndReplace_replace_with = isset($_POST['SearchAndReplace_replace_with']) ? $_POST['SearchAndReplace_replace_with'] : "";
//foreach($fields as $key => $val) {
// if($SearchAndReplace_header == "all" || ($SearchAndReplace_header == $val)) {
// replace column value with parameter value
$sql = "UPDATE ".$table_name." SET ".$val." = REPLACE(".$val.",'".$SearchAndReplace_search_term."','".$SearchAndReplace_replace_with."')";
$db->query($sql);
// }
// }

You can't do a replace on an empty field, you'll have to set the field directly.
UPDATE table
SET column = 'value'
WHERE column = '' or column is null
If you want to cover both cases in a single query, you could do something like this:
UPDATE table
SET column = CASE
WHEN column IS NULL OR COLUMN = ''
THEN 'replace'
ELSE
REPLACE(column, 'find', 'replace')
END CASE

Related

How to get the last inserted ID and insert it to the second table using the laravel collection?

this is the first time I encounter of this problem and to be honest I don't know what this called. I have module where I need to insert all the data in the first table, then every id that inserted to the first table I want to get it each then insert it to the second table. The purpose of inserting the id to the second table is for the relation of the tables. Now I used laravel for my backend and I used the transform method to insert each data.
Now the main problem here is how can I get each last inserted Id to the first table and Insert it to the second table.
Here is my data that I inserted to the first table:
$collection = $rows->transform(function($item) use ($start,$cash_amount, $bank_deposit_amount, $off_set_amount, $grand_total) {
unset($item["key"]);
$item["checkDate"] = ($item["checkDate"] != '') ? $item["checkDate"] : null;
$item['encoded_by'] = ($item['customer'] != '') ? Auth::user()->name : '';
$item['receive_date'] = ($item['customer'] != '') ? $start : null;
$item['status'] = ($item['customer'] != '') ? "exchange_check" : '';
$item['amount'] = ($item['amount'] != '') ? floatval(preg_replace('/[^\d.]/', '', $item['amount'])) : '';
$item["original_date"] = $item["checkDate"];
$item['cash'] = $cash_amount;
$item['bank_deposit'] = $bank_deposit_amount;
$item['offset'] = $off_set_amount;
$item['grand_total'] = $grand_total;
return $item;
});
ExchangeCheck::insert($collection->toArray());
For second table I used this model use App\ExchangeList; where this model use to inserted all the ID's from the the ExchangeCheck Model:
Is this possible that I can insert each ID's of ExchangeCheck to the ExchangeList?
Thanks.
When inserting your data into your table, instead of insert used insertGetId, and inject the result into a variable in order to retrieve the id.
Try something like :
$lastIDinserted = ExchangeCheck::insertGetId($collection->toArray());
Otherwise you can use this method :
$lastIDinserted2 = ExchangeCheck::select('id')->orderByDesc('id')->first();
// OR
$lastIDinserted2 = ExchangeCheck::latest('id')->first();
And to retrieve your id, do:
$lastIDinserted2 = $lastIDinserted2->id;
Hope this helped you !

PHP - Remove extra comma

I have 3 post variables & i need to save those 3 variable values in single field in mysql table
below are table field details:
-------------------------------
id int(11)
name varchar(100)
country varchar(100)
details varchar(100) (this field used for store all 3 variables value)
if variable values are posted as id=1, name-steve & country=usa then needs to store as
RESULT - 1,steve,usa
now problem is all 3 variable are optional so if passed just id & name needs to store as
RESULT - 1,steve (no last comma will be store)
if passed just id & country then needs to store as
RESULT - 1,usa (no additional comma will be stored)
I have tried like:
if(isset($data['id']) || isset($data['name']) || isset($data['country']))
{
$details=$data['id'].",".$data['name'].",".$data['country'];
}
How can i achieve this in php-mysql ?
Put present values in an array and implode it after
$details = [];
if(isset($data['id']) and !empty($data['id'])) $details[] = $data['id'];
if(isset($data['name']) and !empty($data['name'])) $details[] = $data['name'];
if(isset($data['country']) and !empty($data['country'])) $details[] = $data['country'];
$details = implode(',', $details);
Your code
if(isset($data['id']) || isset($data['name']) || isset($data['country']))
{
$details=$data['id'].",".$data['name'].",".$data['country'];
}
Just add this after your code .
And you are done.
$details = trim($details,',');
$text = '';
foreach($details as $k=>$v) { if($v) $text .= ($text?',':'') . $v; }

Update INT/DECIMAL field with a null/no value

I have a lot of input box's. Each input box is linked with a INT or DECIMAL MySQL field and is displayed inside the text box.
The default value of each INT/DECIMAL is a null so that when a user first opens the page, nothing is shown inside the text box's.
I have an update query that updates the value of each input box to the respected MySQL Field.
My problem is, for each input box that doesn't get anything typed in, the value of the field switches from a NULL to a 0.
I am having trouble figuring out a way to update the un-touched input's to a NULL and not have all my untouched values go to 0. Can anyone help?
Defining my variables basically goes like:
if(nullBlank($_POST['variable1']) == false)
$variable1 = $_POST['variable1'];
else
$variable = "";
I've also tried: $variable = null;
My update query basically looks like this:
mysql_query("UPDATE `table` SET `variable1`= '" . $variable1 . "' WHERE something = something
My nullBlank() function
function nullBlank($data)
{
if(is_null($data))
$value = true;
elseif(strlen($data) <= 0)
$value = true;
elseif($data === "")
$value = true;
else
$value = false;
return $value;
}
Set $variable1 to "NULL" (the string). This way it will end up in the query as NULL, which is what represents NULL in SQL.
Perhaps change your code for null checks to
if (is_null($myVariable)) {
$sql .= "$columnName= NULL";
} else {
$sql .= "$columnName= '" . mysql_real_escape_string($myVariable) . "'";
}
then call this for each value and it will either null it or quote it

How i will make a LIKE search in the following code?

I've got the following code which is something like a form search engine with multiple inputs where the results are kinda absolute concerning the number of characters etc(perfect match)
.
// build array of field names=============================================================================
$fields=array('user','customer','vessel','country',
'port','eta','service_station','type_of_service',
'case_reference','status');
// initialize empty array for WHERE clauses
$wheres=array();
// loop through field names, get POSTed values,
// and build array of WHERE clauses, excluding false values
foreach ($fields as $field) {
// get existing field value from POST, mark missing or empty value as FALSE
${$field} = isset($_POST[$field]) && trim($_POST[$field])!=''
? trim($_POST[$field]) : false;
// add to array of WHERE clauses only if value is not FALSE
if (${$field}) { $wheres[]="$field='".${$field}."'"; }
}
// build SELECT statement from WHERE clauses
$sql="SELECT * FROM jobs WHERE ".
(!empty($wheres) ? implode(" AND ",$wheres) : '1=1').
";";
What i want to do is add an input in the form
<label for="special">Special Search</label>
<input type="text" name="special" id="special_search">
where the user would be able to search in the case_reference field and get the results that match the first four characters. Also i would like this new input to work the same as the others as far as the AND or OR and TRUE or FALSE statements are concerned.
All help appreciated thank you in advance:)
UPDATE : Instead of rewriting the whole thing i came up with the following code at the begining of my previous :
$joker = $_POST['special'];
$joker1 = substr($joker1, 0, 4);
if(isset($_POST['case_reference']) && !empty($_POST['case_reference'])
&& empty($_POST['special'])) {
} else { $_POST['case_reference'] = $joker1; }
It is working for now but anyone can confirm that it would be okay in future??
From the SQL:
$sql="SELECT * FROM jobs WHERE ". (!empty($wheres) ? implode(" AND ",$wheres) : '1=1').";";
Just simply add a variable for special:
$special = $_POST['special']; // this will get the data from the textbox
then add it to the sql statement
$sql="SELECT * FROM jobs WHERE LIKE $special 'aaaa%' AND ". (!empty($wheres) ? implode(" AND ",$wheres) : '1=1').";";
Rewritten avoiding variable variable names, and using mysql_real_escape_string (although you should use mysqli or pdo):-
<?php
// build array of field names=============================================================================
$fields=array('user','customer','vessel','country',
'port','eta','service_station','type_of_service',
'case_reference','status');
// initialize empty array for WHERE clauses
$wheres = array('1=1');
// loop through field names, get POSTed values,
// and build array of WHERE clauses, excluding false values
foreach ($fields as $field)
{
// get existing field value from POST, mark missing or empty value as FALSE
if (isset($_POST[$field]) && trim($_POST[$field])!='')
{
$wheres[]="`$field`='".mysql_real_escape_string(trim($_POST[$field]))."'";
}
}
if (isset($_POST['special']) && trim($_POST['special'])!='')
{
$wheres[] = " case_reference' LIKE '".mysql_real_escape_string(trim($_POST['special']))."%'";
)
// build SELECT statement from WHERE clauses
$sql="SELECT * FROM jobs WHERE (".implode(" AND ",$wheres).") ;";
?>

PHP - SQL select first column with no data

How do I find the first column with no data?
//column pet1='dog'
//column pet2=''
//column pet3=''
//column pet4='cat'
if($F=="getempty"){
$uid=$_GET["uid"];
$sql = mysql_query("SELECT DISTINCT pet1,pet2,pet3,pet4 FROM a WHERE uid='".$uid."' AND pet1='' OR pet2='' OR pet3=''OR pet4=''");
while($column=mysql_fetch_field($sql)){
$empty=$column->name;
echo json_encode(array("empty"=>$empty));
}
}else{}
I keep trying but so far it just returns all column names if one is empty
pet1,pet2,pet3,pet4
DISTINCT will combine the rows which are exactly alike (having all the selected columns the same) and return them.
To get the name of the first empty column, use a query like:
SELECT
CASE
WHEN pet1 = '' THEN 'pet1'
WHEN pet2 = '' THEN 'pet2'
WHEN pet3 = '' THEN 'pet3'
WHEN pet4 = '' THEN 'pet4'
ELSE NULL
END AS firstempty
FROM a
WHERE uid = '$uid';
The idea is that the CASE statement checks each one in order, and finding an empty one returns the column name without checking the rest of them.
Don't forget to escape $uid with mysql_real_escape_string() before passing it to the query.
$uid = mysql_real_escape_string($uid);
Since we're now getting the column name inside a field called firstempty, we'll also need to change the way it's fetched:
while($row = mysql_fetch_assoc($sql)){
$empty = $row['firstempty'];
echo json_encode(array("empty"=>$empty));
}

Categories