Jump to content
Larry Ullman's Book Forums
Sign in to follow this  
Deaddog

Use Of Implode To Insert Multiple Rows Into Mysql

Recommended Posts

Hello,

I've googled this thing to death, but still having problems.

 

I'm trying to insert multiple rows into Mysql with one INSERT INTO query (line 39) using an array and the implode().

 

The user can select multiple qualifications for one employee.  I have the multiple select listing all the qualifications from the quals table on the db. 

Another select table is listing all the employee names from the employee table.

 

Each employee can have multiple qualifications. 

I would like the qual_id, employee_id, issue_date, and expiration_date inserted into emp-quals table.

 

The following error keeps appearing:

Array ( [qual_id] => 3 [employee_id] => 13 [issue_date] => [expiration_date] => [Submit] => Submit [/] => ) An error occurred in script 'C:\wamp\www\****\set_qual.php' on line 36: Uninitialized string offset: 0

And

Column count doesn't match value count at row 1

Query: INSERT INTO emp_quals(qual_id, employee_id, issue_date, expiration_date) VALUES ('("3", 3, 3, 3")', '("1", 1, 1, 1")', '("", , , ")', '("", , , ")', '("S", S, S, S")', '("", , , ")')
 

 

 

It seems to be close to working, but I'm not sure how to tweak it.

 

Here is the entire code:

<?php #Ny Kvalifikasjon for Ansatte.
require('includes/config.inc.php');
$page_title = 'Ny Kvalifikasjon for ansatte!';
include ('includes/header.html');

// Create the submission conditional and initialize the $errors array.
if ($_SERVER['REQUEST_METHOD'] == 'POST'){

	// Add the MySQL connection
	include(MYSQL);
		
	$errors = array();
		$qual_id = mysqli_real_escape_string($dbc, trim($_POST['qual_id']));
		$employee_id = mysqli_real_escape_string($dbc, trim($_POST['employee_id']));
		$issue_date = mysqli_real_escape_string($dbc, trim($_POST['issue_date']));
		$expiration_date = mysqli_real_escape_string($dbc, trim($_POST['expiration_date']));
		
		if (empty($_POST['qual_id'])) {
			$errors[] = 'Kvalifikasjonen mangler!';
			}															
				else {
			$qual_id = mysqli_real_escape_string($dbc, trim($_POST['qual_id']));
		}
		if (empty($_POST['employee_id'])) {
			$errors[] = 'Ansatte mangler!';
			}															
				else {
			$employee_id = mysqli_real_escape_string($dbc, trim($_POST['employee_id']));
		}
				
	if (empty($errors)) {
	
		print_r($_POST);  //Added print_r tip from margaux at L.U.forum post: http://www.larryullman.com/forums/index.php?/topic/2131-103-edit-user-script-modification/
		$values = array(); 
		foreach($_POST as $row ) {
		$values[] = '("'.mysql_real_escape_string($row['qual_id']).'", '.$row['employee_id'].', '.$row['issue_date'].', '.$row['expiration_date'].'")';
		}
		
		$q  = "INSERT INTO emp_quals(qual_id, employee_id, issue_date, expiration_date)";
		$q .= " VALUES ('".implode("', '", $values)."')";
		
		$r = @mysqli_query ($dbc, $q);
				
			if ($r) { //See pg 276
				echo '<h1>Success!</h1>
				<p>En ny kvalifikasjon er lagret.</p>
				<p><a href="qualification.php">Gå til kvalifikasjons oversikt.</a><br /></p>';
				}
					else {
					echo '<h1>System Error</h1>
					<p class="error">You could not be registered due to a system error.  We apologize for any inconvenience.</p>';
					echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $q . '</p>';
					} // End of if ($r) IF.
			
		mysqli_close($dbc);
		include ('includes/footer.html');
		exit ();
	 }else {    // Report the errors
		echo '<h1>Error!</h1>
		<p class="error">The following error(s) occurred:<br />';
		foreach ($errors as $msg) {
		// Print each error messages
		echo " - $msg<br />\n";
		}
		echo '</p><p>Please try again.</p><p><br /></p>';
		  }  // End of if (empty($errors)) IF.
		
	 }// End of main submit conditional.
	
	//DISPLAY THE FORM
	?>
<h1>Ny Kvalifikasjon for Ansatte</h1>
<form action="set_qual.php" method="post">
<fieldset>
<legend>Ny Kvalifikasjon for Ansatte</legend>
<label>Qualification:</label><select multiple name="qual_id">';
<?php 
include(MYSQL);
$q = "SELECT qual_id, qual_name FROM quals ORDER BY qual_id ASC";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) > 0) {
	while ($menu_row = mysqli_fetch_array($r, MYSQLI_NUM)) {
		echo '<option value="'.$menu_row[0].'">'.$menu_row[0].' - ' . $menu_row[1] . '</option>\n';
		}
	}
mysqli_free_result($r);
echo '</select><br /><small>Bruk Ctrl knappen for å velge flere.</small><br />'; ?>
<label>Employee Name:</label><select name="employee_id">';
<?php 
$q = "SELECT employee_id, ansattnumber, last_name, first_name FROM employee ORDER BY ansattnumber ASC";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) > 0) {
	while ($menu_row = mysqli_fetch_array($r, MYSQLI_NUM)) {
		echo '<option value="'.$menu_row[0].'">' . $menu_row[1] . ' - ' .$menu_row[2] .', '. $menu_row[3]. '</option>\n';
		}
	}
