I'm trying to add an image upload function to my form, that uses an own table. The problem is, it needs the 'cardid' which is a foreign key, because that's how I want to store which image belongs to which card. The problem is, I can't get the cardid because I want to upload the image on the same page where the user creates the card. So, it has no ID yet. My 'cards' table looks like this:
id - name - phone - more fields - userid
and the'cardimages' table:
id - cardid - image - name
here's my code:
<?php
session_start();
header('Content-type: text/html; charset=utf-8');
require_once("db_connect.php");
// Prepare an insert statement
$sql = "INSERT INTO cards (name, phone, phone2, email, zipcode, address, company, job, description, userid) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
if($stmt = mysqli_prepare($conn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ssssissssi", $name, $phone, $phone2, $email, $zipcode, $address, $company, $job, $description, $userid);
if(isset($_POST['name'])){
$name = $_POST['name'];
}
if(isset($_POST['phone'])){
$phone = $_POST['phone'];
}
if(isset($_POST['phone2'])){
$phone2 = $_POST['phone2'];
}
if(isset($_POST['email'])){
$email = $_POST['email'];
}
if(isset($_POST['zipcode'])){
$zipcode = $_POST['zipcode'];
}
if(isset($_POST['address'])){
$address = $_POST['address'];
}
if(isset($_POST['company'])){
$company = $_POST['company'];
}
if(isset($_POST['job'])){
$job = $_POST['job'];
}
if(isset($_POST['description'])){
$description = $_POST['description'];
}
if(isset($_SESSION['id'])){
$userid = $_SESSION['id'];
}
if(isset($_POST['upload'])){
$name = $_FILES['file']['name'];
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
// Select file type
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Valid file extensions
$extensions_arr = array("jpg","jpeg","png","gif");
// Check extension
if( in_array($imageFileType,$extensions_arr) ){
// Convert to base64
$image_base64 = base64_encode(file_get_contents($_FILES['file']['tmp_name']) );
$image = 'data:image/'.$imageFileType.';base64,'.$image_base64;
$sql = "SELECT id FROM cards";
if(isset($_POST['id'])){
$cardid = $_POST['id'];
}
// Insert record
$sql = "INSERT INTO cardimages(cardid, name, image) VALUES ('".$cardid."', '".$name."','".$image."')";
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'],'upload/'.$name);
}
}
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
header("Location: addbusiness.php?message=1");
} else{
echo "ERROR: Could not execute query: $sql. " . mysqli_error($conn);
}
} else{
echo "ERROR: Could not prepare query: $sql. " . mysqli_error($conn);
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($conn);
?>