Jump to content

Recommended Posts

Hello! Can someone please help me to understand this section of code?  It works correctly, but I don't fully understand how it works, which is preventing me from moving further in my program.  Here is the code:

 

if(!empty($_POST['color']) && is_array($_POST['color'])) {
$_POST['color'] = array_map('mysql_real_escape_string', $_POST['color']);
$colors = implode('\'), (\'', $_POST['color']);

           
$query = 'INSERT INTO colors (color) VALUES (\'' . $colors . '\')';
$rs = mysql_query($query);


} else {
// they didn't specify a color, or there was a problem with the data type 
}

 

I understand this much:  If "color" is checked (true) and it's an array, then insert the value of "color" into the database table named "colors".  Else, do nothing.  This will insert the data each in a separate row in my table which is exactly what I want it to do.  Here are my specific questions: 

 

1.  What does 'array_map' and 'mysql_real_escape_string' do? 

2.  What does the '\' do in the line:  $colors = implode('\'), (\'', $_POST['color']);

3.  What does the '\' do in the line:  $query = 'INSERT INTO colors (color) VALUES (\'' . $colors . '\')';

 

Thank you in advance for any explanation you can give me! 

Link to comment
https://forums.phpfreaks.com/topic/86908-help-with-understanding-code/
Share on other sites

A more understandable way to write these two lines:

<?php
$colors = implode('\'), (\'', $_POST['color']);
      	$query = 'INSERT INTO colors (color) VALUES (\'' . $colors . '\')';
?>

would be to use double quotes to delimit the strings instead of single quotes:

<?php
$colors = implode("'), ('", $_POST['color']);
$query = "INSERT INTO colors (color) VALUES ('" . $colors . "')";
?>

 

Ken

 

Actually, looking at question 2. It looks like it may be valid. explode splits a string (by the first argument) into an array.

 

So if you had...

 

<?php

 $str = 'foo,bar,bob';
 $arr = explode(',',$str);
 // you'd end up with.
 echo $arr[0]; // foo
 echo $arr[1]; // bar
 echo $arr[2]; // bob

?>

 

Given your code it would split the string contained in $_POST['color'] on '), ('

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.