do not write empty array fields - php

ik have a html form where i can select some options. I want to write those values comma separated to my database. This is the code i have
$genretotal = $_POST['genre'];
$genre0 = $genretotal[0];
$genre1 = $genretotal[1];
$genre2 = $genretotal[2];
$genre3 = $genretotal[3];
$genre4 = $genretotal[4];
$genre5 = $genretotal[5];
$genre6 = $genretotal[6];
$genre7 = $genretotal[7];
$genre = $genre0 . "," . $genre1 . "," . $genre2 . "," . $genre3 . "," . $genre4 . "," . $genre5 . "," . $genre6 . "," . $genre7;
How can i leave out the empty values?

Try with implode and array_filter
implode(',', array_filter($_POST['genre']));

Why so?
$genre = join(',', array_filter($_POST['genre'], function($sItem)
{
//here I assume your 'not empty' matches PHP empty() function
//if not, then add desired conditions
return !empty($sItem);
}));

$genretotal = $_POST['genre'];
if(isset($genretotal) && count($genretotal)>0)
{//This check array is null or not
$gen_arr = implode(",",$genretotal);
}//end if
echo $gen_arr;
//This is the code you avoid empty values

Related

How do I use str_replace in an IF statement?

I have an input field that automatically inserts the value of 'www.' before anything the user types. The data in the input field then gets inserted into a table.
Using PHP, I am trying to remove/strip the instance of 'www.' IF an '#' symbol is typed into the input field. I cannot seem to get this to work, looking at what is output in my SQL Table. I'm using an empty variable in $var to replace the 'www.'
Here is my code:
if(strpos($_POST['Link'], '#') !== false) {
$webvar = 'Twitter';
str_replace('www.', '', $var);
$link = mysqli_real_escape_string($conn, '<a href='."'".'https://'.'twitter.com/'.$_POST['Link']."' ".'target='."'".'_blank'."'".'>'.$webvar.'</a>');
}
your question is unclear but something like this ?
if (strpos($_POST['Link'], '#')) {
$webvar = 'Twitter';
$link = mysqli_real_escape_string($conn, '<a href=' . "'" . 'https://' . 'twitter.com/' . str_replace('www.', '', $_POST['Link']) . "' " . 'target=' . "'" . '_blank' . "'" . '>' . $webvar . '</a>');
}
You should directly assign the value back to the variable (although it's not clear what $var is, it sounds like it should be $_POST['Link'])
$var = str_replace('www.', '', $_POST['Link']);

PHP/MySQL Sanitation Issue

From LDAP I'm querying my users and this code sets them as a variable in the quoted format I need to run the MySQL query which would be 'username','other_username', etc...
foreach ($prefs as $who => $pref) {
if (strpos($who, 'public') === false) {
$team_users_string .='\'' . $who . '\',';
}
When I try to sanitize the command with the following code it converts the string to \'username\',\'other_username\', what can I do to correct this?
$team_users = rtrim($team_users_string, ",");
$start_date = $_POST['start_year'] . '-' . $_POST['start_month'];
$end_date = $_POST['end_year'] . '-' . $_POST['end_month'];
echo 'Welcome, <strong>' . $user . '</strong><br />';
echo '<br />';
echo '<strong>Selected Start Date:</strong> ' . $start_date . '<br />';
echo '<strong>Selected End Date:</strong> ' . $end_date . '<br />';
mysql_real_escape_string($team_users),
mysql_real_escape_string($start_date),
mysql_real_escape_String($end_date));
$query = "SELECT * FROM vacation WHERE user_name in ($team_users) AND day BETWEEN '$start_date-01' AND '$end_date-31'";
Your problem is that you're adding the quote characters before you pass the string to mysql_real_escape_string(). So the literal quotes become escaped by that function.
You could avoid this by using mysql_real_escape_string(), and then delimiting the result in quotes.
Also I'd use an array and implode() the array to get commas, instead of being forced to rtrim() the last comma.
foreach ($prefs as $who => $pref) {
if (strpos($who, 'public') === false) {
$team_users_array[] = "'" . mysql_real_escape_string($who) . "'";
}
}
$team_users = implode(",", $team_users_array); // no rtrim needed

How to get rid of empty values when adding string in php

I have something like this:
public function options()
{
$out = '';
$docs = $this->getAll();;
foreach($docs as $key => $doc) {
$out .= ',{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
}
return $out;
}
It gives me a list of options from the DB, but it also gives me a null value at the top.
if I write it like this:
public function options()
{
//$out = '';
$docs = $this->getAll();;
foreach($docs as $key => $doc) {
$out = '';
$out .= '{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
}
return $out;
}
It doesn't give me the null value but it only returns one value.
$out .= ',{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
In this line if I don't add an , it gives me an error message, This because I have $out = ''; at the top. Now can you guys give me an idea how can I get all the values from the DB without the empty value at the beginning.
I also have another question , why we use ;; (double semicolon) in this code:
$docs = $this->getAll();;
test $out to see if it has any length, if so add the comma and the line, otherwise just set it to be the line:
$out="";
foreach($docs as $key=>$doc){
if(strlen($out)){
$out.=',{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
}else{
$out='{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
}
}
as to your other question, er, you wrote the code, so why did you put a double semi-colon?
This is not the correct way to build JSON. First create an array, and use json_encode() on it.
I'd suggest using an array instead to hold the individual values, and using join to concatenate them together.
public function options()
{
$docs = $this->getAll();
// Create an empty array
$items = array();
foreach($docs as $key => $doc) {
// "Push" an item to the end of the array
$items[] = '{"label" : "' . $doc['name'] . '", "value" : "' . $doc['id'] .'"}';
}
// Join the contents together
$out = join(",", $items);
return $out;
}
Also, the double semi-colon is completely unnecessary.

PHP implode quoted string

$brand_condition = ' AND ' . mysql_real_escape_string($brand_selection) . ' IN ';
$brand_condition .= $quote10 . '"'. mysql_real_escape_string($brand_value) . '"' .$quote9;
$brand_conditions[] = $brand_condition;
$query .= implode(' AND ', $brand_conditions) . '';
This produces: AND manufacturer IN ("brand1,brand2")
Since I'm using the IN statement, I need the values to be quoted. At the same time, I am escaping potential quotes with mysql_real_escape_string.
Does anyone see a simple way to get around this small problem?
function quote_escape(&$str) {
$str = '"' . mysql_real_escape_string(chop($str)) . '"';
}
$brands = explode(',', $brand_value);
array_walk($brands, "quote_escape");
$brands = implode(',', $brands);
or
function quote_escape($str) {
return '"' . mysql_real_escape_string(chop($str)) . '"';
}
$brands = implode(',', array_map("quote_escape", explode(',', $brand_value)));
How about $brand_conditions[] = '"'.$brand_condition.'"'; so your adding quotes right before you add the brand_condition in your array.
$concurrent_names = array("O'reilly", 'Tupac "MC New York" Shakur', 'Nemoden');
$escaped_concurrent_names = array_map('mysql_real_escape_string', $concurrent_names);
$condition = 'WHERE name in ("'.implode('", "', $escaped_concurrent_names).'")';
Use this to add quotes for imploded string.
$values = implode( " ',' ", array_values($values) );
$brands=array(nokia,samsung,xiomi);
$brands=implode(" ',' ",$brand);
//$brands='nokia','samsung','xiomi';
WHERE column_name IN ($brands)

Split Comma Separated Names with PHP

I have names in the form of Lastname, Firstname. In my database I have a different field for both the first and last.
I would like to use PHP to read everything before the comma as the lastname and everything after the comma as the firstname. What is the best way to accomplish this?
list($Lastname,$Firstname) = explode(",",$Name);
<?php
$names = explode( "," , $allNames);
// $names[0] and names[1] are first and last names
?>
with the explode function.
<?php
list($firstname, $lastname) = explode(',','Lastname, Firstname',2);
echo $firstname.' '.$lastname;
?>
If you'll use list();
while( list($fname,$lname) = explode(", ", $db->fetch() ) ) {
echo $lname . " " . $fname . "<br />";
}
Without list() and assining an array;
$name = explode( ", ", $db->fetch()->nameField );
// may be you want to do something with that array
// do something
// echoing
foreach( $name as $fname=>$lname ) {
echo $lname . " " . $fname . "<br />"
}
As nobody has mentioned it yet, to expressly meet the question requirements, you'll need to use the third parameter to explode()
list($lastname, $firstname) = explode(',', $name, 2);

Categories