1

I tried it myself and was stuck on query itself. It might not even be the query that's wrong, I'm not sure. What is the correct way to update an image if a user decides to change their profile picture?

    <?php
session_start();
       $msg = "";
       $username = $_SESSION['username'];
if (isset($_POST['upload'])) {
    $target = "img/".basename($_FILES['image']['name']);

    if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
        $db = mysqli_connect("localhost", "root", "", "database");
        $images = $_FILES['image']['name'];
        $sql = "UPDATE users SET image='$images' WHERE username='$username'";
        mysqli_query($db, $sql);
        $msg = echo "Image Uploaded Successfully";
        header("Location: profile.php?uploadsuccess");
    } else {
        $msg = "There Was A problem uploading image";
    }
}
?>




    CREATE TABLE `users` (
  `id` int(8) NOT NULL,
  `first_name` varchar(30) NOT NULL,
  `last_name` varchar(30) NOT NULL,
  `username` varchar(32) NOT NULL,
  `email` varchar(60) NOT NULL,
  `password` varchar(40) NOT NULL,
  `images` varchar(200) NOT NULL
Karen Page
  • 33
  • 6
  • Is there something wrong with the code you posted? – Difster Aug 07 '17 at 22:52
  • Yes, I'm getting success, but it's not updating the field in the database – Karen Page Aug 07 '17 at 22:56
  • What is the data type of your image field? – Difster Aug 07 '17 at 22:58
  • I added the structure in the question – Karen Page Aug 07 '17 at 22:59
  • Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use prepared statements with bound parameters, via either the [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php) drivers. [**This post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) has some good examples. – Alex Howansky Aug 08 '17 at 02:24

1 Answers1

0

You're trying to upload an actual image to a field that will only hold 200 characters. Take a look at your structure, what you need to do is save the image to whatever directory is configured for that purpose and only save the name (and possibly path) of that image to the image field in your database.

Difster
  • 3,264
  • 2
  • 22
  • 32
  • You don't have an `image` column in your `users` table, you have `images`. Follow his instructions and research mysqli prepared statements with placeholders for improved security. – mickmackusa Aug 08 '17 at 01:44