2

How can i insert data from a html form to a table in Joomla database.
Sample code of the form:
Name : <input type="textbox" name="username"> Selection1 : <input type="checkbox" name="choice1" value="first"> Selection2 :<input type="checkbox" name="choice2" value="second"> Selection3: <input type="checkbox" name="choice3" value="third"> <input type="submit" value="submit" action="save_to_joomla_database.php"></form>

What's the script i need to write in save_to_joomla_database.php which will store the data in any specific table of the Joomla database?

2 Answers 2

5

You will first need to get the values using JInput like so,

$input = JFactory::getApplication()->input;
$username = $input->get('username');
$choice1 = $input->get('choice1');
$choice2 = $input->get('choice2');
$choice3 = $input->get('choice3');

then for your database query, you can use the following:

$db = JFactory::getDbo(); 
$query = $db->getQuery(true);

$columns = array('username', 'choice1', 'choice2', 'choice2');
$values = array($db->quote($username), $db->quote($choice1), $db->quote($choice2), $db->quote($choice3));

$query->insert($db->quoteName('#__table_name'))
      ->columns($db->quoteName($columns))
      ->values(implode(',', $values));

$db->setQuery($query);
$db->execute();

You will of course need to make some changes to the database query to suits your needs but this will get you started off

0
6

@Lodder is definitely correct, but there is another syntax for those who are interested. I prefer this syntax because it saves typing the field names as many times

$data = new stdClass;
$input = JFactory::getApplication()->input;
$data->username = $input->get('username');
$data->choice1 = $input->get('choice1');
$data->choice2 = $input->get('choice2');
$data->choice3 = $input->get('choice3');

$db = JFactory::getDbo(); 
$db->insertObject('#__table_name', $data);

As long as your object's properties match the column names exactly, you can just insert the object directly into the table using insertObject

1
  • +1 ... I've never actually used this method before so thanks for pointing it out as it looks much simpler.
    – Lodder
    May 28, 2014 at 18:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.