Jump to content

PHP - How to take an image from an array and save it to MYSQL?


Zorglub
Go to solution Solved by Zorglub,

Recommended Posts

Hi

 

Now I don't mean saving the whole array, only number, say 3. How would you do that?

 

My code so far:

    // DATABASE CONNECTION /////////////////////////////////////
    $servername = "localhost";
    $username = "root";
    $password = "Fun";
    $dbname = "visited";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
    }
    $dateValue = date('d-m-Y H:i:s');
    $sql = "INSERT INTO latest (timestamp, vehicleid, img) VALUES ('$dateValue', '$vehicle->VehicleId', '$vehicle->Pictures[0]')";

    if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
    } else {
    echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $conn->close();

    /////////////////////////////////////////////////////////

But it only inserts "Array()" into to the MYSQL...

Edited by Zorglub
Link to comment
Share on other sites

26 minutes ago, Zorglub said:

Hi

 

Now I don't mean saving the whole array, only number, say 3. How would you do that?

 

My code so far:

    // DATABASE CONNECTION /////////////////////////////////////
    $servername = "localhost";
    $username = "root";
    $password = "Fun";
    $dbname = "visited";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
    }
    $dateValue = date('d-m-Y H:i:s');
    $sql = "INSERT INTO latest (timestamp, vehicleid, img) VALUES ('$dateValue', '$vehicle->VehicleId', '$vehicle->Pictures[0]')";

    if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
    } else {
    echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $conn->close();

    /////////////////////////////////////////////////////////

But it only inserts "Array()" into to the MYSQL...

Not sure if this is what you were looking for but it's what I used when I used MySQLi  to upload an image:


$image = mysqli_real_escape_string($con, $_FILES['image']['name']);
  	// image file directory
  	$target = "images/".basename($image);
  	    if(!empty($_FILES['image']['name'])) {
    $sql = "UPDATE table SET image='".$image."'"; 
  	}
     $result = mysqli_query($con, $sql);

  	if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
  		$msg = "Image uploaded successfully";
  	}else{
  		$msg = "Failed to upload image";
  	}
  	
     if(!$result){ 
        die('Error: ' . mysqli_error($con));
     } else{ 
            
       $message = ' - <i class="fa fa-check text-success"> Record Updated!</i>';

    } 
    }

}

I know it's not an INSERT but the image upload script should still work.

Sorry if this is not what you are looking for.

BTW: go to PDO. It's more fun.

Link to comment
Share on other sites

Actually storing images in a table is not a good idea.  Better to store a link to the images wherever they are saved.  Maybe create a folder for them and simply save the path in a static place and the image names in the table.  Storing the path in the table leads to problems should you ever have to move the image folder. Storing the images in the table just adds bloat to the table.

My $.02

Link to comment
Share on other sites

The array contains url's to the images, so I do not need to upload any images... The data is a JSON url...

 

The whole code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Look at car</title>
    <link rel="stylesheet" href="./css/style-show-room.css">
</head>

<body>

    <div class="container">

    <?php
    $id = $_GET['VehicleId'];

    $url = 'https://gw.bilinfo.net/listingapi/api/export';

    // provide your username and password here
    $auth = base64_encode("demo:ocfB6XzF73");

    // create HTTP context with basic auth
    $context = stream_context_create([
        'http' => ['header' => "Authorization: Basic $auth"]
    ]);

    // query for data
    $data = file_get_contents($url, false, $context);
    // $escaped = json_encode($data);
    $escaped = json_decode($data); //, JSON_FORCE_OBJECT

    /*Initializing temp variable to design table dynamically*/
    $temp = "<table class='car-list'>";

    /*Defining table Column headers depending upon JSON records*/
   /*Dynamically generating rows & columns*/
    foreach ($escaped->Vehicles as $vehicle) {

        if($vehicle->VehicleId == $id) {
        
    // DATABASE CONNECTION /////////////////////////////////////
    $servername = "localhost";
    $username = "root";
    $password = "Wichmand14";
    $dbname = "visited";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
    }
    $dateValue = date('d-m-Y H:i:s');
    $sql = "INSERT INTO latest (timestamp, vehicleid, img) VALUES ('$dateValue', '$vehicle->VehicleId', '$vehicle->Pictures[0]')";

    if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
    } else {
    echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $conn->close();

    /////////////////////////////////////////////////////////

        // INSERT VIEWED CAR - END

        $temp .= "<tr>";
        $temp .= "<th colspan='4' class='th-style'>" . $vehicle->Make . " " . $vehicle->Model . " " . $vehicle->Variant . "</th>";
        $temp .= "</tr>";
        $temp .= "<tr>";
        $temp .= "<td colspan='4' class='td-style'>";
        for ($p = 0; $p < $vehicle->PictureCount; $p++) {

            if ($p < 1) {
                $temp .= "<table class='images-table'>";
                $temp .= "<tr>";
                $temp .= "<td rowspan='2' class='td-style'>";
                $temp .= "<img class='cc-images' src='" . $vehicle->Pictures[$p] . "'>";
                $temp .= "</td>";
                $temp .= "</tr>";
                $temp .= "</table>";
            }
        }
        $temp .= "</td>";
        $temp .= "</tr>";
        $temp .= "<tr>";
        $temp .= "<td class='td-style'>Producent: " . $vehicle->Make . "</td>";
        $temp .= "<td class='td-style'>Model: " . $vehicle->Model . "</td>";
        $temp .= "<td class='td-style'>Variant: " . $vehicle->Variant . "</td>";
        $temp .= "<td class='td-style'>Sælger: " . $vehicle->DealerName . "</td>";
        $temp .= "</tr>";
        $temp .= "<tr>";
        $temp .= "<td class='td-style'>Pris: " . $vehicle->Price . "</td>";
        $temp .= "<td class='td-style'>Type: " . $vehicle->PriceType . "</td>";
        $temp .= "<td class='td-style'>Kontaktpris: " . $vehicle->CashPrice . "</td>";
        $temp .= "<td class='td-style'>Udsalgspris: " . $vehicle->WholesalePrice . "</td>";
        $temp .= "</tr>";
        $temp .= "<tr>";
        $temp .= "<td colspan='4' class='td-style'>Bil id: " . $vehicle->VehicleId . "</td>";
        $temp .= "</tr>";

        }
    }


        // START
        $servername2 = "localhost";
        $username2 = "root";
        $password2 = "Wichmand14";
        $dbname2 = "visited";
        
        // Create connection
        $conn2 = new mysqli($servername2, $username2, $password2, $dbname2);
        // Check connection
        if ($conn2->connect_error) {
          die("Connection failed: " . $conn2->connect_error);
        }
        
        $sql2 = "SELECT * FROM latest LIMIT 3";
        $result2 = $conn2->query($sql2);
        
        if ($result2->num_rows > 0) {
          // output data of each row
          while($row = $result2->fetch_assoc()) {
            for ($i = 0; $i < 3; $i++) {
                if ($i < 3) {
                    $temp .= "<tr>";
                    $temp .= "<td colspan='2'>";
                    $temp .= "<img class='latest-img' src='" . $row["img"] . "'>";
                    $temp .= "" . $row["img"] . "";
                    $temp .= "</td>";

                    $temp .= "<td colspan='2'>" . $row["vehicleid"]. "</td>";
                    $temp .= "</tr>";
                    }
                }
          }
        } else {
          echo "0 results";
        }
        $conn2->close();
        // END


    /*End tag of table*/
    $temp .= "</table>";


    /*Printing temp variable which holds table*/
    echo $temp;

    // echo $data;

?>
    </div>
</body>

</html>

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.