Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 11 Next capture
2021 2022 2023
1 capture
11 Jun 22 - 11 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by kenmarold · Jul 20, 2015 at 08:14 PM · unity5mysqlphp

Need guidance on saving an image to mySQL

I've been piecing a few things together but I've hit a bit of a snag. This is my first attempt at saving an image to a server. I'm including the components I have worked up so far. cs script, php file and my table setup. Right now I'm saving to server but I'm getting empty entries. Can someone show me how to set things up properly in my code?

How do I transfer 'bytes' (byte array in C# file) to the server and save it in the 'image' blob? How do I pass the form.AddBinaryData paramaters and store them in the table that I've created? Based on the code I have written above, can someone tell me why this isn't writing the screenshot to the MySQL DB? Could someone point out my errors?

---------- C# ----------

     public string screenShotCGIURL= "https://locomoku.com/projects/samnoble/animalmatch/php/upload.php";
 int yourInt;

 public void TakeScreenshot() 
 { 
     StartCoroutine("UploadPNG"); 
 }

 IEnumerator UploadPNG()
 {
     // We should only read the screen buffer after rendering is complete
     yield return new WaitForEndOfFrame();
     
     // Create a texture the size of the screen, RGB24 format
     int width = Screen.width;
     int height = Screen.height/2;
     Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
     
     // Read screen contents into the texture
     tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
     tex.Apply();
     
     // Encode texture into PNG
     byte[] bytes = tex.EncodeToPNG();
     Object.Destroy(tex);

     // Create a Web Form
     WWWForm form = new WWWForm();
 
     // Set file name
     string name = "animalmatch_" + System.DateTime.Now.ToString("MM-dd-yyyy_HH-mm-ss");
     name = name+".png";
     Debug.Log("The image name is " + name);

     // Calculate image size
     int size = tex.GetRawTextureData().Length;
     Debug.Log("The image size is " + size);

     // Upload to a cgi script
     WWW upload = new WWW(screenShotCGIURL, form);

     form.AddField("frameCount", Time.frameCount.ToString());

     form.AddField("image_id", "");
     form.AddField("image_type", "image/png");
     form.AddBinaryData("image", bytes, name, "image/png");
     form.AddField("image_size", size);
     form.AddField("image_name", name);

     yield return upload;

     Debug.Log(upload);

     if (!string.IsNullOrEmpty(upload.error)) {
         print(upload.error);
     }
     else {
         print("Finished Uploading Screenshot");
     }

 }

---------- PHP ----------

 $db_host         =     "localhost";     // MySQL Host Name.

 $db_user         =     "********";     // MySQL User Name.

 $db_password     =     "********";     // MySQL Password.

 $db_name         =     "********";     // MySQL Database Name.

 
 $imgData = file_get_contents($filename);
 $size = getimagesize($filename);
 
 mysql_connect("$db_host", "$db_user", "$db_password");
 mysql_select_db ("$db_name");
 
 $sql = "INSERT INTO screenshot
     (image_id ,image_type ,image, image_size, image_name)
     VALUES
     ('', '{$size['mime']}', '{$imgData}', '{$size[3]}', 
      '{$_FILES['userfile']['name']}')";
 
 mysql_query($sql);


----------mySQL ----------

 image_id        tinyint(6)  not null default '0',
 
 image_type      varchar(25) not null default '',
 
 image           largeblob   not null,
 
 image_size      varchar(25) not null default '',
 
 image_name      varchar(50) not null default ''

 
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by RKrogh · Mar 19, 2016 at 08:03 AM

I ran into the exact same problem when trying to upload .png from Unity to my database, but I found a way to solve it. Bear with me that I am new to this stuff so I am not sure if this is the perfect solution but it works:

Your C# script looks fine. Uploading the -png with the AddBinaryData looks similar to what I did. However, the entries never listed properly in the db. This is because what we get from the PHP-script's $_FILES['image'] is an array with the following attributes:

 $_FILES['userfile']['name']
 $_FILES['userfile']['tmp_name']
 $_FILES['userfile']['size']
 $_FILES['userfile']['type']

None of these attributes contain the content as we are looking for, right, only string of names and types and the like. So we have to open a file stream to extract our actual content, our png image.

Add the following to your PHP code:

 $tmpName  = $_FILES['image']['tmp_name'];
 
 $fp      = fopen($tmpName, 'r');
 $content = fread($fp, filesize($tmpName));
 $content = addslashes($content);
 fclose($fp);

Then add the $content variable in your SQL query as shown below:

 $query = "INSERT INTO screenshot (Image) VALUES ('$content')";
 mysqli_query($conn, $query) or die('Error, sql query failed');

This page and some whisky helped me solve it. Hope it can help you too if my solution is not an exact match to what you were looking for.

Good luck!

PS: I see you use your database connection settings in your php file. Many sites like W3schools and such still keep this up but if you are unlucky the information may leak.

You could replace that code with this:

 $config = parse_ini_file('../config/config.ini');

Then keep a config.ini in another inaccessible directory looking like this:

 [database]
 servername = ***
 username = ***
 password = ***
 dbname = ***

PHP have good support for ini-files. To make the directory inaccessible in an Apache environment you cold add a .htaccess script saying simply:

 Deny from all

DS

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by nisovin · Jul 21, 2015 at 05:48 AM

I believe you need to move your form.AddField() calls before you do the WWW call.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Using PHP to generate objects or list in Unity with C# 2 Answers

Retrieving data from a WWW php call? 1 Answer

can i use unity and php to develop a multi player game 2 Answers

Mysql PDO Register user insert not inserting, no error feedback 0 Answers

Upload audio file into mysql database 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges