Jump to content

SQL_QUERY for loop


waverider303

Recommended Posts

Is this possible to do?

for($s=0; $s==$file_len; $s++) {
	// SQL Statements
		$sql = "INSERT INTO `upload_images` (`id`, `image_name`, `img_size`, `img_medium`, `img_title`, `page_name`, `bio_link`, `img_url`, ) VALUES ('', '$image_name[$s]', '$sizes[$s]', '$mediums[$s]', '$titles[$s]', '$page_name', '$bio_link', '$img_url')";						
		if(mysql_query($sql)){
			echo "hello!";
		}
	}

Link to comment
https://forums.phpfreaks.com/topic/185263-sql_query-for-loop/
Share on other sites

Yes that is possible. However do note that you can perform more than one insert within a single query. This will be much more efficient:

 

if($file_len > 0)
{
    // start query
    $sql = 'INSERT INTO `upload_images` (`image_name`, `img_size`, `img_medium`, `img_title`, `page_name`, `bio_link`, `img_url`, ) VALUES ';

    // generate the rest of the query
    for($s=0; $s < $file_len; $s++)
    {
        $sql .= " ('$image_name[$s]', '$sizes[$s]', '$mediums[$s]', '$titles[$s]', '$page_name', '$bio_link', '$img_url'),";
    }

    // remove ending comma
    $sql = substr($sql, 0, -1);

    if(mysql_query($sql))
    {
        echo "Inserted " . count($file_len) . " files successfully";
    }
    else
    {
        die( "ERROR! Unable insert files<br />" . mysql_error() );
    }
}

 

You should also be sanitizing your variables that you use within your queries too.

 

 

Link to comment
https://forums.phpfreaks.com/topic/185263-sql_query-for-loop/#findComment-977974
Share on other sites

I am receiving an error. I believe it is due to the version of php/mysql that I am running. Here is the error:

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 ') VALUES ('', '', '', '', 'home', '', '../images') ('', '', '', '', 'home', '',' at line 1

Link to comment
https://forums.phpfreaks.com/topic/185263-sql_query-for-loop/#findComment-977997
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.