random images and check boxes problem

azharnusayef
azharnusayef used Ask the Experts™
on
hi i have the following code that displays all images randomly from a given folder . the images is

displayed in a table. my problem is that i want to make a form so that each image has a check box

and i want to save the selected image name  in my data base table (user) in filed   ( name)

can anyone help me please???

this is my code
<?php 
$IMAGE_DIRECTORY = "index_files/";
 
 
$line = "";
$randomNumber= 0;
$imageFiles = array();
$fileName = "";
$x=0;
$total = 0;
$result_array = array();
$pics_per_row = 4;
if ($DIR = opendir($IMAGE_DIRECTORY)) {
        while ($fileName = readdir($DIR)) {
                if (is_dir($IMAGE_DIRECTORY . $fileName)) { continue; }
                if (!preg_match("/\w/", $fileName)) { continue; }
                if (preg_match("/\.gif$|\.jpg$|\.jpeg$/i",$fileName)) {
                        $imageFiles[$x] = $fileName;
                        $x+=1;
                }
        }
        closedir($DIR);
 
        if( count($imageFiles) > 0 ) {
			shuffle($imageFiles);
                foreach($imageFiles as $field => $value) {
					
                        $thumb = '<img src="'.$IMAGE_DIRECTORY.$value.'" alt="'.$value.'"  height="100" width="100"/>';
                        $result_array[] = '<td style="text-align:center;">'.$thumb.'</td>';
                        $total++;
                }
                $counter = 0;
                $output = '<table style="text-align:center; width:100%"><tr>';
                foreach($result_array as $cell) {
                        if($counter == $pics_per_row) {
                                $counter = 1;
                                $output .= '</tr><tr>';
                        } else
                                $counter++;
 
                        $output .= $cell;
                }
                // This is so that a blank cell isn't left if there were 2 <td> tags you need to add in colspan 2 (pics_per_row = 4)
                if($counter < $pics_per_row) {
                        $output .= '<td colspan="'.$pics_per_row - $counter.'"> </td>';
                }
                $output .= '</table></tr>';
                echo $output;
        } else {
                echo 'No files found';
        }
} else {
        echo 'There was a problem generating the gallery';
}
?>

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
Make a form tag around your table containing images, then create a checkbox input, all check boxes should have the same name with [] added. This is the best way to send only selected check boxes to php, for example:
<input type="checkbox" name="imageSelected[]" value="<?php echo $IMAGE_DIRECTORY.$value;?>">
When the form is submitted, php offers you an array $_POST['imageSelected'] containing only checkboxes the user has selected.
Top Expert 2008

Commented:
How do you know which user? Is there only one row in the user table? If not, what is the name of the primary key in the user table, and which PHP variable holds this value?

Change line 48:

                echo $output;

...into this:

                echo '<form method="post">'.$output.'<input type="submit" value="Save"></form>';


Change line 29:

                       $result_array[] = '<td style="text-align:center;">'.$thumb.'</td>';

...into this:

                       $result_array[] = '<td style="text-align:center;">'.
                                                   '<input type="radio" name="thumb" value=".urlencode($value)."/>'.
                                                   $thumb.'</td>';

Use type="radio" because that control allows only one selected image. It seemed like that was what you wanted. Checkboxes allows multiple selections.

At the start of your script, add this:
if($_POST) {
  $thumb = isset($_POST['thumb']) ? $_POST['thumb'] : false;
  if($thumb) {
    mysql_connect('localhost','user','pass');
    mysql_select_db('dbname');
    $thumb = mysql_real_escape_string(stripslashes($thumb));
    $res = mysql_query("update user set name='$thumb' where ??? ");  # identify user
    if(!$res) die(mysql_error());
    # redirect if needed
  }
}

Open in new window

Commented:
And to deal with them you can do something like:

$selectedImages=$_POST['imageSelected'];
foreach ($selectedImages as $myImage)
{
        echo $myImage;
}

Open in new window

Expert Spotlight: Joe Anderson (DatabaseMX)

We’ve posted a new Expert Spotlight!  Joe Anderson (DatabaseMX) has been on Experts Exchange since 2006. Learn more about this database architect, guitar aficionado, and Microsoft MVP.

