PHP - Remove extra comma - php

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; }

Related

Finding and sorting data from an unsorted MySQL table / multidimensional array in PHP

I have a table that looks like this:
ID
app_id
field_id
value
xxx
yyy
9
First Name
xxx
yyy
2
Last Name
The "value" column contains data like First Name, Last Name, Adress, E-Mail and so on. The only way to identify what kind of value is situated in the "value" column, is by the "field_id". Meanwhile the "app_id" acts as an unique identifier for the user / a User ID.
(The table is provided by a WordPress Plugin, therefore however terrible it might be I cannot change this.)
This means to get First name and last name of an user I would have to search for 2 rows with the same app_id and then get the value column where the field_id is 9 for first name and 2 for last name.
So what I wanna print out is something like: (pseudo code)
for ($app_id) {
if (app_id == $app_id && field_id = 9) {
$first_name = value
}
if (app_id == $app_id && field_id = 2) {
$last_name = value
}
echo $first_name . $last_name;
}
So far I only have the following code, which puts all the data in a multidimensional array:
$mysqli = new mysqli("localhost","dbane","dbpass","dbuser");
$mysqli->set_charset("utf8mb4");
$fields = $mysqli -> query("SELECT * FROM name_of_table");
$results = $fields->fetch_all();
foreach ($results as $result) {
foreach ($result as $key => $value) {
/* Lost what to do here */
}
}
How would I go about getting the first name and last name of each user and put them together?
The database contains about 20.000 rows so using multiple mysqli_queries is not an option as the load time is 10min.+ and puts a terrible load on the server.
I solved it doing the following, with the help of RiggsFolly:
for ($i = $count; $i >= ($count - 1000); $i--) {
$data = $mysqli -> query("SELECT * FROM table_name WHERE app_id = $i AND field_id IN (2,9,15,5,10,11,6,3)");
$names = $data->fetch_all();
foreach ($names as list($a, $b, $c, $d)) {
switch ($c)
case 9:
$first_name = $d;
break:
case 15:
$last_name = $d;
break;
}
}

Calculate no of fields in MYSQL between two data types

OK weird question.
Table consists of multiple fields. Some with data type int(5) and the rest with datatype int(11)
So lets take a row...
id =>int(5)
var1 =>int(11)
var2 =>int(11)
var3 =>int(11)
var4 =>int(11)
var5 =>int(5)
var6 =>int(11)
var7 =>int(11)
var8 =>int(11)
How can I count the fields in PHP BETWEEN id (int(5)) and var (int(5))
I need to return the values in the fields between using php... but Im stuck. Bad table design doesnt help...but Im stuck with it.
The full scenario is that i need to create an if statement which says, output the name and and data of the int(5) field IF any of the fields between it and the next int(5) contain data
sorry... ugly I know!!!
If run this so far
$sql2 = 'SHOW COLUMNS from services2';
$result2 = getDBResults($sql2, $level, $testing);
$total = count($result2);
$i=2;
while ($i<($total-1))
{
$data = $result2[$i]['Field'];
if ($result2[$i][1]=='int(5)')
{
$html .= '<h2>'.preg_replace('/(?<!\ )[A-Z]/', ' $0', $result2[$i]['Field']).'</h2>';
}
else
{
];
// "$result - This is a seperate query run previously to get the row
if ($result[0][$data] == 1)
{
$html .= '<p>'.preg_replace('/(?<!\ )[A-Z]/', ' $0', $data).'</p>';
}
}
$i++;
}
I have not had a chance to actually test this, so dont beat me up if you need to tweek it a bit to smooth off any rough edges.
But its a fairly standard, if not totally simple, process of processing over the column names result array in a loop and just remembering the last int(5) column name in a variable so you can use it, if and only if, you have found some data in any int(11) column types before seeing the next int(5) column type.
Now I understand why you had trouble explaining what you wanted, I am having the same trouble describing a solution.
Anyway, have a look at this code and see if it makes any sence to you.
$sql2 = 'SHOW COLUMNS from services2';
$columns = getDBResults($sql2, $level, $testing);
$total = count($columns);
$print_column = null;
$found_data = false;
foreach ( $columns as $idx => $column ) {
// skip first 2 columns
if ($idx < 3 ) { continue; }
// first time thru loop so remember the first int5 column name we saw
if ( $column['Type'] == 'int(5)' && empty($print_column) ) {
$print_column = $column['Field'];
$found_data = false;
continue;
}
// found the next int5 column, do we need to print anything
if ( $column['Type'] == 'int(5)' && $found_data ) {
// This is where you would do any output creation,
// I just kept it simple.
echo $result[0][$print_column];
// reset state and the next field that might be printed.
$found_data = false;
$print_column = $column['Field'];
continue;
}
// This may not need to be an if, but just in case you have other field types
// that you are not interested in processing I made it an if.
if ( $column['Type'] == 'int(11)' && ! empty($result[0][$column['Field']]) ) {
$found_data = true;
}
} // endforeach