mysqli_free_result($r);
echo '</select><br />'; ?>
<br />
<label>Start dato yyyy-mm-dd:</label><input type="text" name="issue_date" size="15" maxlength="15" value="<?php if(isset($_POST['issue_date'])) echo $_POST['issue_date']; ?>" /><br /><br />
<label>Utløpsdato yyyy-mm-dd:</label><input type="text" name="expiration_date" size="15" maxlength="15" value="<?php if(isset($_POST['expiration_date'])) echo $_POST['expiration_date']; ?>" /><br /><br />
<p><input type="submit" name="Submit" value="Submit" class="button" /></p>
<input type="hidden" name= />
</fieldset>
</form>		
			
<?php include ('includes/footer.html'); ?>

Any assistance would be appreciated.

Share this post


Link to post
Share on other sites

Your 4th value in each tuple is missing a double quote, or perhaps has an unnecessary double quote.

Is that the issue?

 

Edit: It also seems like you're adding unnecessary single quotes and have an extra set of parentheses around the whole set of values.

You might want to reference this:

http://stackoverflow.com/questions/452859/inserting-multiple-rows-in-a-single-sql-query

Share this post


Link to post
Share on other sites

I've changed the code from line 31 and now get no values returned when using implode.  Also, I'm getting the following error:

#0  my_error_handler(2, implode() [function.implode]: Invalid arguments passed, C:\wamp\www\****\set_qual.php, 46, Array ([GLOBALS] => Array ( *RECURSION*,[_POST] => Array ([qual_id] => 11,[employee_id] => 13,[issue_date] => ,[expiration_date] => ,[Submit] => Submit),[_GET] => Array (),[_COOKIE] => Array ([__utma] => 111872281.652457305.1361574854.1362520724.1362599419.29,[__utmz] => 111872281.1361574854.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none),[PHPSESSID] => qi20vv92fs1s1v75d4a12tguf0),[_FILES] => Array (),[_ENV] => Array (),[_REQUEST] => Array ([qual_id] => 11,[employee_id] => 13,[issue_date] => ,[expiration_date] => ,[Submit] => Submit),[_SERVER] => Array ([HTTP_HOST] => localhost,[HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0,[HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,[HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.5,[HTTP_ACCEPT_ENCODING] => gzip, deflate,[HTTP_REFERER] => http://localhost/storesund/set_qual.php,[HTTP_COOKIE] => __utma=111872281.652457305.1361574854.1362520724.1362599419.29; __utmz=111872281.1361574854.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); PHPSESSID=qi20vv92fs1s1v75d4a12tguf0,[HTTP_CONNECTION] => keep-alive,[CONTENT_TYPE] => application/x-www-form-urlencoded,[CONTENT_LENGTH] => 68,[PATH] => C:\oracle\ora8\jdk\bin\;C:\oracle\ora8\BIN\;C:\Program Files\Oracle\jre\1.1.8\bin\;C:\Program Files\Oracle\jre\1.3.1\bin\;C:\oracle\ora92\bin\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\SAS Institute\Shared Files\Formats\;C:\Program Files\IBM\Personal Communications\;C:\Program Files\IBM\Trace Facility\;C:\Program Files\SASALFA,[SystemRoot] => C:\WINDOWS,[COMSPEC] => C:\WINDOWS\system32\cmd.exe,[PATHEXT] => .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH,[WINDIR] => C:\WINDOWS,[SERVER_SIGNATURE] => ,[SERVER_SOFTWARE] => Apache/2.2.21 (Win32) mod_ssl/2.2.21 OpenSSL/0.9.8r PHP/5.3.8,[SERVER_NAME] => localhost,[SERVER_ADDR] => 127.0.0.1,[SERVER_PORT] => 80,[REMOTE_ADDR] => 127.0.0.1,[DOCUMENT_ROOT] => C:/wamp/www/,[SERVER_ADMIN] => admin@localhost,[SCRIPT_FILENAME] => C:/wamp/www/storesund/set_qual.php,[REMOTE_PORT] => 2160,[GATEWAY_INTERFACE] => CGI/1.1,[SERVER_PROTOCOL] => HTTP/1.1,[REQUEST_METHOD] => POST,[QUERY_STRING] => ,[REQUEST_URI] => /storesund/set_qual.php,[SCRIPT_NAME] => /storesund/set_qual.php,[PHP_SELF] => /storesund/set_qual.php,[REQUEST_TIME] => 1363990601),[page_title] => Ny Kvalifikasjon for ansatte!,[thismonth] => March,[_SESSION] => Array ([user_id] => 1,[first_name] => Jason,[user_level] => 0),[dbc] => mysqli Object ([affected_rows] => ,[client_info] => ,[client_version] => ,[connect_errno] => ,[connect_error] => ,[errno] => ,[error] => ,[field_count] => ,[host_info] => ,[info] => ,[insert_id] => ,[server_info] => ,[server_version] => ,[sqlstate] => ,[protocol_version] => ,[thread_id] => ,[warning_count] => ),[errors] => Array (),[qual_id] => 11,[employee_id] => 13,[issue_date] => ,[expiration_date] => ))#1  implode(,, ) called at [C:\wamp\www\****\set_qual.php:42]

 

 