Commented:
I have added a form submitting to processselection.php:
<?php 
$IMAGE_DIRECTORY = "index_files/";
 
 
$line = "";
$randomNumber= 0;
$imageFiles = array();
$fileName = "";
$x=0;
$total = 0;
$result_array = array();
$pics_per_row = 4;
if ($DIR = opendir($IMAGE_DIRECTORY)) {
        while ($fileName = readdir($DIR)) {
                if (is_dir($IMAGE_DIRECTORY . $fileName)) { continue; }
                if (!preg_match("/\w/", $fileName)) { continue; }
                if (preg_match("/\.gif$|\.jpg$|\.jpeg$/i",$fileName)) {
                        $imageFiles[$x] = $fileName;
                        $x+=1;
                }
        }
        closedir($DIR);
 
        if( count($imageFiles) > 0 ) {
                        shuffle($imageFiles);
                foreach($imageFiles as $field => $value) {
                                        
                        $thumb = '<img src="'.$IMAGE_DIRECTORY.$value.'" alt="'.$value.'"  height="100" width="100"/>';
                        $result_array[] = '<td style="text-align:center;">'.$thumb.'<br><input name="selectedImage"type="checkbox" value="'.$IMAGE_DIRECTORY.$value.'"/></td>';
                        $total++;
                }
                $counter = 0;
                $output="<form name=myform action='processselection.php' method='post'>";      	
                $output .= '<table style="text-align:center; width:100%"><tr>';
                foreach($result_array as $cell) {
                        if($counter == $pics_per_row) {
                                $counter = 1;
                                $output .= '</tr><tr>';
                        } else
                                $counter++;
 
                        $output .= $cell;
                }
                // This is so that a blank cell isn't left if there were 2 <td> tags you need to add in colspan 2 (pics_per_row = 4)
                if($counter < $pics_per_row) {
                        $output .= '<td colspan="'.$pics_per_row - $counter.'"> </td>';
                }
                $output .= '</table></tr>';
                $output.="<input type='hidden' name='posted' value='1'>";
                $output.="</form>";
                echo $output;
        } else {
                echo 'No files found';
        }
} else {
        echo 'There was a problem generating the gallery';
}
?>

Open in new window

Commented:
And this is a sample code for processselection.php:
<?php 
error_reporting(E_ALL);
if (@$_POST['posted']=="1")
{
	$selectedImages=$_POST['imageSelected'];
	foreach ($selectedImages as $myImage)
	{
		//Add code to connect to the database
		$sql="INSERT INTO imageSelectionTable(id, imagePath) values(someValue, '$myImage');
		$rs=mysql_query($sql);
		if ($rs && mysql_affected_rows()>0)
			echo "Image '" .$myImage."' added to the database<br>";
	}
	mysql_free_result($rs);
	echo "<a href='javascript: history.back(1);'>Back</a>";
}
?>

Open in new window

Author

Commented:
it is ok and working , but there is no submit buttom how can i submit my selection?????
Top Expert 2008

Commented:
There is a submit button in the code I suggested:

              echo '<form method="post">'.$output.'<input type="submit" value="Save"></form>';

...I suppose you are talking to profya... :)

Author

Commented:
yes  u r right but i dont want radio buttons. i want check boxes

Author

Commented:
i have changed this in profya code

and in my code line 49

 $output.="<input name='submit' value='Submit' type='submit'/>";



and

processselection.php
<?php 
 
 
$connect=mysql_connect("localhost","root","") or die (mysql_error());
mysql_select_db("project") or  die (mysql_error());
 
error_reporting(E_ALL);
if (@$_POST['posted']=="1")
{
        $selectedImages=$_POST['imageSelected'];
        foreach ($selectedImages as $myImage)
        {
                //Add code to connect to the database
                $sql="INSERT INTO user ('code') values('$myImage')";
                $rs=mysql_query($sql);
                if ($rs && mysql_affected_rows()>0)
                        echo " Image '" .$myImage."' added to the database<br>";
        }
        mysql_free_result($rs);
        echo "<a href='javascript: history.back(1);'>Back</a>";
}
?>

Open in new window

Author

Commented:
when i choose an image and press submit only a blank page appears
Top Expert 2008

Commented:
>> i dont want radio buttons. i want check boxes