how to insert different comma separated values into different coloumns in mysql

I am taking two comma separated values from the database from different coloumn(supplierrouteallocation:1000,1200 and routesymbol:10xx,12xx) and i want to insert this value into the another table into the different column for example like this
route symbol
1000 10xx
1100 11xx
but i tried its not working can anyone helpme .thanks
my code
$routes = explode(",",$supplierrouteallocation);
$symbol = explode(",",$routesymbol);
$count=count($routes,$symbol);
for($i=0;$i<$count;$i++)
{
$sql_insertroute="INSERT INTO `fms`.`routestable` (
`id` ,
`route`
`routesymbol`
)
VALUES (NULL ,'$routes[$i]','$symbol[$i]')
";
mysql_query($sql_insertroute);
}
You've got various mistakes :
count() only accepts a single array
you're missing a coma in your request : ('id', 'route'[,] 'routesymbol')
Here's a piece of code which should work for you :
// get data
$routes = explode(",",$supplierrouteallocation);
$symbols = explode(",",$routesymbol);
// prepare the request
$sql_insertroute = "INSERT INTO `fms`.`routestable` (`id`, `route`, `routesymbol`) VALUES ";
// create an insert line per data couple
$vals = array();
$n = max(count($routes), count($symbols));
for($i=0;$i<$n;$i++) {
$route = isset($routes[$i]) ? "'".$routes[$i]."'" : "NULL";
$symbol = isset($symbols[$i]) ? "'".$symbols[$i]."'" : "NULL";
array_push($vals, "(NULL, $route, $symbol)");
}
// join those lines with comas, and add'em to the request
$sql_insertroute .= implode(', ', $vals);
Try this
$sql_insertroute="INSERT INTO `fms`.`routestable` (`id`,`route`,`routesymbol`) VALUES (NULL,'".$routes[$i]."','".$symbol[$i]."')";

php search/replace empty records in mysql

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

php - Insert data from checkbox array into MySQL

I have a form for registering for weekly summer camps. There are checkboxes to select which camp the person is signing up for that look like this:
<div class="pscdiv"><input type="checkbox" class="psc" name="camps[]" value="psc_1"/><label for="psc_1">AM - Week 1: Camp Description</label></div>
There are about 30 of them total. What I'm trying to do is take the $_POST['camps'] variable on the next page and break it into something I can insert into a MySQL table that has a structure like this:
regid | psc_1 | psc_2 | psc_3 | ...
My code:
if(!empty($_POST['camps'])) {
$boxes=$_POST['camps'];
while (list ($k,$camp) = #each ($boxes)) {
$camp_string .= "'$camp',";
}
}
// The above to create a comma separated string
$camp_string = (substr($camp_string,-1) == ',') ? substr($camp_string, 0, -1) : $camp_string;
// To remove the trailing comma
$newreg_camps = mysql_query("INSERT INTO camps_registered (regid,$camp_string) VALUES ($regid,$camp_string)");
The column names (other than regid which I specify earlier in the script) are the same as the data being put into them. It was the easiest thing I could think of at the time.
I'm not sure what I'm missing.
--
Update#1 (in reference to a comment below)
if(!empty($_POST['camps'])) {
$box=$_POST['camps'];
while (list ($key,$val) = #each ($box)) {
$camp_totals += $campcost[$val];
echo "$campdesc[$val] - $$campcost[$val]";
}
}
Why not name the checkboxes something different like the names of the columns, so that your $_POST comes back as:
// print_r($_POST);
array(
'regID' => 1,
'camp_filmore' => 1,
'camp_greenwald' => 1
'camp_idunno' => 1
);
From there it's fairly simple to build your query:
$query = "INSERT INTO registered (".implode(array_keys($_POST), ", ") . ") ".
"VALUES (" . implode(array_values($_POST), ", ").")";
You should obviously check to make sure the values of $_POST are properly escaped and sanitized before inserting.
A nice trick to remove the trailing comma would be.
$camp_string = rtrim($camp_string,',');
Anyway your query is not formated correctly.
INSERT INTO camps_registered (regid,'psc_1', 'psc_2', 'psc_3') VALUES ($regid,psc_1', 'psc_2', 'psc_3')
You cannot have single quotes in the first bracket
I think you should be looking at implode and you can easily add addition strings to it...
so e.g.
$comma_seperated = implode(',', $boxes);
$subscribed = $regid . ',' . $comma_seperated;

Categories