-3

Here's my code what i've been trying to do. I've tried to upload(insert) image into a folder and a database, but I'm unable to Insert an Image into a folder and a database. Please help me if you see some mistake in my code. It is inserting Title, Date, Content but no Image.

if(isset($_POST['submit'])){
    $title = $connection->real_escape_string($_POST['title']);
    $datum = $connection->real_escape_string($_POST['datum']);
    $content = $connection->real_escape_string($_POST['editor']);
    $image = $_FILES['image'];
    $imageName = $_FILES['image']['name'];
    $imageTmpName = $_FILES['image']['tmp_name'];
    $imageError = $_FILES['image']['error'];
    $imageType = $_FILES['image']['type'];
    $imageExt = explode('.', $imageName);
    $imageActualExt = strtolower(end($imageExt));
    $allowed = array('jpg', 'jpeg', 'png');

    if(in_array($imageActualExt, $allowed)) {
        if($imageError === 0) {
            $imageNameNew = uniqid('', true).".".$imageActualExt;
            $imageDestination = 'images/'.$imageNameNew;
            move_uploaded_file($imageTmpName, $imageDestination);
            $sql = "INSERT INTO `articles` (`image`) VALUES ('$imageNameNew')";
            $qry = mysqli_query($connection, $sql);
            echo "Image was uploaded";            
        }
    } else {
        echo "Cannot upload an image";
    }

    $sql = "INSERT INTO `articles` (`title`, `datum`, `content`) VALUES ('$title', '$datum', '$content')";

    if ($connection->query($sql) === true){
        echo '<script language="javascript">';
        echo 'alert("Post successfully uploaded")';
        echo '</script>';
    }else {
        die("mistacke with uploading a post".mysqli_connect_error());
    };
    header('location: Admin-clanky-Sprava-clanku.php');
};
<form method="post" action="Admin-clanky-vytvorit-clanek.php" enctype=”multipart/form-data”>            
                    <div class="inputs">
                        <input type="file" name="image" src="" alt="">
                    </div>
                    <div>
                        <input type="submit" name="submit" value="Přidat článek">
                    </div>
ADyson
  • 57,178
  • 14
  • 51
  • 63
  • 4
    "Unable to" isn't an error message or a useful problem statement. We can't fix "Unable to" in code, like a mechanic can't fix a car that is "Unable to work" without any other information about the problem. How isn't it working? What [debugging](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) have you done? What exactly happens when you run this? What did you expect to happen instead? Please provide details of error messages, unexpected behaviour etc. See also [What do you mean "It doesn't work"?](https://meta.stackexchange.com/questions/147616/what-do-you-mean-it-doesnt-work) – ADyson Aug 30 '23 at 12:25
  • 3
    **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unparameterised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. mysqli_real_escape_string is obsolete and doesn't guard against everything. – ADyson Aug 30 '23 at 12:25
  • https://phpdelusions.net/mysqli also contains good examples of writing safe SQL using mysqli. See also the [mysqli documentation](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) and this: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) . Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped or incorrectly quoted input values. If you learnt your current technique from a tutorial or book, please don't use that resource again. – ADyson Aug 30 '23 at 12:25
  • And please bring your SQL error handling into the 21st century. Add `mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);` before your `mysqli_connect()` (or `new mysqli()`) command, and this will ensure that errors with your SQL queries are reported correctly to PHP automatically. That way you don't need to clutter your script with repetitive code to keep checking errors after every mysqli command. And you should never be echoing error data deliberately - it can easily reveal sensitive info to attackers by accident. – ADyson Aug 30 '23 at 12:26
  • 1
    Inserting into `articles` twice is likely to cause a bug. You also should do some checking on what file is being uploaded don't want someone uploading `destroymyserver.php` then loading the path to execute that script. – user3783243 Aug 30 '23 at 12:26
  • `It is inserting Title, Date, Content but no Image`...well your code makes no sense, if that's what you're expecting. At the very best, it _will_ insert the image, but on a different row of the table. (Each `INSERT` tries to create a new row). But very possibly, it never gets to execute that line, or perhaps the query fails. Again...did you do any meaningful debugging?? We can't tell you exactly what your code will do, since we don't have access to your environment. We can only point out flaws based on what you tell us. So far the code has logical issues, but we can't detect runtime issues. – ADyson Aug 30 '23 at 12:31
  • Either way though, you need a slight re-think. Is uploading an image optional? If so, consider inserting the data into `articles` first and capturing the ID of the inserted row (using last_insert_id()). Then you should try to validate and save the image to disk, and if that succeeds, you should `UPDATE` the row you just inserted in order to to add the image data to it. – ADyson Aug 30 '23 at 12:33
  • Also... `enctype=”multipart/form-data”` ...is this a typo in your post here, or does this issue exist in your real code too? It should be `enctype="multipart/form-data"` using proper plain-text quote marks. – ADyson Aug 30 '23 at 12:35
  • And I don't know where you think `$_POST['title']`, `$_POST['datum']` and `$_POST['content']` are going to come from, because they are not part of the HTML form you've shown us. Did you omit them from your example HTML in this post for some reason? There is also no `` closing tag either. Make sure you provide a [mre] of the issue which is coherent and would accurately demonstrate the problem if you executed it. – ADyson Aug 30 '23 at 12:37
  • Does this answer your question? [Full Secure Image Upload Script](https://stackoverflow.com/questions/38509334/full-secure-image-upload-script) – ADyson Aug 30 '23 at 13:04
  • Also... enctype=”multipart/form-data” ...is this a typo in your post here, or does this issue exist in your real code too? It should be enctype="multipart/form-data" using proper plain-text quote marks. This seemed to be the problem..Thank you for your help :D – Jiří Szopa Aug 30 '23 at 19:55
  • Glad it helped. That isn't your only problem though, as per the various other comments :-) – ADyson Aug 30 '23 at 21:37

0 Answers0