You can change the name and "radio" to "checkbox" in the input elements in my code suggestion:

                       $result_array[] = '<td style="text-align:center;">'.
                                                   '<input type="checkbox" name="thumb[]" value=".urlencode($value)."/>'.
                                                   $thumb.'</td>';

Then $_POST['thumb'] will contain an array, as profya explained here: http:#a24885615

What should happen when multiple images are selected? Insert them all in new records in the user table?
Top Expert 2008

Commented:
>> when i choose an image and press submit only a blank page appears

Probably because of an error in the code. Do you have access to web server logs?

Insert SQL error check, change line 15 like this:


                $rs=mysql_query($sql);
                if(!$rs) die(mysql_error());

Open in new window

Author

Commented:
hi , i dont understand u do i need to but the following script in the beginning of my script ??

or in another php file??


if($_POST) {
  $thumb = isset($_POST['thumb']) ? $_POST['thumb'] : false;
  if($thumb) {
    mysql_connect('localhost','user','pass');
    mysql_select_db('dbname');
    $thumb = mysql_real_escape_string(stripslashes($thumb));
    $res = "INSERT INTO user ('code') values('$myImage')";  
    if(!$res) die(mysql_error());
    # redirect if needed
  }
}

Open in new window

Top Expert 2008

Commented:
Either is possible. What is in the action attribute of the form? If there is no action attribute in the form (as I suggested), then it should be in the same script, at the beginning.

If you changed the inputs to checkboxes and changed the name to thumb[], the $thumb variable is an array, and you can handle the input like this:
if($_POST) {
  $thumb = isset($_POST['thumb']) ? $_POST['thumb'] : false;
  if($thumb) {
    mysql_connect('localhost','user','pass');
    mysql_select_db('dbname');
    $values = array();
    foreach($thumb as $t)
      $values[] = "('".mysql_real_escape_string(stripslashes($t))."')";
    $res = mysql_query("INSERT INTO user ('code') values ".implode(',',$values));
    if(!$res) die(mysql_error());
    # redirect if needed
  }
}

Open in new window

Author

Commented:
hi im using yur code but it displays the following error

Syntax error near''code 'values ('. Urlencode ($ value ).')' on line 1
<?php 
 
if($_POST) {
  $thumb = isset($_POST['thumb']) ? $_POST['thumb'] : false;
  if($thumb) {
    mysql_connect("localhost","root","") or die (mysql_error());
    mysql_select_db('project');
    $values = array();
    foreach($thumb as $t)
      $values[] = "('".mysql_real_escape_string(stripslashes($t))."')";
    $res = mysql_query("INSERT INTO user 'code' values ".implode(',',$values));
    if(!$res) die(mysql_error());
    # redirect if needed
  }
}
 
$IMAGE_DIRECTORY = "index_files/";
 
 
$line = "";
$randomNumber= 0;
$imageFiles = array();
$fileName = "";
$x=0;
$total = 0;
$result_array = array();
$pics_per_row = 4;
if ($DIR = opendir($IMAGE_DIRECTORY)) {
        while ($fileName = readdir($DIR)) {
                if (is_dir($IMAGE_DIRECTORY . $fileName)) { continue; }
                if (!preg_match("/\w/", $fileName)) { continue; }
                if (preg_match("/\.gif$|\.jpg$|\.jpeg$/i",$fileName)) {
                        $imageFiles[$x] = $fileName;
                        $x+=1;
                }
        }
        closedir($DIR);
 
        if( count($imageFiles) > 0 ) {
                        shuffle($imageFiles);
                foreach($imageFiles as $field => $value) {
                                        
                        $thumb = '<img src="'.$IMAGE_DIRECTORY.$value.'" alt="'.$value.'"  height="100" width="100"/>';
                        $result_array[] = '<td style="text-align:center;">'.
                                                   '<input type="checkbox" name="thumb[]" value=".urlencode($value)."/>'.
                                                   $thumb.'</td>';
 
                        $total++;
                }
                $counter = 0;
                $output = '<table style="text-align:center; width:100%"><tr>';
                foreach($result_array as $cell) {
                        if($counter == $pics_per_row) {
                                $counter = 1;
                                $output .= '</tr><tr>';
                        } else
                                $counter++;
 
                        $output .= $cell;
                }
                // This is so that a blank cell isn't left if there were 2 <td> tags you need to add in colspan 2 (pics_per_row = 4)
                if($counter < $pics_per_row) {
                        $output .= '<td colspan="'.$pics_per_row - $counter.'"> </td>';
                }
                $output .= '</table></tr>';
              echo '<form method="post"   >'.$output.'<input type="submit" value="Save"></form>';
        } else {
                echo 'No files found';
        }
} else {
        echo 'There was a problem generating the gallery';
}
?>