if (empty($errors)) {
		print_r($_POST);
		foreach($_POST['qual_id'] as $row=>$qual_id)
		{
		$qual_id=mysqli_real_escape_string($dbc, trim($qual_id));
		$employee_id=mysqli_real_escape_string($dbc, trim($_POST['employee_id'][$row]));
		$issue_date=mysqli_real_escape_string($dbc, trim($_POST['issue_date'][$row]));
		$expiration_date=mysqli_real_escape_string($dbc, trim($_POST['expiration_date'][$row]));
		
		$query_row[] = "('$qual_id','$employee_id','$issue_date', '$expiration_date')";
		}
		$q= "INSERT INTO emp_quals(qual_id, employee_id, issue_date, expiration_date) VALUES " . implode(',',$query_row); 
		$r = @mysqli_query ($dbc, $q);

 

Share this post


Link to post
Share on other sites

First, the debugging information you've posted is not useful in the format you've presented it. If you want help, please provide useful debugging information. Second, from what I can tell, the error is that implode() is not being provided with the proper argument types. If so, then your debugging step would be to confirm the values (and types) you're providing to implode().

Share this post


Link to post
Share on other sites

If there's one thing I have plenty of, it's debugging information :).  The problem is I don't understand it all. 

I have Scipt 18.3 debugging for !LIVE site.

 

if (!LIVE) { //Development (print the error). //snippet from script 18.3.
		//Show the error message:
		echo '<div class"error">' . nl2br($message);
		// Add the variables and a backtrace:
		echo '<pre>' . print_r($e_vars, 1). "\n";
		debug_print_backtrace();
		echo '</pre></div>';

Below is the debugging info that was generated by script 18.3 - config.inc.php.

 

<?php
Array ( [qual_id] => 4 [employee_id] => 6 [issue_date] => [expiration_date] => [Submit] => Submit )
An error occurred in script 'C:\wamp\www\******\set_qual.php' on line 37: Invalid argument supplied for foreach()
Date/Time: 3-23-2013 23:07:09

Array
(
    [GLOBALS] => Array
 *RECURSION*
    [_POST] => Array
        (
            [qual_id] => 4
            [employee_id] => 6
            [issue_date] =>
            [expiration_date] =>
            [Submit] => Submit
        )

    [_GET] => Array
        (
        )

    [_COOKIE] => Array
        (
            [__utma] => 111872281.652457305.1361574854.1362520724.1362599419.29
            [__utmz] => 111872281.1361574854.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)
            [PHPSESSID] => ******
        )

    [_FILES] => Array
        (
        )

    [_ENV] => Array
        (
        )

    [_REQUEST] => Array
        (
            [qual_id] => 4
            [employee_id] => 6
            [issue_date] =>
            [expiration_date] =>
            [Submit] => Submit
        )

    [_SERVER] => Array
        (
            [HTTP_HOST] => localhost
            [HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0
            [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
            [HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.5
            [HTTP_ACCEPT_ENCODING] => gzip, deflate
            [HTTP_REFERER] => http://localhost/******/set_qual.php
            [HTTP_COOKIE] => __utma=111872281.652457305.1361574854.1362520724.1362599419.29; __utmz=111872281.1361574854.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); PHPSESSID=******
            [HTTP_CONNECTION] => keep-alive
            [CONTENT_TYPE] => application/x-www-form-urlencoded
            [CONTENT_LENGTH] => 86
            [PATH] => C:\****
            [SystemRoot] => C:\WINDOWS
            [COMSPEC] => C:\WINDOWS\system32\cmd.exe
            [PATHEXT] => .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
            [WINDIR] => C:\WINDOWS
            [SERVER_SIGNATURE] =>
            [SERVER_SOFTWARE] => Apache/2.2.21 (Win32) mod_ssl/2.2.21 OpenSSL/0.9.8r PHP/5.3.8
            [SERVER_NAME] => localhost
            [SERVER_ADDR] => 127.0.0.1
            [SERVER_PORT] => 80
            [REMOTE_ADDR] => 127.0.0.1
            [DOCUMENT_ROOT] => C:/wamp/www/
            [SERVER_ADMIN] => admin@localhost
            [SCRIPT_FILENAME] => C:/wamp/www/******/set_qual.php
            [REMOTE_PORT] => 1202
            [GATEWAY_INTERFACE] => CGI/1.1
            [SERVER_PROTOCOL] => HTTP/1.1
            [REQUEST_METHOD] => POST
            [QUERY_STRING] =>
            [REQUEST_URI] => /******/set_qual.php
            [SCRIPT_NAME] => /******/set_qual.php
            [PHP_SELF] => /******/set_qual.php
            [REQUEST_TIME] => 1364076429
        )

    [page_title] => Ny Kvalifikasjon for ansatte!
    [thismonth] => March
    [_SESSION] => Array
        (
            [user_id] => 1
            [first_name] => Jason
            [user_level] => 0
        )

    [dbc] => mysqli Object
        (
            [affected_rows] => 0
            [client_info] => mysqlnd 5.0.8-dev - 20102224 - $Revision: 310735 $
            [client_version] => 50008
            [connect_errno] => 0
            [connect_error] =>
            [errno] => 0
            [error] =>
            [field_count] => 0
            [host_info] => localhost via TCP/IP
            [info] =>
            [insert_id] => 0
            [server_info] => 5.5.16-log
            [server_version] => 50516
            [sqlstate] => 00000
            [protocol_version] => 10
            [thread_id] => 5
            [warning_count] => 0
        )

    [errors] => Array
        (
        )

    [qual_id] => 4
    [employee_id] => 6
    [issue_date] =>
    [expiration_date] =>
)

#0  my_error_handler(2, Invalid argument supplied for foreach(), C:\wamp\www\******\set_qual.php, 37, Array ([GLOBALS] => Array ( *RECURSION*,[_POST] => Array ([qual_id] => 4,[employee_id] => 6,[issue_date] => ,[expiration_date] => ,[Submit] => Submit),[_GET] => Array (),[_COOKIE] => Array ([__utma] => 111872281.652457305.1361574854.1362520724.1362599419.29,[__utmz] => 111872281.1361574854.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none),[PHPSESSID] => ******),[_FILES] => Array (),[_ENV] => Array (),[_REQUEST] => Array ([qual_id] => 4,[employee_id] => 6,[issue_date] => ,[expiration_date] => ,[Submit] => Submit),[_SERVER] => Array ([HTTP_HOST] => localhost,[HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0,[HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,[HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.5,[HTTP_ACCEPT_ENCODING] => gzip, deflate,[HTTP_REFERER] => http://localhost/******/set_qual.php,[HTTP_COOKIE] => __utma=111872281.652457305.1361574854.1362520724.1362599419.29; __utmz=111872281.1361574854.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); PHPSESSID=******,[HTTP_CONNECTION] => keep-alive,[CONTENT_TYPE] => application/x-www-form-urlencoded,[CONTENT_LENGTH] => 86,[PATH] => C:\*****

[SystemRoot] => C:\WINDOWS,[COMSPEC] => C:\WINDOWS\system32\cmd.exe,[PATHEXT] => .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH,[WINDIR] => C:\WINDOWS,[SERVER_SIGNATURE] => ,[SERVER_SOFTWARE] => Apache/2.2.21 (Win32) mod_ssl/2.2.21 OpenSSL/0.9.8r PHP/5.3.8,[SERVER_NAME] => localhost,[SERVER_ADDR] => 127.0.0.1,[SERVER_PORT] => 80,[REMOTE_ADDR] => 127.0.0.1,[DOCUMENT_ROOT] => C:/wamp/www/,[SERVER_ADMIN] => admin@localhost,[SCRIPT_FILENAME] => C:/wamp/www/******/set_qual.php,[REMOTE_PORT] => 1202,[GATEWAY_INTERFACE] => CGI/1.1,[SERVER_PROTOCOL] => HTTP/1.1,[REQUEST_METHOD] => POST,[QUERY_STRING] => ,[REQUEST_URI] => /******/set_qual.php,[SCRIPT_NAME] => /******/set_qual.php,[PHP_SELF] => /******/set_qual.php,[REQUEST_TIME] => 1364076429),[page_title] => Ny Kvalifikasjon for ansatte!,[thismonth] => March,[_SESSION] => Array ([user_id] => 1,[first_name] => Jason,[user_level] => 0),[dbc] => mysqli Object ([affected_rows] => ,[client_info] => ,[client_version] => ,[connect_errno] => ,[connect_error] => ,[errno] => ,[error] => ,[field_count] => ,[host_info] => ,[info] => ,[insert_id] => ,[server_info] => ,[server_version] => ,[sqlstate] => ,[protocol_version] => ,[thread_id] => ,[warning_count] => ),[errors] => Array (),[qual_id] => 4,[employee_id] => 6,[issue_date] => ,[expiration_date] => )) called at [C:\wamp\www\******\set_qual.php:37]

