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.
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.
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.
I am trying to create a web application by which you can add projects and any files relating to it. There is an angular table which displays the project information and I want to include one column which displays the number of files uploaded for each of the projects. The uploaded files are saved in a seperate directory. I have posted some parts of code so that you guys can get an idea about it.
<th><button type="button" id="show"># Of Files</button></th>
This is the table header for number of files which is a button.
<tr ng-repeat="project in allProjects >
<td> {{ ??? }} </td>
The above is table data to get the number of files for each project.
<input type="file" nv-file-select="" id="myFile" uploader="uploader" multiple />
<button type="button" id="file"> Upload</button>
Above is file input with a button to upload the files.
$scope.get_files = function(){
$http.post('core/engine.php?method=route', {'class':'Upload', 'function':'get_project_files', 'data':$scope.project.PROJECT_NAME})
.success(function(data){
if (data != 0) $scope.fileList = data;
})
}
Above is the code to upload the files.
static function get_project_files(){
if(!file_exists(self::$root . DIRECTORY_SEPARATOR . self::$data)){
mkdir(self::$root . DIRECTORY_SEPARATOR . self::$data);
} else {
return array_diff(scandir(self::$root . DIRECTORY_SEPARATOR . self::$data), array('..', '.'));
}
}
This makes a directory and saves the uploaded file in them.
$scope.get_count = function(){
var fi = document.getElementById('file');
return fi.files.length;
}
I have tried to write this part of code and pass it to the table data but it does not work.
Guys any help with this is really appreciated and thanks in advance. Please let me know if you want to know more about this code.
In order to get number of files you can simply add a function bind it with change event in the file as follows
<input type="file" multiple (change)="chooseFile($event.target.files)" />
Create a choose file function to get the number of the files selected by the user. The following code will do the task
chooseFile(file){
console.log(file.length)
}
The file is an array containing the total number of the files selected by the user.
im a bit new to this,
I have a model with an attribute file_id but it'll be displayed as File. I should make this mandatory..but when user uploads a file, I'm storing the file path and all in file table. and getting id from that table and storing it in my model.
can anyone pls tell me how can i make file upload mandatory for create but not for update
my code for file upload is:
<?php echo $form->labelEx($model,'file'); ?>
<?php echo $form->fileField($model, 'file');?>
<?php echo $form->error($model,'file'); ?>`
its working fine. but i need to make it mandatory for this current model. do i need to make it required in rules function in file model or current model??
Thanks,
The easiest way would be in the model rules:
array('file', 'required','on'=>'insert'),
Then it is only required on insert and not updates.
Another way would be to utilize the before or afterValidate method:
protected function afterValidate(){
if($this->isNewRecord){
if(!isset($this->file)){ //Not sure about handling files if this works.
$this->addError("file","Not file selected. Please choose a file to upload.");
return false;
}
}
return parent::afterValidate();
}
I am beginner to Joomla! development and have created a very simple module.
How do I create a form with 3 text fields and then save the entered values into a database table?
Try this example:
We will Post a user's first and last name to a table.
create a table in your database. Note it should have the prefix "jos_"
We will call this form, "names". So we will name our table "jos_names"
At the SQL line in PHPMyAdmin (or whatever tool you use..), do this query to create a new table:
CREATE TABLE `databasename`.`jos_names` (`id` int(11) NOT NULL auto_increment, `firstname` VARCHAR(100), `lastname` VARCHAR(100), PRIMARY KEY (`id`) )
To simplify things, we will post the results to the same page.. Let's build the form:
<?php
/** post form to db module **/
// No direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
//--POST YOUR FORM DATA HERE-->
$fname = $_POST['fname'];
$lname = $_POST['lname'];
//--END POST YOUR FORM DATA---|
//--build the form------------>
?>
<form name="names" id="names" action="<?php echo JURI::current(); ?>" method="post">
<p><input type="text" name="fname" id="fname" value="" /></p>
<p><input type="text" name="lname" id="lname" value="" /></p>
<p><input id="submit" name="submit" type="submit" value="Submit Names" /></p>
</form>
//--END BUILD THE FORM--------|
<?
if( (isset($lname)) || (isset($fname)) ) {
//first name or last name set, continue-->
$data =new stdClass();
$data->id = NULL;
$data->firstname = $fname;
$data->lastname = $lname;
$db = JFactory::getDBO();
$db->insertObject('#__names', $data, id);
} else {
echo '<h4>One Field Is Required!</h4>';
}
?>
That should do it. If you are writing a traditional Joomla module, this should be your helper.php file.
NOTES:
Only include the "die" script once in a joomla document.. (defined( '_JEXEC' )..
JURI::current() automatically reads the current page URL. If you call echo JURI::current(); on a page with the url http://www.example.com/names, then it will display the same link.
It is important that the action="" points to the exact Url where you will publish this module.
Furthermore, it is considered bad practice to post data to 'SELF', but you are kindof limited with a module, so unless you build a component or a plugin, you should post your form to 'SELF' as done with this example. (JURI::current();)
When in the Joomla framework, it isn't necessary to declare your database name, username or password as Joomla is already "logged in".. So instead of querying databasename.jos__tablename, in joomla you can replace the query with this: #__tablename. In fact this is the best practice when dealing with db queries and Joomla because users do not have to use the default jos_ prefix, joomla automatically replaces "#" with whatever the prefix. In my case "#" equals "jos"
Take note when querying the sql to create the table.. make sure you replace databasename with the actual name of your database..
That should do it.
If for some reason you are unable to post data:
1) Make sure the form doesn't redirect to a different page when you click submit. If it does, change the form action"" to the absolute url to where this page is published.. then go from there.
2) Sometimes the $data =new method doesn't work. This depends on how you set up your module, functions and classes.
Here is an alternative:
$db =& JFactory::getDBO();
$query = "INSERT INTO `#__names` (`fname`, `lname`)
VALUES ($fname, $lname);";
$db->setQuery( $query );
$db->query();
Try something like http://www.chronoengine.com/ - Chronoforms
You may run a custom query to get a result on tmpl file which is simple
<?php // no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
$category = $_REQUEST['category'];
if(isset($category))
{
$db = JFactory::getDbo();
$db->setQuery("SELECT machine_id FROM j25_machinefinder_products WHERE category = '$category'");
// Load the row.
$result = $db->loadRowList();
//your result will return here
print_r($result);
}
?>
<form action="" method="get" name="usedequipment">
<select name="category">
<?php foreach($hello as $category)
{
?><option value="<?php echo $category[0]; ?>"> <?php echo $category[0]; ?></option><?php
} ?>
</select>
<input type="submit" />
</form>