hi fellow programmers I am new in web programming, I have a task that I need to upload png files to sql database using url.
$connection = mysqli_connect ($db_host,$db_user,$db_pass);
mysqli_select_db($connection,$db_name);
$sql1 = "INSERT INTO figures (Id, Name, Image) VALUES ('".$_GET['id']."', '".$_GET['Name']."', '".$_GET['Image']."')";
mysqli_query($connection,$sql1);
Those lines used to send data , in this way I can upload VARCHAR to the database how ever I cannot upload png ,I don't know how to define file path here. (Maybe if you know easier solution for my task, could you please share it? )
Thanks in advance!!
First of all you need to set the sending form to multipart and also change the method to POST:
<form method="POST" action="uploader.php" enctype="multipart/form-data">
<input type="file" name="myfile">
<input type="text" name="id">
<input type="submit" value="Upload">
</form>
in PHP page you can get the file data using $_FILES:
// I dont know what is id here? shouldn't be the auto Primary key?
$id=$_POST['id'];
//Get name of file
$imageName=$_FILES["myfile"]["name"];
//Get the binary data of the image
$imageData= addslashes(file_get_contents($_FILES['myfile']['temp_name']));
$connection = mysqli_connect ($db_host,$db_user,$db_pass);
mysqli_select_db($connection,$db_name);
$sql1 = "INSERT INTO figures (Id, Name, ImageData) VALUES ('$id', '$imageName', '$imageData')";
mysqli_query($connection,$sql1);
Please note that the type of column imageData should be BLOB.
As you have mentioned the you are new to programming, I have to say that you have this option too to uplaod the file directly to the server and only save the url in database.
Related
I know this question is probably going to get downvoted and I will probably get into trouble but I am hoping someone may be able to help me with my situation.
On my site I use json to download data from an external source, and then I style it beautifully.
Within the json data is an individual ID for each data set.
What I want to accomplish is to have a database where I can insert the ID and a url link.
I have created the table within the wordpress database via phpMyAdmin, but I want to create a page within the admin section where I can simply add the data in.
For displaying the json data I use a php insert addon, within that php clip i want to do a piece of code that checks the database for the id within my custom database and displays the link.
I will be honest I don't know where to start on this, even if its just a link to a source that shows me how to create an admin page and submit data to the database within wordpress dashboard.
I really appreciate any help given and like I say I know I should try harder, but when ever I do a search all I get is 100's of references to add an admin to the database manually.
Thanks,
Adam
Edit I just realized I never put any table information in my question.
The table name within wordpress is called: wp_home_tickets
within that are 3 fields: id (auto increasement), gameid (numeric) and ticketlink (text)
thanks.
For adding a custom settings page in your admin, use the Settings API https://codex.wordpress.org/Settings_API
Here is a nice tutorial using it https://deliciousbrains.com/create-wordpress-plugin-settings-page/#wp-settings-api
To fetch data from your custom table, use the wpdb class https://developer.wordpress.org/reference/classes/wpdb/. More specifically, you can use wpdb::get_results if you will have multiple rows sharing the same id https://developer.wordpress.org/reference/classes/wpdb/get_results/
Or wpdb::get_row if you will ever only have one https://developer.wordpress.org/reference/classes/wpdb/get_row/
Hope this helps you out!
For anyone wishing to see how it was done, here is how I did it.
I created a file in my theme called db_admin_menu.php and added the following to it:
<?php
function ticket_admin_menu() {
global $team_page;
add_menu_page( __( 'Tickets', 'sports-bench' ), __( 'Tickets', 'sports-bench' ), 'edit_posts', 'add_data', 'ticket_page_handler', 'dashicons-groups', 6 ) ;
}
add_action( 'admin_menu', 'ticket_admin_menu' );
function ticket_page_handler() {
$table_name = 'wp_home_tickets';
global $wpdb;
echo '<form method="POST" action="?page=add_data">
<label>Team ID: </label><input type="text" name="gameid" /><br />
<label>Ticket Link: </label><input type="text" name="ticketlink" /><br />
<input type="submit" value="submit" />
</form>';
$default = array(
'gameid' => '',
'ticketlink' => '',
);
$item = shortcode_atts( $default, $_REQUEST );
$gameid = $item['gameid'];
if ($wpdb->get_var("SELECT * FROM wp_home_tickets WHERE gameid = $gameid ")) { echo 'Ticket already exists for this game.'; goto skip; }
if (!empty($_POST)) { $wpdb->insert( $table_name, $item ); }
skip:
}
?>
I then put this code in my script that fetches and displays the json:
$matchid = $match['id'];
$ticket_url = $wpdb->get_var("SELECT ticketlink FROM wp_home_tickets WHERE gameid = '$matchid' ");
if ($ticket_url) { echo 'Get Tickets'; }
I hope someone does find it of use, i did have to use a wordpress plugin called `Insert PHP Code Snippet' by xyzscripts to be able to snippet the php to a shortcode, but that is not the purpose of this post.
Thanks again for your help.
I've created a custom table on database and I need to upload image from my template page member. In this page I've done all the codings. I'm able to insert data but stuck on the image insert. I can get the file name but unable to get the extension.
Here is my inserting code of my template file.
$tmpfile = explode(".", $_FILES['image']['name']);
$newfile = round(microtime(true)) . '.' . end($tmpfile);
move_uploaded_file($_FILES['image']['tmp_name'], ABSPATH . '/wp-content/themes/themename/inc/images/' . $newfile);
$sql = $wpdb->query($wpdb->prepare("INSERT INTO members(member_image) VALUES (%s)", $newfile));
The above code shows the field value without extension as: https://screenshots.firefox.com/w7aDRfXESHZEw39s/localhost
Here is my html form field:
<form action="" method="post">
<input type="file" name="image" class="form-control">
</form>
All other text fields are inserted but only image can't be derived with extension. I can't figure out the problem. I've also tried by adding .jpg extension but it didn't work.
Is there a web2py way of displaying images from a database table?
Example:
The model:
db.define_table=('images',Field('picture', 'upload' ))
The controller:
def somefunction(): to get the image.
How exactly should I "read" a picture from the database?
The view:
<img src="{{somefunction}}" />
As is, your model will not store the image in the database -- instead, it will store the image on the filesystem, with its new filename stored in the database (in the 'picture' field). If you want to store the image itself in the database, use the following:
db.define_table('images',
Field('picture', 'upload', uploadfield='picture_file')
Field('picture_file', 'blob'))
Whether you store the images on the filesystem or in the database, you can use the same method to retrieve them. The 'welcome' scaffolding application includes the following download() action in the default.py controller:
def download():
return response.download(request, db)
To retrieve an image, just do something like:
<img src="{{=URL('default', 'download', args=picture_name)}}" />
where picture_name is the value stored in the 'picture' field of the 'images' table for the particular image you want to retrieve.
For more details, see here and here.
If you need further help, try asking on the mailing list.
Alternatively, if you use web2py's default way of uploading images as files, you can use:
In models:
db.define_table('images',Field('picture','upload'))
In controllers:
def somefunction():
pic = db(db.images).select().first().picture #select first picture
return dict(pic=pic)
And in the default/somefunction.html view:
{{extend 'layout.html'}}
<img src="{{=URL( 'download', args=pic)}}" />
I know this is a while after the original question but thought it might be useful as it took me a while to figure out.
I wanted to know if I was uploading an image in CodeIgniter to a database what would be my
$config['upload_path']
All the examples I have seen are using the filesystem. I have articles in a db and would like to store images relating to articles in the db as well. Can anyone help?
You can read this great article called Storing Images in Mysql.
The article covers the following:
Isn’t this a bad idea?
What is a BLOB?
Creating an image table
The upload form
Uploading the image
The upload() function
Display an image from the database
Displaying all the information
But not to leave you empty handed, look into Blob, it's a data-type for colums in MySQL ( and various other dbms ). This will let you store data such as Images and other binary file-types.
The idea of storing files and images in the database is in general the same as storing them on the filesystem, the layer in-between upload and having the actual file is just different.
You cannot just set your upload-path and hope everything is solved, you need to get some dirt on your hands aswell!
i posted here in hope this help someone since this is an old post and the answers are no help at all, this code works for me, also the model part is not here so you must figure it out reading codeigniter's docs , i think this will work if you put it in your controller, also it think the submit form must be pointing this function
function upload() {
$caption = $this->input->post('caption');
$codigo = $this->input->post('codigo');
//$imagen = $this->input->post('imagen');
$config['upload_path'] = 'uploads';// this is a directory with 777 permissions where you upload the file
$config['allowed_types'] = 'gif|jpg|jpeg|png|pdf';
//$config['max_size'] = '5000';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('imagen')) { // this is the input from the form
echo $this->upload->display_errors();
} else {
//here $file_data receives an array that has all the info
//pertaining to the upload, including 'file_name'
$file_data = $this->upload->data();
$fp = fopen($file_data['full_path'], 'r');
$content = fread($fp, filesize($file_data['full_path']));
//$content = addslashes($content);
fclose($fp);
$data = array( // this is the table i got in my db
'idBotones' => null,
'imagen' => $content, //blob image
'caption' => $caption,
'codigo' => $codigo
);
$this->load->model('generic_model');
$table = "botones";
$this->generic_model->insertar_datos($table, $data);
//print_r($content);
}
}
It seems like for most common use cases storing images in the database is not a great idea.
Please see these two previous SO threads:
To Do or Not to Do: Store Images in a Database
Storing Images in DB - Yea or Nay?
Has anyone tried to dynamically select which properties they want to write to an entity on appengine? For example:
I have a web form with 5 fields, and any given user will fill out some subset of those fields. I POST only the fields with data to the server (e.g. Fields 1,2,4). On the server side, how do I elegantly write only properties 1,2, and 4? The Model class has a function that returns a dictionary of property names (Model.properties()), but how would I use it to select property names?
In SQL, I would build an INSERT or UPDATE statement by matching the fields POSTed against the Model.properties() dictionary. I would look at the db module code in the Appengine SDK, to see if the Model class had some collection of Property objects, but I can't find the module on my disk (I'm a little new to python and appengine).
Update: I read trunk/google/appengine/ext/db/init.py which confirmed that there is no way to refer to the properties as a group. Anyone know of a workaround?
Any thoughts?
Update2: This question was answered on the Google Group for AppEngine: http://groups.google.com/group/google-appengine/browse_thread/thread/b50be862f6d94b6e#
The python module will look something like this:
from google.appengine.ext.db import Key
from google.appengine.api.datastore import Get, Put
def edit_item(request, db_id):
objKey = Key(str(db_id))
if request.method == 'POST':
objEntity = Get(objKey)
for k, v in request.POST.iteritems():
objEntity[k]=v
Put(objEntity)
return HttpResponseRedirect('/')
query = TestModel.get(objKey)
return render_to_response('edit.html', ({'modify_data': query,}))
Your HTML should look something like this:
<form method="POST" action="." enctype="multipart/form-data">
Title: <input type="text" name="title" value="{{modify_data.field1}}"/>
Text: <input type="text" name="txt" value="{{modify_data.field2}}"/>
<input type="submit"/>
</form>