An error occurred in script 'C:\wamp\www\******\set_qual.php' on line 46: Undefined variable: query_row
Date/Time: 3-23-2013 23:07:09

Array
(
    [GLOBALS] => Array
 *RECURSION*
    [_POST] => Array
        (
            [qual_id] => 4
            [employee_id] => 6
            [issue_date] =>
            [expiration_date] =>
            [Submit] => Submit
        )

    [_GET] => Array
        (
        )

    [_COOKIE] => Array
        (
            [__utma] => 111872281.652457305.1361574854.1362520724.1362599419.29
            [__utmz] => 111872281.1361574854.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)
            [PHPSESSID] => ******
        )

    [_FILES] => Array
        (
        )

    [_ENV] => Array
        (
        )

    [_REQUEST] => Array
        (
            [qual_id] => 4
            [employee_id] => 6
            [issue_date] =>
            [expiration_date] =>
            [Submit] => Submit
        )

    [_SERVER] => Array
        (
            [HTTP_HOST] => localhost
            [HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0
            [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
            [HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.5
            [HTTP_ACCEPT_ENCODING] => gzip, deflate
            [HTTP_REFERER] => http://localhost/******/set_qual.php
            [HTTP_COOKIE] => __utma=111872281.652457305.1361574854.1362520724.1362599419.29; __utmz=111872281.1361574854.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); PHPSESSID=*****
            [HTTP_CONNECTION] => keep-alive
            [CONTENT_TYPE] => application/x-www-form-urlencoded
            [CONTENT_LENGTH] => 86
            [PATH] => C:\****
            [SystemRoot] => C:\WINDOWS
            [COMSPEC] => C:\WINDOWS\system32\cmd.exe
            [PATHEXT] => .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
            [WINDIR] => C:\WINDOWS
            [SERVER_SIGNATURE] =>
            [SERVER_SOFTWARE] => Apache/2.2.21 (Win32) mod_ssl/2.2.21 OpenSSL/0.9.8r PHP/5.3.8
            [SERVER_NAME] => localhost
            [SERVER_ADDR] => 127.0.0.1
            [SERVER_PORT] => 80
            [REMOTE_ADDR] => 127.0.0.1
            [DOCUMENT_ROOT] => C:/wamp/www/
            [SERVER_ADMIN] => admin@localhost
            [SCRIPT_FILENAME] => C:/wamp/www/******/set_qual.php
            [REMOTE_PORT] => 1202
            [GATEWAY_INTERFACE] => CGI/1.1
            [SERVER_PROTOCOL] => HTTP/1.1
            [REQUEST_METHOD] => POST
            [QUERY_STRING] =>
            [REQUEST_URI] => /******/set_qual.php
            [SCRIPT_NAME] => /******/set_qual.php
            [PHP_SELF] => /******/set_qual.php
            [REQUEST_TIME] => 1364076429
        )

    [page_title] => Ny Kvalifikasjon for ansatte!
    [thismonth] => March
    [_SESSION] => Array
        (
            [user_id] => 1
            [first_name] => Jason
            [user_level] => 0
        )

    [dbc] => mysqli Object
        (
            [affected_rows] => 0
            [client_info] => mysqlnd 5.0.8-dev - 20102224 - $Revision: 310735 $
            [client_version] => 50008
            [connect_errno] => 0
            [connect_error] =>
            [errno] => 0
            [error] =>
            [field_count] => 0
            [host_info] => localhost via TCP/IP
            [info] =>
            [insert_id] => 0
            [server_info] => 5.5.16-log
            [server_version] => 50516
            [sqlstate] => 00000
            [protocol_version] => 10
            [thread_id] => 5
            [warning_count] => 0
        )

    [errors] => Array
        (
        )

    [qual_id] => 4
    [employee_id] => 6
    [issue_date] =>
    [expiration_date] =>
)

#0  my_error_handler(8, Undefined variable: query_row, C:\wamp\www\******\set_qual.php, 46, Array ([GLOBALS] => Array ( *RECURSION*,[_POST] => Array ([qual_id] => 4,[employee_id] => 6,[issue_date] => ,[expiration_date] => ,[Submit] => Submit),[_GET] => Array (),[_COOKIE] => Array ([__utma] => 111872281.652457305.1361574854.1362520724.1362599419.29,[__utmz] => 111872281.1361574854.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none),[PHPSESSID] => ******),[_FILES] => Array (),[_ENV] => Array (),[_REQUEST] => Array ([qual_id] => 4,[employee_id] => 6,[issue_date] => ,[expiration_date] => ,[Submit] => Submit),[_SERVER] => Array ([HTTP_HOST] => localhost,[HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0,[HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,[HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.5,[HTTP_ACCEPT_ENCODING] => gzip, deflate,[HTTP_REFERER] => http://localhost/******/set_qual.php,[HTTP_COOKIE] => __utma=111872281.652457305.1361574854.1362520724.1362599419.29; __utmz=111872281.1361574854.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); PHPSESSID=******,[HTTP_CONNECTION] => keep-alive,[CONTENT_TYPE] => application/x-www-form-urlencoded,[CONTENT_LENGTH] => 86,[PATH] => C:\***** C:\WINDOWS\system32\cmd.exe,[PATHEXT] => .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH,[WINDIR] => C:\WINDOWS,[SERVER_SIGNATURE] => ,[SERVER_SOFTWARE] => Apache/2.2.21 (Win32) mod_ssl/2.2.21 OpenSSL/0.9.8r PHP/5.3.8,[SERVER_NAME] => localhost,[SERVER_ADDR] => 127.0.0.1,[SERVER_PORT] => 80,[REMOTE_ADDR] => 127.0.0.1,[DOCUMENT_ROOT] => C:/wamp/www/,[SERVER_ADMIN] => admin@localhost,[SCRIPT_FILENAME] => C:/wamp/www/******/set_qual.php,[REMOTE_PORT] => 1202,[GATEWAY_INTERFACE] => CGI/1.1,[SERVER_PROTOCOL] => HTTP/1.1,[REQUEST_METHOD] => POST,[QUERY_STRING] => ,[REQUEST_URI] => /******/set_qual.php,[SCRIPT_NAME] => /******/set_qual.php,[PHP_SELF] => /******/set_qual.php,[REQUEST_TIME] => 1364076429),[page_title] => Ny Kvalifikasjon for ansatte!,[thismonth] => March,[_SESSION] => Array ([user_id] => 1,[first_name] => Jason,[user_level] => 0),[dbc] => mysqli Object ([affected_rows] => ,[client_info] => ,[client_version] => ,[connect_errno] => ,[connect_error] => ,[errno] => ,[error] => ,[field_count] => ,[host_info] => ,[info] => ,[insert_id] => ,[server_info] => ,[server_version] => ,[sqlstate] => ,[protocol_version] => ,[thread_id] => ,[warning_count] => ),[errors] => Array (),[qual_id] => 4,[employee_id] => 6,[issue_date] => ,[expiration_date] => )) called at [C:\wamp\www\******\set_qual.php:46]

An error occurred in script 'C:\wamp\www\******\set_qual.php' on line 46: implode() [function.implode]: Invalid arguments passed
Date/Time: 3-23-2013 23:07:09

Array
(
    [GLOBALS] => Array
 *RECURSION*
    [_POST] => Array
        (
            [qual_id] => 4
            [employee_id] => 6
            [issue_date] =>
            [expiration_date] =>
            [Submit] => Submit
        )

    [_GET] => Array
        (
        )

    [_COOKIE] => Array
        (
            [__utma] => 111872281.652457305.1361574854.1362520724.1362599419.29
            [__utmz] => 111872281.1361574854.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)
            [PHPSESSID] => *******
        )

    [_FILES] => Array
        (
        )

    [_ENV] => Array
        (
        )

    [_REQUEST] => Array
        (
            [qual_id] => 4
            [employee_id] => 6
            [issue_date] =>
            [expiration_date] =>
            [Submit] => Submit
        )

    [_SERVER] => Array
        (
            [HTTP_HOST] => localhost
            [HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0
            [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
            [HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.5
            [HTTP_ACCEPT_ENCODING] => gzip, deflate
            [HTTP_REFERER] => http://localhost/******/set_qual.php
            [HTTP_COOKIE] => __utma=111872281.652457305.1361574854.1362520724.1362599419.29; __utmz=111872281.1361574854.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); PHPSESSID=******
            [HTTP_CONNECTION] => keep-alive
            [CONTENT_TYPE] => application/x-www-form-urlencoded
            [CONTENT_LENGTH] => 86
            [PATH] => C:\****
            [SystemRoot] => C:\WINDOWS
            [COMSPEC] => C:\WINDOWS\system32\cmd.exe
            [PATHEXT] => .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
            [WINDIR] => C:\WINDOWS
            [SERVER_SIGNATURE] =>
            [SERVER_SOFTWARE] => Apache/2.2.21 (Win32) mod_ssl/2.2.21 OpenSSL/0.9.8r PHP/5.3.8
            [SERVER_NAME] => localhost
            [SERVER_ADDR] => 127.0.0.1
            [SERVER_PORT] => 80
            [REMOTE_ADDR] => 127.0.0.1
            [DOCUMENT_ROOT] => C:/wamp/www/
            [SERVER_ADMIN] => admin@localhost
            [SCRIPT_FILENAME] => C:/wamp/www/******/set_qual.php
            [REMOTE_PORT] => 1202
            [GATEWAY_INTERFACE] => CGI/1.1
            [SERVER_PROTOCOL] => HTTP/1.1
            [REQUEST_METHOD] => POST
            [QUERY_STRING] =>
            [REQUEST_URI] => /******/set_qual.php
            [SCRIPT_NAME] => /******/set_qual.php
            [PHP_SELF] => /******/set_qual.php
            [REQUEST_TIME] => 1364076429
        )

    [page_title] => Ny Kvalifikasjon for ansatte!
    [thismonth] => March
    [_SESSION] => Array
        (
            [user_id] => 1
            [first_name] => Jason
            [user_level] => 0
        )

    [dbc] => mysqli Object
        (
            [affected_rows] => 0
            [client_info] => mysqlnd 5.0.8-dev - 20102224 - $Revision: 310735 $
            [client_version] => 50008
            [connect_errno] => 0
            [connect_error] =>
            [errno] => 0
            [error] =>
            [field_count] => 0
            [host_info] => localhost via TCP/IP
            [info] =>
            [insert_id] => 0
            [server_info] => 5.5.16-log
            [server_version] => 50516
            [sqlstate] => 00000
            [protocol_version] => 10
            [thread_id] => 5
            [warning_count] => 0
        )

    [errors] => Array
        (
        )

    [qual_id] => 4
    [employee_id] => 6
    [issue_date] =>
    [expiration_date] =>
)

#0  my_error_handler(2, implode() [function.implode]: Invalid arguments passed, C:\wamp\www\******\set_qual.php, 46, Array ([GLOBALS] => Array ( *RECURSION*,[_POST] => Array ([qual_id] => 4,[employee_id] => 6,[issue_date] => ,[expiration_date] => ,[Submit] => Submit),[_GET] => Array (),[_COOKIE] => Array ([__utma] => 111872281.652457305.1361574854.1362520724.1362599419.29,[__utmz] => 111872281.1361574854.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none),[PHPSESSID] => ******),[_FILES] => Array (),[_ENV] => Array (),[_REQUEST] => Array ([qual_id] => 4,[employee_id] => 6,[issue_date] => ,[expiration_date] => ,[Submit] => Submit),[_SERVER] => Array ([HTTP_HOST] => localhost,[HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0,[HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,[HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.5,[HTTP_ACCEPT_ENCODING] => gzip, deflate,[HTTP_REFERER] => http://localhost/******/set_qual.php,[HTTP_COOKIE] => __utma=111872281.652457305.1361574854.1362520724.1362599419.29; __utmz=111872281.1361574854.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); PHPSESSID=*****,[HTTP_CONNECTION] => keep-alive,[CONTENT_TYPE] => application/x-www-form-urlencoded,[CONTENT_LENGTH] => 86,[PATH] => C:********

 CGI/1.1,[SERVER_PROTOCOL] => HTTP/1.1,[REQUEST_METHOD] => POST,[QUERY_STRING] => ,[REQUEST_URI] => /******/set_qual.php,[SCRIPT_NAME] => /******/set_qual.php,[PHP_SELF] => /******/set_qual.php,[REQUEST_TIME] => 1364076429),[page_title] => Ny Kvalifikasjon for ansatte!,[thismonth] => March,[_SESSION] => Array ([user_id] => 1,[first_name] => Jason,[user_level] => 0),[dbc] => mysqli Object ([affected_rows] => ,[client_info] => ,[client_version] => ,[connect_errno] => ,[connect_error] => ,[errno] => ,[error] => ,[field_count] => ,[host_info] => ,[info] => ,[insert_id] => ,[server_info] => ,[server_version] => ,[sqlstate] => ,[protocol_version] => ,[thread_id] => ,[warning_count] => ),[errors] => Array (),[qual_id] => 4,[employee_id] => 6,[issue_date] => ,[expiration_date] => ))
