Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 426
  • Last Modified:

delete the last comma

         $q = 'INSERT INTO '.$tablename.' (';
        foreach ($cols as &$columnname) {
          $q.=$columnname.',';
          }        
        $q = substr($q,'',-1);
        $q.=') VALUES (';
        foreach ($cols as &$columnname) {
        $q.='\''.mysql_real_escape_string($$columnname).'\',';        
        }
        $q = substr($q,'',-1);
        $q.=')';

echo $q;

Open in new window



this code worked with another page
but this line

$q = substr($q,'',-1);

is generating warning and there is no output

Warning: substr() expects parameter 2 to be long, string given in





I want to replace the last
,
with
nothing
0
rgb192
Asked:
rgb192
1 Solution
 
Pratima PharandeCommented:
0
 
Pratima PharandeCommented:
or try this

substr_replace

$q = substr_replace($q,'',-1);
0
 
InsoftserviceCommented:
if (substr($string, -1, 1) == ',')
{
  $string = substr($string, 0, -1);
} // will check if last character is comma.

//if you want to remove all commas from the end of a line use the simpler:
$string = rtrim($string, ',');

//The rtrim function (and corresponding ltrim for left trim) is very useful as you can specify a range of characters to remove, i.e. to remove commas and trailing whitespace

$string = rtrim($string, ", \t\n");



// Please print value of $q before
echo "Before ".$q;
 $q = substr($q,'',-1);
        $q.=')';

echo "After =".$q;
0
 
Ray PaseurCommented:
You should consider using array_map() and implode() to build query strings.  This will give you cleaner code.  Snippet is untested but probably valid in principle.  You might need to use backticks around column names, or not.

// COLUMN NAMES
$cnames = array
( 'name'
, 'email'
, 'phone'
)
;

// DATA TO BE INSERTED
$values = array
( "O'Reilly"
, "Bill.OReilly@Fox.com"
, "800-555-1212"
)
;

// ESCAPE THE DATA
$safe_values = array_map('mysql_real_escape_string', $values);

// BUILD THE QUERY PARTS
$cols = "`" . implode("`,`", $cnames)      . "`";
$vals = "'" . implode("','", $safe_values) . "'";

// BUILD THE QUERY STRING
$sql = "INSERT INTO $tablename ( $cols ) VALUES ( $vals )";

// SHOW THE QUERY
var_dump($sql);

Open in new window

Best regards, ~Ray
0
 
rgb192Author Commented:
answered a small question and changed the way I insert into tables in the future

thanks
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now