How to use Insert into query for joomla 2.5?

2020-03-30 07:01发布

I am using query for joomla.

$query = "INSERT INTO '#__demo'( 'id', 'fname', 'mname', 'lname' ) VALUES ( '$val', '$post['fname']', '$post['Mname']', '$post['Lname']' );";

It is giving error

syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING 

标签: php mysql joomla
3条回答
姐就是有狂的资本
2楼-- · 2020-03-30 07:23

There are two mistakes on your query.

  1. You haven't escaped your quotes in $_POST values.

    '$post['fname']'
    //     ^ here and other places
    
  2. You are using single quotes ' to represent tables and field names.

     .. INTO '#__demo'( ..       
    //       ^ here and other places
    

Now after removing all such problems. You query becomes:

$query = "INSERT INTO `#__demo` ( `id`, `fname`, `mname`, `lname` ) VALUES ( '$val', '$post[fname]', '$post[Mname]', '$post[Lname]' );";
查看更多
够拽才男人
3楼-- · 2020-03-30 07:32

For inserting the data you can use this format also in joomla 2.5 :

$data =new stdClass();
$data->id = null;
$data->field1 = 'val1';
$data->field2 = 'val2';
$data->field3 = 'val3';

$db = JFactory::getDBO();
$db->insertObject( '#__mytable', $data, id );

stdClass is a php base class from which all other classes are extended.

'id' is the name for your primary key for the connected table.

查看更多
Ridiculous、
4楼-- · 2020-03-30 07:42

You can use a more formatted way of writing insert query

$db = JFactory::getDBO(); // get the connection
$query = $db->getQuery(true);

$columns = array('field1','field2'); // set the column names to a variable 
$values = array(1,$db->quote('Your message'));

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

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

$tourid = $db->insertid(); // get the last inserted id

You can get the reference from here

https://docs.joomla.org/Inserting,_Updating_and_Removing_data_using_JDatabase

查看更多
登录 后发表回答