I'm trying to run two stmts and bind them with php. When I just run the $stmt and delete all of $stmt2, it works perfectly. I'm trying to change the 'active' column to Zeros. Basically trying to search and update all the other pictures the user has uploaded and change them to zero (so that it's not profile picture), only the most recent one should be active (1 in the $active).
if (!$mysqli) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
echo $db;
exit;
}
try {
if (empty($_FILES['image'])) {
throw new Exception('Image file is missing');
}
$image = $_FILES['image'];
// check INI error
if ($image['error'] !== 0) {
if ($image['error'] === 1)
throw new Exception('Max upload size exceeded');
throw new Exception('Image uploading error: INI Error');
}
// check if the file exists
if (!file_exists($image['tmp_name']))
throw new Exception('Image file is missing in the server');
$maxFileSize = 2 * 10e6; // in bytes
if ($image['size'] > $maxFileSize)
throw new Exception('Max size limit exceeded');
// check if uploaded file is an image
$imageData = getimagesize($image['tmp_name']);
if (!$imageData)
throw new Exception('Invalid image');
$mimeType = $imageData['mime'];
// validate mime type
$allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($mimeType, $allowedMimeTypes))
throw new Exception('Only JPEG, PNG and GIFs are allowed');
// nice! it's a valid image
// get file extension (ex: jpg, png) not (.jpg)
$fileExtention = strtolower(pathinfo($image['name'] ,PATHINFO_EXTENSION));
// create random name for your image
$fileName = round(microtime(true)) . mt_rand() . '.' . $fileExtention; // anyfilename.jpg
// Create the path starting from DOCUMENT ROOT of your website
$path = '/php/image_upload/images/' . $fileName;
// file path in the computer - where to save it
$destination = $_SERVER['DOCUMENT_ROOT'] . $path;
if (move_uploaded_file($image['tmp_name'], $destination)) {
// create the url
$protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === true ? 'https://' : 'http://';
$domain = $protocol . $_SERVER['SERVER_NAME'];
$url = $domain . $path;
$active = 1;
$mysqli->autocommit(FALSE);
$stmt2 = $mysqli->prepare('UPDATE image_uploads SET active = ? WHERE user_id = ?');
$stmt = $mysqli -> prepare('INSERT INTO image_uploads (url, active, user_id) VALUES (?, ?, ?)');
if (
$stmt &&
$stmt2 &&
$stmt2 -> bind_param('ii', 0, $_SESSION['id']) &&
$stmt -> bind_param('sii', $url, $_SESSION['id'], $active) &&
$stmt2 -> execute() &&
$stmt -> execute()
) {
exit(
json_encode(
array(
'status' => true,
'url' => $url
)
)
);
} else {
throw new Exception('Error in saving into the database');
}
}
} catch (Exception $e) {
exit(json_encode(
array (
'status' => false,
'error' => $e -> getMessage()
)
));
}