Foreach error

I ran into this error


on this

<?php
session_start();
include '../db/pdo_conn.php'; 

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


	if($_SERVER["REQUEST_METHOD"] == "POST") {
		
	  $project_id = (int)$_POST['project_id'];
		  
		foreach($_POST['assets'] AS $index => $asset) {
			
			try{
			$sql = "UPDATE assets SET project_id = ".$project_id." WHERE asset_id = ".$asset[$index];    

			echo $sql."<br>";
			//die();
			$pdo->exec($sql);
			
			} catch(PDOException $e){
				die("ERROR: Could not able to execute $sql. " . $e->getMessage());
			}	
		}
			header("location: add_assets_success.php?id=".$project_id."");
			


	}

?>

I dont know what this means

foreach($_POST[‘assets’] AS $index => $asset) {

Looking at the print_r of $_POST[‘assets’] compared to your foreach statement you can see that $index represents the KEYS in the $_POST[‘assets’] array (0,1,2) and $asset represents the VALUES in the $_POST[‘assets’] array. So $asset is singular value like (2,3,4) and not an array with [KEYS], so $asset[$index] will throw an error as $index is not a key of $asset.

Using

$_POST['assets'][$index]

would give you the foreach value OR you could sumply use

$asset

as it represents the VALUES in the $_POST[‘assets’] array.

1 Like

And for future reference just copy/paste your error into a code block. Much easier to read than images. And much much easier to copy from.

3 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.