Open in new window

Top Expert 2008

Commented:
Change line 11 into this:

    $res = mysql_query("INSERT INTO user (code) values ".implode(',',$values));

Commented:
Good done, cxr, any help azharnusayef?

Author

Commented:
hi, i have chanced line 11
but when i select an image the same page reloads and in my database table (user) i found this

.urlencode($value).    saved in filed code , what is this?????
Top Expert 2008

Commented:
Line 45 is wrong:

                                                   '<input type="checkbox" name="thumb[]" value=".urlencode($value)."/>'.

Change it into this:

                                                   '<input type="checkbox" name="thumb[]" value="'.urlencode($value).'"/>'.

>> the same page reloads

Yes, in line 13 you have this:

    # redirect if needed

Change it to this:

    header('Location: PageToRedirectTo.php');
    exit;

Instead of "PageToRedirectTo.php" you must put the name of the page you wish to go to after saving the image/images.

Commented:
PHP parser ignores strings enclosed between single quotes, it does not get inside and see if there is variables or not, I think there is a problem with the line:
'<input type="checkbox" name="thumb[]" value=".urlencode($value)."/>'.
The whole string should be enclosed between double quotes and then use single quotes inside, for example (line 44):

$result_array[] = "<td style='text-align:center;'>".
                                                   "<input type='checkbox' name='thumb[]' value='".urlencode($value)."'/>".
                                                   $thumb."</td>";

Open in new window

Commented:
@cxr: It seems that while I was writing you have fixed the problem and submitted it, I am not stealing your solution by the way.

Author

Commented:
ok  cxr it is now working i really thank you very very much for your effort.
but please i have one more thing that is. if i choose for example 10.jpg and  2.jpg check boxes

how can i save the sum of them i.e  14 in the same filed ???
Top Expert 2008

Commented:
>> if i choose for example 10.jpg and  2.jpg check boxes
>> how can i save the sum of them i.e  14 in the same filed ???

What?

First, you can not sum images, you can only sum numbers. Do you mean to extract the numbers from the file names of the images? If so, how does 10+2 become 14 ?

Author

Commented:
oh im sorry for the mistake ,
i mean to sum the numbers  as they are the name for images and 10+2 =12 for example i was wrong
im sorry
Top Expert 2008

Commented:
Just to make sure I understand you: instead of saving each selected image name in the database, you want to extract the numbers from the file names, and insert the sum of those numbers in a single row in the user table?

Commented:
You can cache the image number (after extracting it from the image name either using regex or using string functions) beside the image path, separating it with comma. When you are about to save it to the database then you can use explode function for example to get the values separated by commas.
For example "dir1/12.jpg, 12" "dir1/2.jpg,2"
Or you can get the image file name and make regex to extract the name without extension and parse it as number and sum it.

Author

Commented:
CXR:    yes that is exactly what i want

Commented:
CXR: not cxr:
I am quitting, although I am who first presented the array of controls idea. Good luck cxr :)
Top Expert 2008
Commented:
Change this line:

                                                   '<input type="checkbox" name="thumb[]" value="'.urlencode($value).'"/>'.

...into this:

                                                   '<input type="checkbox" name="thumb[]" value="'.((int)$value).'"/>'.

Then change the loop like this:
if($_POST) {
  $thumb = isset($_POST['thumb']) ? $_POST['thumb'] : false;
  if($thumb) {
    mysql_connect("localhost","root","") or die (mysql_error());
    mysql_select_db('project');
    $sum = 0;
    foreach($thumb as $number)
      $sum += (int) $number;
    $res = mysql_query("INSERT INTO user (code) values ($sum)";
    if(!$res) die(mysql_error());
    # redirect here
  }
}

Open in new window

Author

Commented:
wow it was really amazing journey through php i 'd like to thank you CXR and profia for your efforts
thanks alot

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial