www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 17

Thread: Sintaks error when i use foreach

  1. #1
    Join Date
    Nov 2012
    Posts
    1

    Sintaks error when i use foreach

    The code below gives a sintaks error when I'am trying to send path to the db!
    Could you please help me solve the problem

    Error:

    INSERT INTO imloop (', 'image1'') VALUES (','Z:\tmp\phpB8.tmp'')
    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '', 'image1'') VALUES (','Z:\tmp\phpB8.tmp'')' at line 1


    Code:
    foreach($active_keys as $key)
    {
    	@move_uploaded_file($_FILES[$fieldname]['tmp_name'][$key], $uploadFilename[$key])
    		or error('receiving directory insuffiecient permission', $uploadForm);
    		
    		
    		$query_part_1 = '';
    $query_part_2 = '';
    $i = 1;
    		
    		   $query_part_1 .= ", 'image" . $i++ . "'";
        $query_part_2 .= ",'" . $uploadFilename[$key]. "'"; 
    
    
    $query = "INSERT INTO `imloop` ('" .$query_part_1. "') VALUES ('" .$query_part_2. "')";
    		
    		
    		mysql_query($query) or exit($query . '<br />' . mysql_error()); 
    		
    		mysql_close($connection);
    	 }

  2. #2
    Join Date
    Jul 2007
    Location
    Wisconsin
    Posts
    468
    PHP Code:
    INSERT INTO imloop (', 'image1''VALUES (','Z:\tmp\phpB8.tmp''
    Looks like you've got some messed up quotation marks in your query.

    a single quote for the first var, and a mixed (open single, two closing singles) for the second for both KEYS and VALUES


    edit: looking deeper, there's more "funky" stuff happening when you build the query strings. You're building your KEYS starting with a comma, which is invalid.

    suggestion:
    PHP Code:
    // add the comma AFTER you write the key/values to the strings
    $query_part_1 .= " 'image" $i++ . "',";
    $query_part_2 .= " '" $uploadFilename[$key]. "',"
    then, you need to make sure you remove the trailing comma when you build the full query string:

    PHP Code:
    $query_part_1 preg_replace("/,$/","",$query_part_1); // remove the comma at the end of the string
    $query_part_2 preg_replace("/,$/","",$query_part_2); 
    and remove the single-quotes from the KEYS/VALUES from this line:

    PHP Code:
    $query "INSERT INTO `imloop` (" .$query_part_1") VALUES (" .$query_part_2")"
    Last edited by OctoberWind; 11-05-2012 at 03:23 PM.

  3. #3
    Join Date
    May 2012
    Posts
    17
    Thanks a lot I will test it

  4. #4
    Join Date
    May 2012
    Posts
    17
    Code:
    foreach($active_keys as $key)
    {
    	@move_uploaded_file($_FILES[$fieldname]['tmp_name'][$key], $uploadFilename[$key])
    		or error('receiving directory insuffiecient permission', $uploadForm);
    				
    		$query_part_1 = '';
    $query_part_2 = '';
    $i = 1;
    		
    	//	   $query_part_1 .= ",'image" . $i++ . "'";
       // $query_part_2 .= ",'" . $_FILES[$fieldname]['tmp_name'][$key] . "'"; 
      // $query_part_2 .= ",'" . $uploadFilename[$key] . "'"; 
       
       // add the comma AFTER you write the key/values to the strings
    $query_part_1 .= " image" . $i++ . ",";
    $query_part_2 .= " '" . $uploadFilename[$key]. "',";  
       
       $query_part_1 = preg_replace("/,$/","",$query_part_1); // remove the comma at the end of the string
    $query_part_2 = preg_replace("/,$/","",$query_part_2); 
    
    $query = "INSERT INTO `imloop` (" .$query_part_1. ") VALUES (" .$query_part_2. ")";
    		
    		mysql_query($query) or exit($query . '<br />' . mysql_error()); 
    		
    		
    	 }	
    		
    mysql_close($connection);
    I have changed the code as you told me and it work fine.
    But it locate the image path just in "image1"

    Something like this
    id image1 image2 image3 image4 image5 image6

    1 pic1
    2 pic2

  5. #5
    Join Date
    May 2012
    Posts
    17
    but I need to get something like this

    id image1 image2 image3 image4 image5 image6

    1 pic1 pic2 pic2 pic2 pic2 pic2
    2

  6. #6
    Join Date
    Jul 2007
    Location
    Wisconsin
    Posts
    468
    Now that I look at it again, you will need to move these four lines outside of the foreach loop:

    PHP Code:
    $query_part_1 preg_replace("/,$/","",$query_part_1); // remove the comma at the end of the string
    $query_part_2 preg_replace("/,$/","",$query_part_2); 

    $query "INSERT INTO `imloop` (" .$query_part_1") VALUES (" .$query_part_2")";

    mysql_query($query) or exit($query '<br />' mysql_error()); 

  7. #7
    Join Date
    May 2012
    Posts
    17
    Code:
    foreach($active_keys as $key)
    {
    @move_uploaded_file($_FILES[$fieldname]['tmp_name'][$key], $uploadFilename[$key])
      or error('receiving directory insuffiecient permission', $uploadForm);
     
      $query_part_1 = '';
    $query_part_2 = '';
    $i = 1;
     
       // add the comma AFTER you write the key/values to the strings
    $query_part_1 .= " image" . $i++ . ",";
    $query_part_2 .= " '" . $uploadFilename[$key]. "',";
     
      
      }
    I have taken out this part of script but that doesn't give any result ! In this case it just put one path.

    Code:
    $query_part_1 = preg_replace("/,$/","",$query_part_1); // remove the comma at the end of the string
    $query_part_2 = preg_replace("/,$/","",$query_part_2);
    $query = "INSERT INTO `imloop` (" .$query_part_1. ") VALUES (" .$query_part_2. ")";
      mysql_query($query) or exit($query . '<br />' . mysql_error());
    mysql_close($connection);

  8. #8
    Join Date
    Jul 2007
    Location
    Wisconsin
    Posts
    468
    Put these three lines BEFORE the foreach:

    PHP Code:
    $query_part_1 '';
    $query_part_2 '';
    $i 1

  9. #9
    Join Date
    May 2012
    Posts
    17
    now it gives an error like bellow but it adds data the same way

    INSERT INTO `imloop` ( image1 image2) VALUES ( 'Z:/home/multiple/www/uploaded_files/1352231075-1.jpg' 'Z:/home/multiple/www/uploaded_files/1352231075-2.jpg')
    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'image2) VALUES ( 'Z:/home/multiple/www/uploaded_files/1352231075-1.jpg' 'Z:/home' at line 1

  10. #10
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,144
    I have not looked closely at your code, but the end result is that you do not have commas between the names in the column list nor between the values in the values list.
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  11. #11
    Join Date
    May 2012
    Posts
    17
    May be I should put inside foreach something like

    while i<$key
    i++

  12. #12
    Join Date
    May 2012
    Posts
    17
    I have chaned the code like bellow but it gives me an error

    foreach($active_keys as $key)
    {
    @move_uploaded_file($_FILES[$fieldname]['tmp_name'][$key], $uploadFilename[$key])
    or error('receiving directory insuffiecient permission', $uploadForm);



    $cols[] = $query_part_1;
    $data[] = $query_part_2;

    $query_part_1 .= " image" . $i++ . ",";
    $query_part_2 .= " '" . $uploadFilename[$key]. "',";

    $cols = array_map ('mysql_real_escape_string', $cols);
    $data= array_map ('mysql_real_escape_string', $data);



    $query = 'INSERT INTO `imloop` (' . implode(',', $cols) . ') VALUES ("' . implode('","', $cols) . '")';

    }
    mysql_query($query) or exit($query . '<br />' . mysql_error());

    mysql_close($connection);


    INSERT INTO `imloop` (, image,, image, image1,, image, image1, image2,, image, image1, image2, image3,, image, image1, image2, image3, image4,) VALUES (""," image,"," image, image1,"," image, image1, image2,"," image, image1, image2, image3,"," image, image1, image2, image3, image4,")
    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' image,, image, image1,, image, image1, image2,, image, image1, image2, image3,,' at line 1

  13. #13
    Join Date
    Jul 2007
    Location
    Wisconsin
    Posts
    468
    what does your $active_keys array look like? can you please print_r() that, and post it here?

    You loop is getting really messy, there is no reason to be array_mapping or imploding anything.

  14. #14
    Join Date
    May 2012
    Posts
    17
    The code is like this


    <?php

    // filename: upload.processor.php

    // first let's set some variables

    include("conf.php");

    // open database connection
    $connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
    //$db = mysql_connect($host, $user, $pass) or die ("Unable to connect!");

    // select database
    mysql_select_db($db) or die ("Unable to select database!");


    // make a note of the current working directory, relative to root.
    $directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);

    // make a note of the directory that will recieve the uploaded files
    $uploadsDirectory = $_SERVER['DOCUMENT_ROOT'] . $directory_self . 'uploaded_files/';

    // make a note of the location of the upload form in case we need it
    $uploadForm = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'multiple.upload.form.php';

    // make a note of the location of the success page
    $uploadSuccess = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'multiple.upload.success.php';

    // name of the fieldname used for the file in the HTML form
    $fieldname = 'file';

    //echo'<pre>';print_r($_FILES);exit;





    // Now let's deal with the uploaded files

    // possible PHP upload errors
    $errors = array(1 => 'php.ini max file size exceeded',
    2 => 'html form max file size exceeded',
    3 => 'file upload was only partial',
    4 => 'no file was attached');

    // check the upload form was actually submitted else print form
    isset($_POST['submit'])
    or error('the upload form is neaded', $uploadForm);

    // check if any files were uploaded and if
    // so store the active $_FILES array keys
    $active_keys = array();
    foreach($_FILES[$fieldname]['name'] as $key => $filename)
    {
    if(!empty($filename))
    {
    $active_keys[] = $key;
    }
    }

    // check at least one file was uploaded
    count($active_keys)
    or error('No files were uploaded', $uploadForm);

    // check for standard uploading errors
    foreach($active_keys as $key)
    {
    ($_FILES[$fieldname]['error'][$key] == 0)
    or error($_FILES[$fieldname]['tmp_name'][$key].': '.$errors[$_FILES[$fieldname]['error'][$key]], $uploadForm);
    }

    // check that the file we are working on really was an HTTP upload
    foreach($active_keys as $key)
    {
    @is_uploaded_file($_FILES[$fieldname]['tmp_name'][$key])
    or error($_FILES[$fieldname]['tmp_name'][$key].' not an HTTP upload', $uploadForm);
    }

    // validation... since this is an image upload script we
    // should run a check to make sure the upload is an image
    foreach($active_keys as $key)
    {
    @getimagesize($_FILES[$fieldname]['tmp_name'][$key])
    or error($_FILES[$fieldname]['tmp_name'][$key].' not an image', $uploadForm);
    }

    // make a unique filename for the uploaded file and check it is
    // not taken... if it is keep trying until we find a vacant one
    foreach($active_keys as $key)
    {
    $now = time();
    while(file_exists($uploadFilename[$key] = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name'][$key]))
    {
    $now++;

    }
    }


    // now let's move the file to its final and allocate it with the new filename
    foreach($active_keys as $key)
    {
    @move_uploaded_file($_FILES[$fieldname]['tmp_name'][$key], $uploadFilename[$key])
    or error('receiving directory insuffiecient permission', $uploadForm);

    $query_part_1 .= " image" . $i++ . ",";

    $query_part_2 .= " '" . $uploadFilename[$key]. "',";


    }

    $cols[] = $query_part_1;
    $data[] = $query_part_2;
    $cols = array_map ('mysql_real_escape_string', $cols);
    $data= array_map ('mysql_real_escape_string', $data);

    //$cols = rtrim($cols, ',');
    //$data = rtrim($data, ',');
    $query = 'INSERT INTO `imloop` (' . implode(',', $cols) . ') VALUES ("' . implode('","', $data) . '")';

    mysql_query($query) or exit($query . '<br />' . mysql_error());



    mysql_close($connection);

    # Assuming image1, etc accept null values you could try something like this... Not tested

    #set some variables


    //foreach($active_keys as $key)
    //{

    // }






    // If you got this far, everything has worked and the file has been successfully saved.
    // We are now going to redirect the client to the success page.
    header('Location: ' . $uploadSuccess);

    // make an error handler which will be used if the upload fails
    function error($error, $location, $seconds = 5)
    {
    header("Refresh: $seconds; URL=\"$location\"");
    echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'."\n".
    '"http://www.w3.org/TR/html4/strict.dtd">'."\n\n".
    '<html lang="en">'."\n".
    ' <head>'."\n".
    ' <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">'."\n\n".
    ' <link rel="stylesheet" type="text/css" href="stylesheet.css">'."\n\n".
    ' <title>Upload error</title>'."\n\n".
    ' </head>'."\n\n".
    ' <body>'."\n\n".
    ' <div id="Upload">'."\n\n".
    ' <h1>Upload failure</h1>'."\n\n".
    ' <p>An error has occured: '."\n\n".
    ' <span class="red">' . $error . '...</span>'."\n\n".
    ' The upload form is reloading</p>'."\n\n".
    ' </div>'."\n\n".
    '</html>';
    exit;
    } // end error handler

    ?>

  15. #15
    Join Date
    Jul 2007
    Location
    Wisconsin
    Posts
    468
    Without knowing exactly what's in the $uploadFilename and $active_keys arrays, I had to make a few assumptions, but hopefully with what's here, you can make adjustments as needed.

    You can ignore the kdo() functions, those are my debugs (look at the print_r() results below them)

    PHP Code:
        // I'm making up the $uploadFilename and $active_keys arrays;  based on your code, I think this is how they look
        
        // this is just a zero-based array of the file paths
        //    !! this won't be in your final code !!
        
    $uploadFilename = array("/path/to/file1.jpg""/path/to/file2.jpg""/path/to/file3.jpg""/path/to/file4.jpg""/path/to/file5.jpg""/path/to/file6.jpg");
        
        
    //kdo($uploadFilename, "uploadFilename");
        // ------------ uploadFilename
        // Array
        // (
        //     [0] => /path/to/file1.jpg
        //     [1] => /path/to/file2.jpg
        //     [2] => /path/to/file3.jpg
        //     [3] => /path/to/file4.jpg
        //     [4] => /path/to/file5.jpg
        //     [5] => /path/to/file6.jpg
        // )
        // 
        // ------------ 
        
        // this is just a zero-based array of keys from the $_FILES array
        //    !! this won't be in your final code !!
        
    $active_keys = array(123456);
        
        
    //kdo($active_keys, "active_keys");
        // ------------ active_keys
        // Array
        // (
        //     [0] => 1
        //     [1] => 2
        //     [2] => 3
        //     [3] => 4
        //     [4] => 5
        //     [5] => 6
        // )
        // 
        // ------------
        
        // now let's move the file to its final and allocate it with the new filename
        // as a safety net, I always unset the $key=>$value of a foreach loop prior to using them {I also always use $key=>$value, and not just $value}
        
    unset($key$image);
        foreach(
    $active_keys as $key => $image)
        {
        @
    move_uploaded_file($_FILES[$fieldname]['tmp_name'][$key], $uploadFilename[$key])
        or 
    error('receiving directory insuffiecient permission'$uploadForm);

        
    // i added back-ticks to the db fields, and single quotes to the db values, keeping the trailing comma
        
    $query_part_1 .= " `image" $image"`,";
        
    $query_part_2 .= " '" mysql_real_escape_string($uploadFilename[$key]). "',";     // you can sanitize your inputs here, rather than array_mapping later.
        
    }    

        
    $query_part_1 preg_replace("/,$/"""$query_part_1);
        
    $query_part_2 preg_replace("/,$/"""$query_part_2);

        
    $query "INSERT INTO `imloop` ("$query_part_1 .") VALUES ("$query_part_2 .");"// don't add quotes around FIELDS or VALUES here
        
        //kdo($query, "query");
        // ------------ query
        // INSERT INTO `imloop` ( `image1`, `image2`, `image3`, `image4`, `image5`, `image6`) VALUES ( '/path/to/file1.jpg', '/path/to/file2.jpg', '/path/to/file3.jpg', '/path/to/file4.jpg', '/path/to/file5.jpg', '/path/to/file6.jpg');
        // ------------ 
        
        
    mysql_query($query) or exit($query '<br />' mysql_error()); 
    This next part is pure speculation, and untested code:

    You don't need to loop through $array_keys FOUR TIMES... rather, add all those sanity checks into one loop, and in reality, could probably even be added to the whole "write the db query" loop as well, but that's for a later enhancement.

    PHP Code:
        // Now let's deal with the uploaded files
        
        // possible PHP upload errors
        
    $errors = array(=> 'php.ini max file size exceeded'
        
    => 'html form max file size exceeded'
        
    => 'file upload was only partial'
        
    => 'no file was attached');
        
        
    // check the upload form was actually submitted else print form
        
    isset($_POST['submit'])
        or 
    error('the upload form is neaded'$uploadForm);
        
        
    // check if any files were uploaded and if 
        // so store the active $_FILES array keys
        
    $active_keys = array();
        foreach(
    $_FILES[$fieldname]['name'] as $key => $filename)
        {
            if(!empty(
    $filename))
            {
                
    $active_keys[] = $key;
            }
        }
        
        
    // check at least one file was uploaded
        
    count($active_keys)
        or 
    error('No files were uploaded'$uploadForm);
        
        
        foreach(
    $active_keys as $key)
        {
            
    // check for standard uploading errors
            
    ($_FILES[$fieldname]['error'][$key] == 0)
            or 
    error($_FILES[$fieldname]['tmp_name'][$key].': '.$errors[$_FILES[$fieldname]['error'][$key]], $uploadForm);
        
            
    // check that the file we are working on really was an HTTP upload
            
    @is_uploaded_file($_FILES[$fieldname]['tmp_name'][$key])
            or 
    error($_FILES[$fieldname]['tmp_name'][$key].' not an HTTP upload'$uploadForm);
        
            
    // validation... since this is an image upload script we 
            // should run a check to make sure the upload is an image
            
    @getimagesize($_FILES[$fieldname]['tmp_name'][$key])
            or 
    error($_FILES[$fieldname]['tmp_name'][$key].' not an image'$uploadForm);
        
            
    // make a unique filename for the uploaded file and check it is 
            // not taken... if it is keep trying until we find a vacant one    
            
    $now time();
            while(
    file_exists($uploadFilename[$key] = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name'][$key]))
            {
                
    $now++;
            }
            
        } 

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles