Asked  7 Months ago    Answers:  5   Viewed   31 times

How can I insert an image in MySQL and then retrieve it using PHP?

I have limited experience in either area, and I could use a little code to get me started in figuring this out.

 Answers

86

First you create a MySQL table to store images, like for example:

create table testblob (
    image_id        tinyint(3)  not null default '0',
    image_type      varchar(25) not null default '',
    image           blob        not null,
    image_size      varchar(25) not null default '',
    image_ctgy      varchar(25) not null default '',
    image_name      varchar(50) not null default ''
);

Then you can write an image to the database like:

/***
 * All of the below MySQL_ commands can be easily
 * translated to MySQLi_ with the additions as commented
 ***/ 
$imgData = file_get_contents($filename);
$size = getimagesize($filename);
mysql_connect("localhost", "$username", "$password");
mysql_select_db ("$dbname");
// mysqli 
// $link = mysqli_connect("localhost", $username, $password,$dbname); 
$sql = sprintf("INSERT INTO testblob
    (image_type, image, image_size, image_name)
    VALUES
    ('%s', '%s', '%d', '%s')",
    /***
     * For all mysqli_ functions below, the syntax is:
     * mysqli_whartever($link, $functionContents); 
     ***/
    mysql_real_escape_string($size['mime']),
    mysql_real_escape_string($imgData),
    $size[3],
    mysql_real_escape_string($_FILES['userfile']['name'])
    );
mysql_query($sql);

You can display an image from the database in a web page with:

$link = mysql_connect("localhost", "username", "password");
mysql_select_db("testblob");
$sql = "SELECT image FROM testblob WHERE image_id=0";
$result = mysql_query("$sql");
header("Content-type: image/jpeg");
echo mysql_result($result, 0);
mysql_close($link);
Tuesday, June 1, 2021
 
QuantumMechanic
answered 7 Months ago
67

This is an overly simplified answer and should be taken with a grain of salt, as most answers about security:

  • Use SSL everywhere.

  • Use a secure encryption key

For storage of encrypted data, you could use a BLOB field, and use MySQL's built in encryption functions. Example:

update mytable set myfield = AES_ENCRYPT('some value', SHA2('your secure secret key', 512));

If you prefer to do the encryption/decryption in the application code, take a look at PHP's Mcrypt functions.

  • Encrypt the user input
  • Store in the database
  • Decrypt it after fetching it

This is by no means a complete guide, but it's a start and better than doing nothing.

You may be able to learn more on https://security.stackexchange.com/

Wednesday, March 31, 2021
 
BetaRide
answered 9 Months ago
29

You should parse information from information_schema.columns table -

SELECT
  column_type
FROM
  information_schema.columns
WHERE
  table_schema = 'your_schema' AND table_name = 'your_table' AND column_name = 'your_column'

...another query -

SELECT
  TRIM(TRAILING ')' FROM TRIM(LEADING '(' FROM TRIM(LEADING 'enum' FROM column_type))) column_type
FROM
  information_schema.columns
WHERE
  table_schema = 'your_schema' AND table_name = 'your_table' AND column_name = 'your_column';

There will be something like this - enum('01','02','03'). Parse this string in the php-application.

Wednesday, March 31, 2021
 
Slinky
answered 9 Months ago
10

You don't need to escape your variables in a prepared statement, instead you should bind your variables before executing the statement. Also the column names should be inside ` marks.

$stmt = $dbConnectionW->prepare("UPDATE members SET 
                      `fname`=?,
                      `sname`=?,
                      `gender`=?,
                      `nationality`=?,
                      `year`=?,
                      `dep1`=?,
                      `dep2`=?,
                      `f_pos`=?,
                      `f_region`=?,
                      `exp_comp`=?,
                      `exp_dep`=?,
                      `shareinfo`=?,
                      `interest`=?,
                      `userconfirm`=?
                          WHERE `confirmcode`=?");
$stmt->bind_param('ssssissssssssis',$_POST['fname'],$_POST['sname'],$_POST['gender'],...);          
$stmt->execute();

I haven't included all the bound parameters for brevity.

Hope this helps.

Wednesday, March 31, 2021
 
hjalpmig
answered 9 Months ago
88

Delete your other question, ok?

The problem is you loop through $_SESSION and use the same name value each time. You need to create an array of your inputs. Here is an example:

<?php
echo '<h3>Your Order</h3>';
$current_url = base64_encode($url='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
  if(isset($_SESSION['products'])){
     echo '<ol>';
     echo '<form action="checkout_with_us.php" method="POST">';
     $total = 0;
     $cart_items = 0;

        foreach($_SESSION['products'] as $cart_itm){
           $product_code = $cart_itm['code'];
           $results = $mysqli->query("SELECT product_name,product_desc,price FROM products WHERE product_code='$product_code' LIMIT 1");
             $obj = $results->fetch_object();
                echo '<li>';
                echo 'Price: '.$currency.$obj->price;
                echo '<h4>'.$obj->product_name.'(Code: '.$product_code.')</h4>';
                echo 'Qty: '.$cart_itm['qty'];
                echo '</li>';

                   $subtotal = ($cart_itm['price'] * $cart_itm['qty']);
                     $total = ($total + $subtotal);
                     $cart_items++;
                       echo '<input type="hidden" name="product['.$product_code.'][item_name]" value="'.$obj->product_name.'">';
                       echo '<input type="hidden" name="product['.$product_code.'][item_desc]" value="'.$obj->product_desc.'">';
                       echo '<input type="hidden" name="product['.$product_code.'][item_qty]" value="'.$cart_itm["qty"].'">';
                       echo '<input type="hidden" name="product['.$product_code.'][item_code]" value="'.$product_code.'">';     
                }
                    echo '<strong>Sub Total: '.$currency.$total.'</strong>';
                    echo '<input type="hidden" name="product['.$product_code.'][price]" value="'.$total.'">';
                    echo '</ol>';   
                    }

//Here is the information of the customer
echo 'Firstname: <input type="text" name="firstname"><br />';
echo 'Lastname: <input type="text" name="lastname"><br />';
echo 'Email: <input type="text" name="email"><br />';
echo '<input type="submit" value="Send Step">';

echo '</form>';
?>

You can catch this by looping in your product array:

<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];

$conn = mysqli_connect('localhost','root','','sampsix')or die('Could not connect');

foreach($_POST['product'] as $product)
{
    $order_name = $product['item_name'];
    $order_code = $product['item_code'];
    $order_qty = $product['item_qty'];
    $sub_total = $product['price'];

    $query = "INSERT INTO `sampsix`.`orders`(`firstname`,`lastname`,`email`,`OrderName`,`OrderCode`,`OrderQty`,`SubTotal`) VALUES('$firstname','$lastname','$email','$order_name','$order_code','$order_qty','$sub_total')";
    mysqli_query($conn,$query);
}



mysqli_close($conn);

header('Location: checkout.php');
?>

I don't know what the purpose is of the table orders but with my example the products will be added to this table with the same firstname, lastname, etc.

Saturday, May 29, 2021
 
Ula
answered 7 Months ago
Ula
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share