#1  implode(,, ) called at [C:\wamp\www\******\set_qual.php:46]



One thing that stands out is, my_error_handler(2, implode() [function.implode]: Invalid arguments passed on line 372.

 

It seems to be so close, but just not right.

 

Any suggestions?

 

-Jason

Share this post


Link to post
Share on other sites

Before going any further, please check out the PHP.net page for the implode function:

http://php.net/manual/en/function.implode.php

 

Please look at the syntax and the execution examples, and see if you can figure out the problem on your own.

If you're still having problems, please output the part of your code where you're calling the implode function.

Thanks.

Share this post


Link to post
Share on other sites

Thanks HartleySan,

I've been to the PHP manual, in fact it is the first place I checked for advice.  The specific part of the code that is giving problems is below.  If it wasn't for the foreach statement maybe I could have figured it out by now.  Since each qual_id must be a new row on the emp_quals table, it's tricky.

 

if (empty($errors)) {
		print_r($_POST);
		foreach($_POST['qual_id'] as $row=>$qual_id)
		{
		$qual_id=mysqli_real_escape_string($dbc, trim($qual_id));
		$employee_id=mysqli_real_escape_string($dbc, trim($_POST['employee_id'][$row]));
		$issue_date=mysqli_real_escape_string($dbc, trim($_POST['issue_date'][$row]));
		$expiration_date=mysqli_real_escape_string($dbc, trim($_POST['expiration_date'][$row]));
		
		$query_row[] = "('$qual_id','$employee_id','$issue_date', '$expiration_date')";
		}
		$q= "INSERT INTO emp_quals(qual_id, employee_id, issue_date, expiration_date) VALUES " . implode(',',$query_row);

 

Share this post


Link to post
Share on other sites

No, I did not have it.  I have tried it now though, both above and below the foreach statement.  Still getting invalid argument supplied for foreach().

Share this post


Link to post
Share on other sites

Please run the following code, and paste the results into a post here so that we can see. Thanks.

echo '<pre>';
 
print_r($_POST['qual_id']);
 
echo '</pre>';

Share this post


Link to post
Share on other sites

Ok.  I've done it.  This is the result: 4.  It echos the qual_id.

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 '' at line 1

Query: INSERT INTO emp_quals(qual_id, employee_id, issue_date, expiration_date) VALUES

4

The input form (multiple select) for qual_id looks like this:

 

<label>Kvalifikasjon:</label><select multiple name="qual_id">';
<?php 
include(MYSQL);
$q = "SELECT qual_id, qual_name FROM quals ORDER BY qual_id ASC";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) > 0) {
	while ($menu_row = mysqli_fetch_array($r, MYSQLI_NUM)) {
		echo '<option value="'.$menu_row[0].'">'.$menu_row[0].' - ' . $menu_row[1] . '</option>\n';
		}
	}
