How to upload multiple images into a row in the database

general-dev
#1

i am try to upload multiple image into a row in my db. And I get this error
Array to string conversion. thanks
Here is my code.

if (isset($_POST['submit']))

	{	

				//list out your form variables...
				$property_name=$_POST['property_name'];
				$property_location=$_POST['property_location'];
				$property=$_FILES['property']['name'];
				$property_price=$_POST['property_price'];
				$category_id=$_POST['category_id'];
				$status=$_POST['status'];

				if (empty($property_name)){
					echo "Enter Property Location.";
				}elseif (empty($property_location)) {
					echo "Description";
					# code...
				}elseif (empty($property)) {
					echo "Select an Image .";
					# code...
				}elseif (empty($property_price)) {
					echo "Enter Price.";
					# code...
				}
				elseif(empty($category_id)){
					echo "category_id Feild is required";
				}elseif (empty($status)){
					echo "Indicate Status of Property";
					# code...
				}else 
				     
				    $image_name='';
					$images_name=array();
					
				    for( $x=0; $x < count( $_FILES['property']['tmp_name'] ); $x++ ) {
 {
				    	
				        $file_name = $_FILES['property']['name'][$x];
                        $file_size = $_FILES['property']['size'][$x];
                        $file_tmp = $_FILES['property']['tmp_name'][$x];
				            
				            /* Less complicated and more reliable method to find the file extension!! */
                            $file_ext = strtolower( pathinfo( $file_name, PATHINFO_EXTENSION ) );
                            $ext_boleh = array( 'jpg', 'jpeg', 'png', 'gif', 'bmp' );
                             if( in_array( $file_ext, $ext_boleh ) ) {
				            $uploads_dir = 'uploads/';
				            $add= move_uploaded_file($file_tmp, $uploads_dir. $file_name);
				            if($add)$images_name[]=$file_name;
                          var_dump($file_name);
				             
				            }
				        }
				                
		 // inserting into the database...

          	      $add_pro=$db->insertRow("INSERT INTO property (property_name, property_location, property, property_price, category_id, status)VALUES (?, ?, ?, ?, ?, ?)",
							[$property_name, $property_location, $property, $property_price, 
							$category_id, $status]);
          	                //$arrayName = array(':property_name' =>$property_name ,
          	                      //             ':property_location'=>$property_location,
          	                        //             ':property'=>implode(',', ) );
							if ( $add_pro== True){
					 			echo "File upload successfully";
                 				 }
					       else{ echo "Upload was Unsuccessful...";}

here is my database class

class Database{
public $isconn;
protected $datab;
public $error;
//connect to db
public function __construct($username="root", $password="", $host= "localhost", $dbname="gold", $options =[]){
	$this->isConn= TRUE;
try{
$this->datab=new PDO("mysql:host={$host};dbname={$dbname};charaset=utf8", $username,$password,$options);
$this->datab->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}catch (PDOException $e){
throw new Exception($e->getMessage()); 
}
}
//disconnect from db
public function Disconnect(){
	$this->datab=null;
	$this->isConn=false;
}
//get row
public function getRow($query,$params=[]){
	try{
	$stmt=$this->datab->prepare($query);
	$stmt->execute($params);
	return $stmt->fetch();
	}
	catch (PDOException $e){throw new Exception($e->getMessage());
	}
	}
//get rows
public function getRows($query,$params=[]){
	try{
	$stmt=$this->datab->prepare($query);
	$stmt->execute($params);
	return $stmt->fetchAll();
	echo $stmt;
	}
	catch (PDOException $e){
	throw new Exception($e->getMessage());
	}
		}
//insert row
	public function insertRow($query,$params=[]){
	try{		
	$stmt=$this->datab->prepare($query);
	$stmt->execute($params);
	return TRUE;
	}catch (PDOException $e){
	throw new Exception($e->getMessage());
	}
	}
#2

On what line is it throwing that error?

#3

my database class.Exception any suggestion?

#4

Try adding this DEBUG script to see the values that are failing. It looks as though a string is expected and an array is trying to be passed:

// DEBUG START
var_dump( $property_name );
var_dump( $property_location ); 
var_dump( $property );  
var_dump( $property_price );  
var_dump( $category_id );  
var_dump( $status ); 
die; // halt execution
// DEBUG END

$sql =  "INSERT INTO property 
	(
		property_name, 
		property_location, 
		property, 
		property_price, 
		category_id, 
		status
	)
	VALUES 
	(
		?, ?, ?, ?, ?, ?
	)
	";

echo $sql;

$add_pro = $db->insertRow
( 
$sql, 
  [
	$property_name, 
	$property_location, 
	$property, 
	$property_price, 
	$category_id, 
	$status
  ]
) ;

#5

If you are uploading multiple images, won’t this line

$property=$_FILES['property']['name'];

mean that $property is an array, and therefore will throw the error when you use it in this line?

$add_pro=$db->insertRow("INSERT INTO property (property_name, property_location, property, property_price, category_id, status)VALUES (?, ?, ?, ?, ?, ?)",
[$property_name, $property_location, $property, $property_price, $category_id, $status]);

You deal with the multiple entries when you’re moving the uploaded files, you need to do something about it for the query, too.

1 Like
#6

any suggestion of what to do to the array. $property before inserting it.
i tried " implode" but that did not work.

#7

Please show the following contents:


var_dump( $property );
die;
#8

i get an array.

#9

That is why the query is failing.

var_dump(…); displays the array element names which is required to pass as a string to the query.

#10

i now get a string. but still showing same error. when i remove
die function from it. any suggestion please.

#11

Is the string the value of var_dump( $property );

What is the string value?

#12

i just fixed that now. but am not getting the exact result.
i actually want all the image in a row. but the increase progressively until the selected image are inserted. like this

#14

Follow up…

In PM OP tells me he has an image table and seems to know about getting the last insert id to do the image insert so at this point I am not sure what the problem is. Apparently there was a miscommunication with the OP in PM.

#15

i will fix that. what i meant is i need to commit to the data base first before i can insert image.
thanks so much for your assistance. i appreciate.

#16

Got it. Just to be clear, the process is what is described in PM. On submit insert property data to the property table, capture the last_insert_id and use that to insert the image data to the images table. It is a pretty straight forward process. Let me/us know if you get stuck.

#17

Yes, you really don’t want to have a single column in your table that contains multiple values. It will make it very difficult to retrieve stuff. The separate images table is the way to go.

2 Likes
#18

hi guys i have a challenge of inserting multiple image at once.
one image goes into the db from the array of images i selected .
here is my code thanks.

if (isset($_POST[‘submit’]))

{			//list out your form variables...
		$property_name=$_POST['property_name'];
		$property_location=$_POST['property_location'];
		//$property=$_FILES['property']['name'];
		$property_price=$_POST['property_price'];
		$category_id=$_POST['category_id'];
		$status=$_POST['status'];

		if (empty($property_name)){
					echo "Enter Property Location.";
				}elseif (empty($property_location)) {
					echo "Description";
					# code...
				}elseif (empty($property_price)) {
					echo "Enter Price.";
					# code...
				}
				elseif(empty($category_id)){
					echo "category_id Feild is required";
				}elseif (empty($status)){
					echo "Indicate Status of Property";
					# code...
				}else{
					//validation

       $sql="INSERT INTO `property` (property_name, property_location, property_price, category_id, status)VALUES (:property_name, :property_location, :property_price, :category_id, :status)";

      	     $params=[':property_name'=>$property_name, 
      	              ':property_location'=>$property_location,
      	              ':property_price'=>$property_price, 
					  ':category_id'=>$category_id, 
					  ':status'=>$status];

	    //var_dump($db->runQuery($sql,$params));
						$inserting=$db->runQuery($sql,$params);

						if ($inserting==1)
						{			
									
							$pro_id= $db->lastId();
							var_dump($pro_id);
                              $property_img=$_FILES['property_img']['name'];
	                          if (empty($property_img))
	               
	                          	{ echo "Enter Property Images.";}

	                          // uploading image file.
					
				   else{
				   	     $image_name='';
				$images_name=array();
				foreach($_FILES['property_img']['tmp_name'] as $i => $tmp_name ){

					 $property_img = $_FILES['property_img']['name'][$i];
                    $file_size = $_FILES['property_img']['size'][$i];
                    $file_tmp = $_FILES['property_img']['tmp_name'][$i];
				 				    
				 				    \
		        /* Less complicated and more reliable method to find the file extension!! */
                    $file_ext = strtolower( pathinfo( $property_img, PATHINFO_EXTENSION ) );
                     $ext_boleh = array( 'jpg', 'jpeg', 'png', 'gif', 'bmp' );
                      if( in_array( $file_ext, $ext_boleh ) ) {
			         $uploads_dir = 'uploads/';
			         $add= move_uploaded_file($file_tmp, $uploads_dir. $property_img);
			             print_r($property_img);

$sql2=“INSERT INTO property_img (property_img, pro_id)VALUES (?,?)”;

					$params=[$property_img,$pro_id];

      	              $img=$db->runQuery($sql2,$params);

                  if($img!=0){
                  	echo "file uploaded successfully";

                  }
                  else {
                  	echo "Error in file Upload.";
                  }

Reply

closed #19

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