Jakub L Jakub L - 3 months ago 18
PHP Question

PHP How to use variable from one if statement in another?

I have a little problem.

I'm making form that submits simple article to database and then displays it on admin.php page.

Everything works fine, except image.
First i upload it to my server and then I try to add string(path of this image) to database.

However I can't use variable $filepath in second if statement.
I can echo it after image upload but can't use in other if.

Could u help me?
Thanks in advance.

Here's code:

<?php session_start();
if (!isset($_SESSION['logged-in']))
header('Location: index.php');
if(isset($_POST['btn_upload'])) {
$filetmp = $_FILES["file_img"]["tmp_name"];
$filename = $_FILES["file_img"]["name"];
$filetype = $_FILES["file_img"]["type"];
$filepath = "photo/".$filename;


$result = mysqli_query($mysqli, "INSERT INTO upload_img (img_name,img_path,img_type) VALUES ('$filename','$filepath','$filetype')");

echo '<img src="' . $filepath . '" alt="">';
echo $filepath;

if ( isset($_POST['add']) ) {
$title = strip_tags($_POST['title']);
$content = strip_tags($_POST['content']);
$image = strip_tags($filepath);
$statement = $mysqli->prepare("INSERT bikes (title,image,content) VALUES (?,?,?)");
header('Location: admin.php');

<form method="post" action="" class="ui form">
<div class="required field">
<input type="text" name="title" id="title">
<div class="required field">
<textarea name="content" id="content" cols="30" rows="10"></textarea>
<div class="required field">
<input type="text" name="image" id="image">
<input type="submit" class="ui primary button" id="add" name="add" value="Add article"></input>

<form action="addbike.php" method="post" enctype="multipart/form-data">
<input type="file" name="file_img" />
<input type="submit" name="btn_upload" value="Upload">

Answer Source

btn_upload is mutually exclusive to add, so the if statement which executes for btn_upload doesn't also run for add.

If you want it to be a two-phase process (upload image, then add) then you have to set a hidden input whose value is the filepath.

However, ideally the user would fill in name and provide an image and then submit them together. In order to do that, place all inputs inside the same form element and remote the "Add" button.