mysqli_free_result($r);
echo '</select><br /><small>Bruk Ctrl knappen for å velge flere.</small><br />'; ?>

 

Share this post


Link to post
Share on other sites

Right, so qual_id is not an array. The reason is because of how you've named the form element:

 

 

<label>Qualification:</label><select multiple name="qual_id">'; 
 
That only allows for a single value to be assigned to $_POST['qual_id'], even though multiple selections are possible. The last selected value will be the lone value of $_POST['qual_id']. Change that line in your form to:
 
<label>Qualification:</label><select multiple name="qual_id[]">'; 

 

to allow it to be an array.

Share this post


Link to post
Share on other sites

It's a happy day.  That did it.  I'm sure the code is probably rough around the edges to all you experienced folks, but it works.  Here's a snippet.  I'm sure there is a cleaner way to make the foreach() statements, but for now, it's fantastic.  As Larry wrote in the last post, qual_id should have been qual_id[].  I used this same approach on the other values, i.e.  employee_id[], etc... 

 

I know it takes a lot of effort to answer these forums posts, so thanks again for the help to Larry and HartleySan for this one.

 

 

// Create the submission conditional and initialize the $errors array.
if ($_SERVER['REQUEST_METHOD'] == 'POST'){

    // Add the MySQL connection
    include(MYSQL);
        
    $errors = array();
        foreach($_POST['qual_id'] as $row=>$qual_id)
        foreach($_POST['employee_id'] as $row=>$employee_id)
        foreach($_POST['issue_date'] as $row=>$issue_date)
        foreach($_POST['expiration_date'] as $row=>$expiration_date)
        {
        $qual_id=mysqli_real_escape_string($dbc, trim($qual_id));
        $employee_id=mysqli_real_escape_string($dbc, trim($employee_id));
        $issue_date=mysqli_real_escape_string($dbc, trim($issue_date));
        $expiration_date=mysqli_real_escape_string($dbc, trim($expiration_date));
        $query_row[] = "('$qual_id','$employee_id','$issue_date', '$expiration_date')";
        }        
                
    if (empty($errors)) {
        print_r($_POST['qual_id']);
        

        
        $q= "INSERT INTO emp_quals(qual_id, employee_id, issue_date, expiration_date) VALUES " . implode(", ", $query_row);

 

Share this post


Link to post
Share on other sites

I have a similar problem, but it is just different enough...

 

I have a tag input field that asks for comma separated input. I am able to explode this into an array. The trouble comes when I want to insert each tag into its own row. I tried to assign a value for each array item, but I can't figure that out.

 

Here is what I have so far: the var_dump for $tags gives the array, but $tag only gives me the last array item.

//check for tags
	if (!empty($_POST['tag'])) {
		$input = $_POST['tag'];
		$tags = explode(',', $input);
		}else { //if empty
		$tag = NULL;
		}
	if (isset ($tags)){
		foreach($tags as $tag) {
		$tag = trim($tag); 
		}
	}

Share this post


Link to post
Share on other sites

artsyL, what's your problem exactly? Assuming $input is a comma-separated list of data, $tags will be an array, and your foreach loop will properly loop through the array, assigning each element to the $tag variable.

Share this post


Link to post
Share on other sites

that is why I am confused. This seems like it should work

 

Here is the result for var_dump($input, $tags, $tag):

string(16) "tag1, tag2, tag3" array(3) { [0]=> string(4) "tag1" [1]=> string(5) " tag2" [2]=> string(5) " tag3" } string(4) "tag3"

 

$input and $tags are doing what is expected, but $tag does not; therefore it does not insert multiple rows later on.

Share this post


Link to post
Share on other sites

Can we see more of your code? If you are performing var_dump() outside the loop then it will only hold the value of the last loop through.

Share this post


Link to post
Share on other sites

Here is the form input

<p><b>(optional) Add tags (separate with commas):</b> <input class="box" type="text" name="tag" size="30" maxlength="255" 
		value="<?php if (isset($_POST['tag'])) echo htmlspecialchars($_POST['tag']); ?>"/></p>
	</div>

Here is the validation

//check for tags
	if (!empty($_POST['tag'])) {
		$input = $_POST['tag'];
		$tags = explode(',', $input);
		}else { //if empty
		$tag = NULL;
		}
	if (isset ($tags)){
		foreach($tags as $tag) {
		$tag = trim($tag); 
		var_dump($input, $tags, $tag);
		}
	}

Here is the insert statement

$q = 'INSERT INTO tag (tag_display, tag, coll_id) VALUES
			(?, ?, ?)';
			$stmt = mysqli_prepare($dbc, $q);
			mysqli_stmt_bind_param($stmt, 'ssi', $input, $tag, $c);
			mysqli_stmt_execute($stmt);

Share this post


Link to post
Share on other sites

If you want to insert a row for each $tag value, you need to run the query within the foreach loop, which you do not seem to be doing. Something like the following should work:

 

if (!empty($_POST['tag'])) {
  
  $input = $_POST['tag'];
  
  $tags = explode(',', $input);
  
} else {
  
  $tag = NULL;
  
}


if (isset ($tags)) {
  
  foreach($tags as $tag) {
    
    $tag = trim($tag);
    
    var_dump($input, $tags, $tag);
    
    $q = 'INSERT INTO tag (tag_display, tag, coll_id) VALUES (?, ?, ?)';
    
    $stmt = mysqli_prepare($dbc, $q);
    
    mysqli_stmt_bind_param($stmt, 'ssi', $input, $tag, $c);
    
    mysqli_stmt_execute($stmt);
    
  }
  
}

As a side note, I would use isset instead of !empty to test for the existence of POST values. The following link explains why:

http://techtalk.virendrachandak.com/php-isset-vs-empty-vs-is_null/

Share this post


Link to post
Share on other sites

Now it is not posting at all to the database. Do I need to create a separate variable for each loop?

 

Here is the updated code (switched to isset - thanks for the tip!). Here is the var_dump($input, $tags, $tag);

 

string(18) "Hey, ho, let's, go" array(4) { [0]=> string(3) "Hey" [1]=> string(3) " ho" [2]=> string(6) " let's" [3]=> string(3) " go" } string(3) "Hey" string(18) "Hey, ho, let's, go" array(4) { [0]=> string(3) "Hey" [1]=> string(3) " ho" [2]=> string(6) " let's" [3]=> string(3) " go" } string(2) "ho" string(18) "Hey, ho, let's, go" array(4) { [0]=> string(3) "Hey" [1]=> string(3) " ho" [2]=> string(6) " let's" [3]=> string(3) " go" } string(5) "let's" string(18) "Hey, ho, let's, go" array(4) { [0]=> string(3) "Hey" [1]=> string(3) " ho" [2]=> string(6) " let's" [3]=> string(3) " go" } string(2) "go"

    //check for tags
    if (isset($_POST['tag'])) {
        $input = $_POST['tag'];
        $tags = explode(',', $input);
        }else { //if empty
        $tag = NULL;
        }
    if (isset ($tags)) {
        foreach($tags as $tag) {    
           $tag = trim($tag);    
           $q = 'INSERT INTO tag (tag_display, tag, coll_id) VALUES (?, ?, ?)';
           $stmt = mysqli_prepare($dbc, $q);
           mysqli_stmt_bind_param($stmt, 'ssi', $input, $tag, $c);
           mysqli_stmt_execute($stmt);
           //var_dump($input, $tags, $tag);
        }
    }

Share this post


Link to post
Share on other sites

Is your DB query valid?

Right before your $q assignment, try echoing $tag to the screen and making sure it's what you want.

 

Also, right after your mysqli_prepare function call, do the following to see whether your statement object is valid or not:

if ($stmt)
  
  // Valid.
  
} else {
  
  // Not valid.
  
}

Share this post


Link to post
Share on other sites

It turns out that it wouldn't post because $c is declared later on. I have the page organized with a validation section and a query section, so I ended up having to stick it all in the query section to get all the parts moving. If you hadn't suggested checking $stmt I would have never figured it out because I cut and pasted the query directly into the loop, so I knew it worked!

 

Thanks again!!!

 

Here is the final code:

//check for tags
	if (isset($_POST['tag'])) {
		$input = $_POST['tag'];
		$tags = explode(',', $input);
		foreach($tags as $tag) {    
			$tag = trim($tag); 
			//echo $tag;
			$q = 'INSERT INTO tag (tag_display, tag, coll_id) VALUES
			(?, ?, ?)';
			$stmt = mysqli_prepare($dbc, $q);
			mysqli_stmt_bind_param($stmt, 'ssi', $input, $tag, $c);
			mysqli_stmt_execute($stmt);
  }
		}else{ 
		if (isset($_POST['tag'])){//if empty
		$tag = NULL;
		$q = 'INSERT INTO tag (tag_display, tag, coll_id) VALUES
			(?, ?, ?)';
			$stmt = mysqli_prepare($dbc, $q);
			mysqli_stmt_bind_param($stmt, 'ssi', $input, $tag, $c);
			mysqli_stmt_execute($stmt);
		} 		
}

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  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.

Loading...
Sign in to follow this  

×
×
  • Create New...